hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
4fc61785d539301a5bf5e7f22e9874d42e41392f
8,320
hpp
C++
cuML/src/glm/glm.hpp
venkywonka/cuml
c0b4a4b0cc2a24ca49b22363f23363d91538fbd1
[ "Apache-2.0" ]
null
null
null
cuML/src/glm/glm.hpp
venkywonka/cuml
c0b4a4b0cc2a24ca49b22363f23363d91538fbd1
[ "Apache-2.0" ]
null
null
null
cuML/src/glm/glm.hpp
venkywonka/cuml
c0b4a4b0cc2a24ca49b22363f23363d91538fbd1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <common/cumlHandle.hpp> namespace ML { namespace GLM { /** * @defgroup Functions fit an ordinary least squares model * @param input device pointer to feature matrix n_rows x n_cols * @param n_rows number of rows of the feature matrix * @param n_cols number of columns of the feature matrix * @param labels device pointer to label vector of length n_rows * @param coef device pointer to hold the solution for weights of size n_cols * @param intercept device pointer to hold the solution for bias term of size 1 * @param fit_intercept if true, fit intercept * @param normalize if true, normalize data to zero mean, unit variance * @param algo specifies which solver to use (0: SVD, 1: Eigendecomposition, 2: QR-decomposition) * @{ */ void olsFit(float *input, int n_rows, int n_cols, float *labels, float *coef, float *intercept, bool fit_intercept, bool normalize, int algo = 0); void olsFit(double *input, int n_rows, int n_cols, double *labels, double *coef, double *intercept, bool fit_intercept, bool normalize, int algo = 0); /** @} */ /** * @defgroup Functions fit a ridge regression model (l2 regularized least squares) * @param input device pointer to feature matrix n_rows x n_cols * @param n_rows number of rows of the feature matrix * @param n_cols number of columns of the feature matrix * @param labels device pointer to label vector of length n_rows * @param alpha device pointer to parameters of the l2 regularizer * @param n_alpha number of regularization parameters * @param coef device pointer to hold the solution for weights of size n_cols * @param intercept device pointer to hold the solution for bias term of size 1 * @param fit_intercept if true, fit intercept * @param normalize if true, normalize data to zero mean, unit variance * @param algo specifies which solver to use (0: SVD, 1: Eigendecomposition) * @{ */ void ridgeFit(float *input, int n_rows, int n_cols, float *labels, float *alpha, int n_alpha, float *coef, float *intercept, bool fit_intercept, bool normalize, int algo = 0); void ridgeFit(double *input, int n_rows, int n_cols, double *labels, double *alpha, int n_alpha, double *coef, double *intercept, bool fit_intercept, bool normalize, int algo = 0); /** @} */ /** * @defgroup Functions to make predictions with a fitted ordinary least squares and ridge regression model * @param input device pointer to feature matrix n_rows x n_cols * @param n_rows number of rows of the feature matrix * @param n_cols number of columns of the feature matrix * @param coef weights of the model * @param intercept bias term of the model * @param preds device pointer to store predictions of size n_rows * @{ */ void olsPredict(const float *input, int n_rows, int n_cols, const float *coef, float intercept, float *preds); void olsPredict(const double *input, int n_rows, int n_cols, const double *coef, double intercept, double *preds); void ridgePredict(const float *input, int n_rows, int n_cols, const float *coef, float intercept, float *preds); void ridgePredict(const double *input, int n_rows, int n_cols, const double *coef, double intercept, double *preds); /** @} */ /** * @defgroup functions to fit a GLM using quasi newton methods. * @param cuml_handle reference to cumlHandle object * @param X device pointer to feature matrix of dimension * NxD (row- or column major: see X_col_major param) * @param y device pointer to label vector of length N (for * binary logistic: [0,1], for multinomial: [0,...,C-1]) * @param N number of examples * @param D number of features * @param C number of outputs (C > 1, for multinomial, * indicating number of classes. For logistic and normal, C must be 1.) * @param fit_intercept true if model should include a bias. If true, * the initial point/result w0 should point to a memory location of size (D+1) * * C * @param l1 l1 regularization strength (if non-zero, will * run OWL-QN, else L-BFGS). Note, that as in scikit, the bias will not be * regularized. * @param l2 l2 regularization strength. Note, that as in * scikit, the bias will not be regularized. * @param max_iter limit on iteration number * @param grad_tol tolerance for gradient norm convergence check * @param linesearch_max_iter max number of linesearch iterations per outer * iteration * @param lbfgs_memory rank of the lbfgs inverse-Hessian approximation. * Method will request memory of size O(lbfgs_memory * D). * @param verbosity verbosity level * @param w0 device pointer of size (D + (fit_intercept ? 1 : * 0)) * C with initial point, overwritten by final result. * @param f host pointer holding the final objective value * @param num_iters host pointer holding the actual number of * iterations taken * @param X_col_major true if X is stored column-major, i.e. feature * columns are contiguous * @param loss_type id of likelihood model (0: logistic/sigmoid, 1: * multinomial/softmax, 2: normal/squared) * @{ */ void qnFit(const cumlHandle &cuml_handle, float *X, float *y, int N, int D, int C, bool fit_intercept, float l1, float l2, int max_iter, float grad_tol, int linesearch_max_iter, int lbfgs_memory, int verbosity, float *w0, float *f, int *num_iters, bool X_col_major, int loss_type); void qnFit(const cumlHandle &cuml_handle, double *X, double *y, int N, int D, int C, bool fit_intercept, double l1, double l2, int max_iter, double grad_tol, int linesearch_max_iter, int lbfgs_memory, int verbosity, double *w0, double *f, int *num_iters, bool X_col_major, int loss_type); /** @} */ /** * @defgroup functions to fit a GLM using quasi newton methods. * @param cuml_handle reference to cumlHandle object * @param X device pointer to feature matrix of dimension NxD (row- or column major: see X_col_major param) * @param N number of examples * @param D number of features * @param C number of outputs (C > 1, for multinomial, indicating number of classes. For logistic and normal, C must be 1.) * @param fit_intercept true if model includes a bias. * @param params device pointer to model parameters. Length D if fit_intercept == false else D+1 * @param X_col_major true if X is stored column-major, i.e. feature columns are contiguous * @param loss_type id of likelihood model (0: logistic/sigmoid, 1: multinomial/softmax, 2: normal/squared) * @param preds device pointer to predictions of length N (for binary logistic: [0,1], for multinomial: [0,...,C-1]) */ void qnPredict(const cumlHandle &cuml_handle, float *X, int N, int D, int C, bool fit_intercept, float *params, bool X_col_major, int loss_type, float *preds); void qnPredict(const cumlHandle &cuml_handle, double *X, int N, int D, int C, bool fit_intercept, double *params, bool X_col_major, int loss_type, double *preds); /** @} */ } // namespace GLM } // namespace ML
51.358025
143
0.66226
[ "object", "vector", "model" ]
4fc6f437d8c97f5cf5071dd34c2c7bc36671c90a
3,399
cpp
C++
src/tests/test_name_constraint.cpp
tiwoc/botan
6b7e1ba04d394aa7feaee22e859c29264280bf4e
[ "BSD-2-Clause" ]
1
2017-03-21T14:32:53.000Z
2017-03-21T14:32:53.000Z
src/tests/test_name_constraint.cpp
tiwoc/botan
6b7e1ba04d394aa7feaee22e859c29264280bf4e
[ "BSD-2-Clause" ]
null
null
null
src/tests/test_name_constraint.cpp
tiwoc/botan
6b7e1ba04d394aa7feaee22e859c29264280bf4e
[ "BSD-2-Clause" ]
null
null
null
/* * (C) 2015,2016 Kai Michaelis * * Botan is released under the Simplified BSD License (see license.txt) */ #include "tests.h" #if defined(BOTAN_HAS_X509_CERTIFICATES) #include <botan/x509path.h> #include <botan/calendar.h> #endif #include <algorithm> #include <fstream> #include <iomanip> #include <string> #include <vector> #include <map> #include <cstdlib> namespace Botan_Tests { namespace { #if defined(BOTAN_HAS_X509_CERTIFICATES) class Name_Constraint_Tests : public Test { public: std::vector<Test::Result> run() override { const std::vector<std::tuple<std::string, std::string, std::string, std::string>> test_cases = { std::make_tuple( "Root_Email_Name_Constraint.crt", "Invalid_Email_Name_Constraint.crt", "Invalid Email Name Constraint", "Certificate does not pass name constraint"), std::make_tuple( "Root_DN_Name_Constraint.crt", "Invalid_DN_Name_Constraint.crt", "Invalid DN Name Constraint", "Certificate does not pass name constraint"), std::make_tuple( "Root_DN_Name_Constraint.crt", "Valid_DN_Name_Constraint.crt", "Valid DN Name Constraint", "Verified"), std::make_tuple( "Root_DNS_Name_Constraint.crt", "Valid_DNS_Name_Constraint.crt", "aexample.com", "Verified"), std::make_tuple( "Root_IP_Name_Constraint.crt", "Valid_IP_Name_Constraint.crt", "Valid IP Name Constraint", "Verified"), std::make_tuple( "Root_IP_Name_Constraint.crt", "Invalid_IP_Name_Constraint.crt", "Invalid IP Name Constraint", "Certificate does not pass name constraint"), }; std::vector<Test::Result> results; const Botan::Path_Validation_Restrictions restrictions(false, 80); std::chrono::system_clock::time_point validation_time = Botan::calendar_point(2016, 10, 21, 4, 20, 0).to_std_timepoint(); for(const auto& t : test_cases) { Botan::X509_Certificate root(Test::data_file("name_constraint/" + std::get<0>(t))); Botan::X509_Certificate sub(Test::data_file("name_constraint/" + std::get<1>(t))); Botan::Certificate_Store_In_Memory trusted; Test::Result result("X509v3 Name Constraints: " + std::get<1>(t)); trusted.add_certificate(root); Botan::Path_Validation_Result path_result = Botan::x509_path_validate( sub, restrictions, trusted, std::get<2>(t), Botan::Usage_Type::TLS_SERVER_AUTH, validation_time); if(path_result.successful_validation() && path_result.trust_root() != root) { path_result = Botan::Path_Validation_Result(Botan::Certificate_Status_Code::CANNOT_ESTABLISH_TRUST); } result.test_eq("validation result", path_result.result_string(), std::get<3>(t)); results.push_back(result); } return results; } }; BOTAN_REGISTER_TEST("x509_path_name_constraint", Name_Constraint_Tests); #endif } }
32.682692
115
0.593704
[ "vector" ]
4fca86ec5aea1d8eb91721f2e3c52a5880f80d99
14,608
cpp
C++
TheMenus.cpp
Dozed12/AEDAProject
52fdbe810a76ffb1cd63a447bd4f1eb0d81681ca
[ "MIT" ]
null
null
null
TheMenus.cpp
Dozed12/AEDAProject
52fdbe810a76ffb1cd63a447bd4f1eb0d81681ca
[ "MIT" ]
null
null
null
TheMenus.cpp
Dozed12/AEDAProject
52fdbe810a76ffb1cd63a447bd4f1eb0d81681ca
[ "MIT" ]
null
null
null
#include "TheMenus.h" #include "Tools.h" #include "Date.h" unsigned short int InicialMenu() { unsigned short int TheOption; cout << endl << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "Main Menu:\n" << endl; cout << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "1 - Student Managment\n" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "2 - Uc Managment\n" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "3 - Tutor Managment\n" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "4 - Registration Managment\n" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "5 - Class Managment\n" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "6 - Exit Program\n" << endl << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "Please select an option: "; TheOption = ReadUnsignedShortInt(1, 6); //Chamada da funcao ReadUnsignedShortInt que verifica se opcao se encontrar entre 1 e 6 clearScreen(); if (TheOption == 6) return 0; return TheOption; } void InicialOptions(Mieic & TheCourse) { unsigned int Option; while ((Option = InicialMenu())) switch (Option) { case 1: StudentManagmentOptions(TheCourse); break; case 2: UcManagmentOptions(TheCourse); break; case 3: TutorManagmentOptions(TheCourse); break; case 4: RegistrationManagmentOptions(TheCourse); break; case 5: ClassManagmentOptions(TheCourse); break; } } unsigned short int StudentManagmentMenu() { unsigned short int Option; cout << endl << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "Student Managment Menu" << endl; cout << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "1 - List Students" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "2 - List of Students Who Have Finished or Interrupted the Course" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "3 - See Information About a Single Student" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "4 - Add Student" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "5 - Makes Changes to a Student" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "6 - Remove Student" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "7 - Studant Passes Uc" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "8 - Studant Doesn't Pass Uc" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "9 - Student Interrupts Course" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "10 - Go Back to Inicial Menu" << endl << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "Input your Option: "; Option = ReadUnsignedShortInt(1, 10); //Chamada da funcao ReadUnsignedShortInt que verifica se opcao se encontrar entre 1 e 10 clearScreen(); if (Option == 10) { return 0; } return Option; } void StudentManagmentOptions(Mieic & TheCourse) { unsigned int Option; while ((Option = StudentManagmentMenu())) switch (Option) { case 1:TheCourse.showListofStudents(); break; case 2:TheCourse.showListofIorTStudents(); break; case 3: { long code; cout << TAB_BIG << "Student Info:" << endl; cout << endl << "Please insert the code of the student (no up prefix needed):\n\nCode: "; cin >> code; while (cin.fail()) { cout << "Error. Please input a valid Code." << endl; //Se o input for invalido volta a pedir um novo Code cin.clear(); cin.ignore(256, '\n'); cin >> code; } TheCourse.showInfoStudent(code); } break; case 4: TheCourse.addStudent(); break; case 5: { long TheCcode; cout << TAB_BIG << "Make Changes to a Student:" << endl; cout << endl << "Please insert the code of the student you want to make changes to (no up prefix needed):\n\nCode:" << TAB; cin >> TheCcode; while (cin.fail()) { cout << "Error. Please input a valid Code." << endl; //Se o input for invalido volta a pedir um novo Code cin.clear(); cin.ignore(256, '\n'); cin >> TheCcode; } bool isThereStudent = false; vector <Student> TheListofStudents = TheCourse.getListofStudents(); for (unsigned int i = 0; i < TheListofStudents.size(); i++) { if (TheListofStudents[i].getCode() == TheCcode) { isThereStudent = true; break; } } if (isThereStudent == false) { TheCourse.changeStudentsFromHash(TheCcode); } else { TheCourse.changeStudentFromList(TheCcode); } } break; case 6: { long TheRcode; cout << TAB_BIG << "Remove Student:" << endl; cout << endl << "Please insert the code of the student you want to remove (no up prefix needed):\n\nCode:" << TAB; cin >> TheRcode; while (cin.fail()) { cout << "Error. Please input a valid Code." << endl; //Se o input for invalido volta a pedir um novo Code cin.clear(); cin.ignore(256, '\n'); cin >> TheRcode; } TheCourse.removeStudent(TheRcode); } break; case 7: { long code; cout << TAB_BIG << "Student's Passed UC's Register:" << endl; cout << endl << "Please insert the code of the student (no up prefix needed):\n\nCode:" << TAB; cin >> code; while (cin.fail()) { cout << "Error. Please input a valid Code." << endl; //Se o input for invalido volta a pedir um novo Code cin.clear(); cin.ignore(256, '\n'); cin >> code; } TheCourse.StudentPassesUc(code); } break; case 8: { long code; cout << TAB_BIG << "Student's Failed UC's Register:" << endl; cout << endl << "Please insert the code of the student (no up prefix needed)\n\nCode:" << TAB; cin >> code; while (cin.fail()) { cout << "Error. Please input a valid Code." << endl; //Se o input for invalido volta a pedir um novo Code cin.clear(); cin.ignore(256, '\n'); cin >> code; } TheCourse.StudentDoesntPassUc(code); } break; case 9: { long code; cout << endl << "Please insert the code of the student (no up prefix needed)\n\nCode:" << TAB; cin >> code; while (cin.fail()) { cout << "Error. Please input a valid Code." << endl; //Se o input for invalido volta a pedir um novo Code cin.clear(); cin.ignore(256, '\n'); cin >> code; } TheCourse.StudentInterruptsCourse(code); } break; } } unsigned short int UcManagmentMenu() { unsigned short int Option; cout << endl << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "Uc Managment Menu" << endl << endl; cout << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "1 - List Required Uc's" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "2 - List Optional Uc's" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "3 - List All Uc's" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "4 - Search UC" << endl; cout << endl << TAB << TAB_BIG << TAB_BIG << "Uc Costumized Search:" << endl << endl; cout << TAB << TAB << TinyTAB << TAB_BIG << TAB_BIG << TAB_BIG << "5 - List all 1st Year Uc's" << endl; cout << TAB << TAB << TinyTAB << TAB_BIG << TAB_BIG << TAB_BIG << "6 - List all 2nd Year Uc's" << endl; cout << TAB << TAB << TinyTAB << TAB_BIG << TAB_BIG << TAB_BIG << "7 - List all 3rd Year Uc's" << endl; cout << TAB << TAB << TinyTAB << TAB_BIG << TAB_BIG << TAB_BIG << "8 - List all 4th Year Uc's" << endl; cout << TAB << TAB << TinyTAB << TAB_BIG << TAB_BIG << TAB_BIG << "9 - List all 5th Year Uc's" << endl; cout << TAB << TAB << TinyTAB << TAB_BIG << TAB_BIG << TAB_BIG << "10 - List all 1st Semester Uc's" << endl; cout << TAB << TAB << TinyTAB << TAB_BIG << TAB_BIG << TAB_BIG << "11 - List all 2nd Semester Uc's" << endl << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "12 - Go Back to Inicial Menu" << endl << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "Input your Option: "; Option = ReadUnsignedShortInt(1, 12); //Chamada da funcao ReadUnsignedShortInt que verifica se opcao se encontrar entre 1 e 12 clearScreen(); if (Option == 12) return 0; return Option; } void UcManagmentOptions(Mieic & TheCourse) { unsigned int Option; while ((Option = UcManagmentMenu())) switch (Option) { case 1: TheCourse.showListofRUcs(); break; case 2: TheCourse.showListofOUcs(); break; case 3: TheCourse.showListAllUcs(); break; case 4: { cout << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "UCs Search:" << endl; cout << endl << TAB_BIG << "Please insert the AKA of the UC you want to search:" << TAB; string AKA; cin >> AKA; TheCourse.showSearchUC(AKA); } break; case 5: TheCourse.showListofFirstYearUcs(); break; case 6: TheCourse.showListofSecondYearUcs(); break; case 7: TheCourse.showListofThirdYearUcs(); break; case 8: TheCourse.showListofFourthYearUcs(); break; case 9: TheCourse.showListofFifthYearUcs(); break; case 10: TheCourse.showListofFirstSemesterUcs(); break; case 11: TheCourse.showListofSecondSemesterUcs(); break; } } unsigned short int TutorManagmentMenu() { unsigned short int Option; cout << endl << endl << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "Tutor Managment Menu" << endl; cout << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "1 - Add Tutor" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "2 - Remove Tutor" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "3 - List all Tutors" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "4 - Schedule a Reunion" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "5 - Cancel a Reunion" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "6 - Change Reunion's Topics" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "7 - Show Tutor's Reunions" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "8 - Go Back to Inicial Menu" << endl << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "Input your Option: "; Option = ReadUnsignedShortInt(1, 8); //Chamada da funcao ReadUnsignedShortInt que verifica se opcao se encontrar entre 1 e 7 clearScreen(); if (Option == 8) return 0; return Option; } void TutorManagmentOptions(Mieic & TheCourse) { unsigned int Option; while ((Option = TutorManagmentMenu())) switch (Option) { case 1: { string name; cout << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "New Tutor" << endl; cout << endl << TAB_BIG << TAB_BIG << "Please enter the name of the new Tutor:" << TAB; getline(cin, name); TheCourse.addTutor(name); } break; case 2: TheCourse.removeTutor(); break; case 3: TheCourse.showListofTutors(); break; case 4: TheCourse.addTutorReunion(); break; case 5:TheCourse.removeTutorReunion(); break; case 6: TheCourse.changeTutorReunion(); break; case 7: TheCourse.showTutorReunions(); break; } } unsigned short int RegistrationManagmentMenu() { unsigned short int Option; cout << endl << endl << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "Registration Managment Menu" << endl; cout << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "1 - Make Registration" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "2 - List all Registrations" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "3 - Go Back to Inicial Menu" << endl << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "Input your Option: "; Option = ReadUnsignedShortInt(1, 3); //Chamada da funcao ReadUnsignedShortInt que verifica se opcao se encontrar entre 1 e 5 clearScreen(); if (Option == 3) return 0; return Option; } void RegistrationManagmentOptions(Mieic & TheCourse) { unsigned int Option; while ((Option = RegistrationManagmentMenu())) switch (Option) { case 1: { long aStudent; cout << endl << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "New Registration" << endl; cout << endl << TAB_BIG << "Please insert the code of the student (no up prefix needed):\n\nCode:" << TAB; cin >> aStudent; while (cin.fail()) { cout << "Error. Please input a valid Code." << endl; //Se o input for invalido volta a pedir um novo Code cin.clear(); cin.ignore(256, '\n'); cin >> aStudent; } bool isThereStudent = false; vector <Student> TheListofStudents = TheCourse.getListofStudents(); for (unsigned int i = 0; i < TheListofStudents.size(); i++) { if (TheListofStudents[i].getCode() == aStudent) { isThereStudent = true; break; } } if (isThereStudent == true) { string aUc; cout << TAB_BIG << "\nPlease insert the initials of the Uc" << TAB; cin >> aUc; string TheDate; cout << "\nPlease insert the date of the Registration [in the format DD/MM/YYYY]: " << TAB; cin >> TheDate; Date aDate(TheDate); TheCourse.addRegistration(aDate, aUc, aStudent); } else { string aUc; cout << TAB_BIG << "\nPlease insert the initials of the Uc" << TAB; cin >> aUc; string TheDate; cout << "\nPlease insert the date of the Registration [in the format DD/MM/YYYY]: " << TAB; cin >> TheDate; Date aDate(TheDate); TheCourse.addHashRegistration(aDate, aUc, aStudent); } } break; case 2: TheCourse.showListofRegistrations(); break; } } unsigned short int ClassManagmentMenu() { unsigned short int Option; cout << endl << TAB_BIG << TAB_BIG << TAB_BIG << TAB_BIG << "Class Managment Menu" << endl; cout << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "1 - View Classes" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "2 - Add Class" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "3 - Remove Class" << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "4 - Go Back to Inicial Menu" << endl << endl; cout << TAB << TAB_BIG << TAB_BIG << TAB_BIG << "Input your Option: "; Option = ReadUnsignedShortInt(1, 4); //Chamada da funcao ReadUnsignedShortInt que verifica se opcao se encontrar entre 1 e 5 clearScreen(); if (Option == 4) return 0; return Option; } void ClassManagmentOptions(Mieic & TheCourse) { unsigned int Option; while ((Option = ClassManagmentMenu())) switch (Option) { case 1: TheCourse.showListofClasses(); break; case 2: TheCourse.addClass(); break; case 3: TheCourse.removeClass(); break; } }
32.680089
130
0.609324
[ "vector" ]
4fca981c6a59cdb91a997e6a887fd26472c1a10a
36,750
cc
C++
tensorflow/compiler/xla/service/heap_simulator.cc
fraudies/tensorflow
a42423e302b71893bbd24aa896869941013c07fb
[ "Apache-2.0" ]
36
2016-12-17T15:25:25.000Z
2022-01-29T21:50:53.000Z
tensorflow/compiler/xla/service/heap_simulator.cc
shekharpalit/tensorflow
6aa83398ab03bfae822f36772757097bcb98b6ed
[ "Apache-2.0" ]
59
2019-06-17T09:37:49.000Z
2022-01-19T01:21:34.000Z
tensorflow/compiler/xla/service/heap_simulator.cc
shekharpalit/tensorflow
6aa83398ab03bfae822f36772757097bcb98b6ed
[ "Apache-2.0" ]
36
2017-07-27T21:12:40.000Z
2022-02-03T16:45:56.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/heap_simulator.h" #include <algorithm> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/memory/memory.h" #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/util.h" namespace xla { using absl::flat_hash_map; using absl::flat_hash_set; /*static*/ StatusOr<int64> HeapSimulator::MinimumMemoryForModule( const HloSchedule& schedule, const LogicalBuffer::SizeFunction& size_function) { if (schedule.empty()) { return 0; } const HloModule* module = schedule.module(); TF_ASSIGN_OR_RETURN(std::unique_ptr<TuplePointsToAnalysis> points_to_analysis, TuplePointsToAnalysis::Run(module)); // The absolute minimum memory required for a given sequence of instructions // is determined by the sequence of Alloc and Free calls on a simulated heap, // ignoring fragmentation. We run the heap simulation on the whole module, // rather than summing each computation, since it gives us a better lower // bound, by minimizing the liveness of sub-computations. TF_ASSIGN_OR_RETURN( HeapSimulator::Result result, HeapSimulator::Run(absl::make_unique<NoFragmentationStatsHeap>(), *module, schedule, *points_to_analysis, size_function)); return result.heap_size; } /*static*/ StatusOr<int64> HeapSimulator::MinimumMemoryForComputation( const HloComputation& computation, const HloInstructionSequence& sequence, const TuplePointsToAnalysis& points_to_analysis, const LogicalBuffer::SizeFunction& size_function, const absl::flat_hash_map<const HloComputation*, int64>* memory_by_computation) { TF_ASSIGN_OR_RETURN( HeapSimulator::Result result, HeapSimulator::Run(absl::make_unique<NoFragmentationStatsHeap>(), computation, sequence, points_to_analysis, size_function, HeapSimulator::Options(), memory_by_computation)); return result.heap_size; } /*static*/ StatusOr<HeapSimulator::Result> HeapSimulator::Run( std::unique_ptr<HeapAlgorithm> algorithm, const HloModule& module, const HloSchedule& schedule, const TuplePointsToAnalysis& points_to_analysis, const BufferValue::SizeFunction& size_fn, const Options& options) { HeapSimulator heap(std::move(algorithm), size_fn, options, &schedule); const HloComputation* entry_computation = module.entry_computation(); const HloInstructionSequence& instruction_sequence = schedule.sequence(entry_computation); TF_RETURN_IF_ERROR(heap.RunComputation( *entry_computation, instruction_sequence, points_to_analysis)); return heap.Finish(); } /*static*/ StatusOr<HeapSimulator::Result> HeapSimulator::Run( std::unique_ptr<HeapAlgorithm> algorithm, const HloComputation& computation, const HloInstructionSequence& instruction_sequence, const TuplePointsToAnalysis& points_to_analysis, const BufferValue::SizeFunction& size_fn, const Options& options, const absl::flat_hash_map<const HloComputation*, int64>* memory_by_computation) { HeapSimulator heap(std::move(algorithm), size_fn, options, /*schedule=*/nullptr, memory_by_computation); TF_RETURN_IF_ERROR(heap.RunComputation(computation, instruction_sequence, points_to_analysis)); return heap.Finish(); } // Runs a heap simulation for the given 'computation', assuming the given // 'instruction_sequence'. Status HeapSimulator::RunComputation( const HloComputation& computation, const HloInstructionSequence& instruction_sequence, const TuplePointsToAnalysis& points_to_analysis) { VLOG(3) << "Computation:\n" << computation.ToString(); // The goal here is to minimize memory usage, assuming the given sequential // ordering of instructions. The strategy is to walk through the instruction // sequence, calling Alloc and Free on the underlying heap algorithm. The // heap algorithm takes care of packing and reducing fragmentation. // // 'live_buffers' tracks the liveness of each buffer that we assign, by // associating it with a set of HloInstructions that need to be visited. When // the set becomes empty, the buffer is no longer used, and can be freed. // 'used_buffers' is the reverse map - it tracks which buffers were used by an // instruction, so that we can remove the instructions from a buffer's live // set after they are visited. flat_hash_map<const BufferValue*, flat_hash_set<const HloInstruction*>> live_buffers; flat_hash_map<const HloInstruction*, flat_hash_set<const BufferValue*>> used_buffers; auto add_user_to_buffer = [this, &live_buffers, &used_buffers]( const HloInstruction* user, const BufferValue* buffer) { if (!IgnoreBuffer(buffer)) { VLOG(4) << " Adding user " << user->name() << " to buffer " << buffer->ToString(); live_buffers[buffer].insert(user); used_buffers[user].insert(buffer); } }; // Initialize live_buffers for each buffer that we're going to assign. The // set of instructions that need to be visited contains all users of all // aliases, that is, all users of all instructions that have the buffer // contained in their points-to set. for (const HloInstruction* instruction : instruction_sequence.instructions()) { const PointsToSet& points_to = points_to_analysis.GetPointsToSet(instruction); const PointsToSet::BufferSet& buffer_set = points_to.CreateFlattenedSet(); for (const HloInstruction* user : instruction->users()) { if (user->opcode() != HloOpcode::kGetTupleElement) { for (const BufferValue* buffer : buffer_set) { add_user_to_buffer(user, buffer); } } else { // A GetTupleElement doesn't need to keep all of its operand's buffers // alive. It only needs the buffers that relate to the element it's // extracting, and the tuple it's extracting from, but not the buffers // for the other elements. for (const BufferValue* buffer : points_to.element({})) { add_user_to_buffer(user, buffer); } const PointsToSet& gte_points_to = points_to_analysis.GetPointsToSet(user); for (const BufferValue* buffer : gte_points_to.CreateFlattenedSet()) { add_user_to_buffer(user, buffer); } } } } const HloInstruction* root = computation.root_instruction(); BufferValueCompactPointerSet output_source_buffers = ToBufferValueCompactPointerSet( points_to_analysis.GetPointsToSet(root).CreateFlattenedSet()); std::vector<const BufferValue*> dead_buffers_to_free; std::vector<const BufferValue*> operand_buffers_to_free; for (const HloInstruction* instruction : instruction_sequence.instructions()) { const TuplePointsToAnalysis::BufferDefinitionVector& buffers_defined_by_instruction = points_to_analysis.GetBuffersDefinedByInstruction(instruction); VLOG(3) << "Instruction: " << instruction->ToString(); for (const BufferValue* buffer : buffers_defined_by_instruction) { VLOG(4) << " Defines: " << buffer->ToString() << (IgnoreBuffer(buffer) ? " (Ignored)" : ""); } dead_buffers_to_free.clear(); for (const BufferValue* buffer : buffers_defined_by_instruction) { if (IgnoreBuffer(buffer)) { continue; } // Add a nullptr sentry to ensure entry parameters and output source // buffers are not freed until the very end. const bool entry_parameter = &computation == computation.parent()->entry_computation() && buffer->instruction()->opcode() == HloOpcode::kParameter; const bool output = output_source_buffers.count(buffer) > 0; if (entry_parameter || output) { live_buffers[buffer].insert(nullptr); } // If the buffer has no users and isn't an entry parameter or output, it // must be a dead value. if (!live_buffers.contains(buffer)) { dead_buffers_to_free.push_back(buffer); } } // Update live_buffers to indicate we've visited this instruction; this is // the inverse of the initialization logic. We erase this instruction from // all source buffers of all operands of this instruction. Buffers that // have no instructions left to visit are moved from live_buffers to // operand_buffers_to_free. operand_buffers_to_free.clear(); for (const BufferValue* operand_buffer : used_buffers[instruction]) { if (IgnoreBuffer(operand_buffer)) { continue; } VLOG(4) << " Removing user " << instruction->name() << " from buffer " << operand_buffer->ToString(); auto it = live_buffers.find(operand_buffer); flat_hash_set<const HloInstruction*>* live_set = &it->second; live_set->erase(instruction); if (live_set->empty()) { live_buffers.erase(it); operand_buffers_to_free.push_back(operand_buffer); } } // Sort to get a deterministic iteration order. absl::c_sort(operand_buffers_to_free, [](const BufferValue* x, const BufferValue* y) { return x->id() < y->id(); }); // Allocate buffers defined by this instruction. This is the latest point // that we can allocate; right before the buffer is first used. This must // happen before dead or operand buffers are freed; the instruction reads // the operand buffers to produce its output. // // INVARIANT: Either Alloc or ShareBuffer will be called for each buffer // that we should assign. // Make sure each buffer get reused at most once. flat_hash_set<const BufferValue*> reused_buffers; int64 alloc_size_by_instruction = 0; for (const BufferValue* buffer : buffers_defined_by_instruction) { if (IgnoreBuffer(buffer)) { continue; } // Check whether the buffer can share with one of its operands; we can // save memory by sharing the buffer, rather than allocating a new one. // We can only share with the operand buffer if it is about to be freed; // we must be the last user of the buffer. bool shared = false; if (options_.may_reuse_operand_buffers) { for (const BufferValue* operand_buffer : operand_buffers_to_free) { if (reused_buffers.contains(operand_buffer)) { continue; } if (buffer->instruction()->IsUserOf(operand_buffer->instruction()) && buffer->instruction()->opcode() != HloOpcode::kCopy && points_to_analysis.CanShareOperandBufferWithUser( operand_buffer->instruction(), operand_buffer->index(), buffer->instruction(), buffer->index())) { VLOG(3) << " Sharing: " << buffer->ToString() << " with " << operand_buffer->ToString(); ShareBuffer(buffer, operand_buffer, instruction); shared = true; reused_buffers.insert(operand_buffer); break; } } } if (!shared) { VLOG(3) << " Allocating: " << buffer->ToString(); alloc_size_by_instruction += size_fn_(*buffer); Alloc(buffer, instruction); } } // Account for the memory used by subcomputations when estimating the // current heap size. if (memory_by_computation_ != nullptr) { algorithm_->AccountForSubcomputationMemory( instruction, alloc_size_by_instruction, *memory_by_computation_); } // If all computations in the module have been scheduled, we can save memory // by running the heap-simulation for sub-computations inline. E.g. the // buffers for the condition and body of a kWhile instruction are only live // for the duration of the instruction itself. // // The order that the sub-computations are simulated does not affect // correctness; since the whole module has been scheduled, we know that the // sub-computations will never be run concurrently. if (schedule_ != nullptr) { if (instruction->opcode() == HloOpcode::kCall || instruction->opcode() == HloOpcode::kConditional || instruction->opcode() == HloOpcode::kWhile) { for (const HloComputation* called_computation : instruction->called_computations()) { const HloInstructionSequence& called_sequence = schedule_->sequence(called_computation); TF_RETURN_IF_ERROR(RunComputation( *called_computation, called_sequence, points_to_analysis)); } } // Other sub-computations (e.g. Map, Reduce, ...) are skipped; they are // assigned "thread-local" allocations, meaning their buffers are not // allocated up-front at the beginning of the computation. } // Free buffers that are no longer live. This is the earliest point that we // can de-allocate; right after the last use of the buffer. for (const BufferValue* buffer : dead_buffers_to_free) { VLOG(3) << " Freeing dead: " << buffer->ToString(); Free(buffer, instruction); } for (const BufferValue* buffer : operand_buffers_to_free) { VLOG(3) << " Freeing operand: " << buffer->ToString(); Free(buffer, instruction); } } // Any remaining live buffers must be entry parameters or output source // buffers, which had a nullptr sentry added. Free them now, in a // deterministic order. std::vector<const BufferValue*> to_free; to_free.reserve(live_buffers.size()); for (const auto& buffer_pending : live_buffers) { const BufferValue* buffer = buffer_pending.first; const flat_hash_set<const HloInstruction*>& pending = buffer_pending.second; CHECK_EQ(pending.size(), 1) << *buffer; CHECK(*pending.begin() == nullptr) << *buffer; to_free.push_back(buffer); } absl::c_sort(to_free, [](const BufferValue* x, const BufferValue* y) { return x->id() < y->id(); }); for (const BufferValue* buffer : to_free) { VLOG(3) << "Freeing pending: " << buffer->ToString(); Free(buffer, root); } return Status::OK(); } HeapSimulator::HeapSimulator( std::unique_ptr<HeapAlgorithm> algorithm, const BufferValue::SizeFunction& size_fn, const Options& options, const HloSchedule* schedule, const absl::flat_hash_map<const HloComputation*, int64>* memory_by_computation) : no_fragmentation_stats_(absl::make_unique<NoFragmentationStatsHeap>()), algorithm_(std::move(algorithm)), size_fn_(size_fn), options_(options), schedule_(schedule), memory_by_computation_(memory_by_computation) { debug_trace_.set_whole_module_simulation(schedule_ != nullptr); } HeapSimulator::~HeapSimulator() {} bool HeapSimulator::IgnoreBuffer(const BufferValue* buffer) const { // Buffers for constants are ignored unless the alloc_constants option is // set. Also ignore buffers that we're not meant to assign. // // TODO(b/32248867): For consistency, constants should get allocations. if (!options_.alloc_constants && buffer->instruction()->opcode() == HloOpcode::kConstant) { return true; } return options_.buffers_to_assign != nullptr && !options_.buffers_to_assign->contains(buffer); } // Alloc always calls the underlying heap algorithm. void HeapSimulator::Alloc(const BufferValue* buffer, const HloInstruction* instruction) { CHECK(!allocated_buffers_.contains(buffer)) << "Alloc called on allocated buffer: " << *buffer; CHECK(!freed_buffers_.contains(buffer)) << "Alloc called on freed buffer: " << *buffer; allocated_buffers_.insert(buffer); const int64 size = size_fn_(*buffer); algorithm_->Alloc(buffer, size); no_fragmentation_stats_->Alloc(buffer, size); FillDebugTrace(HeapSimulatorTrace::Event::ALLOC, buffer, instruction, nullptr); } // Free calls the underlying algorithm for non-shared buffers, and for shared // buffers whose group liveness has expired. Shared group liveness is tracked // by maintaining a refcount; the Free call on the last buffer in the group // causes Free to be called on the underlying algorithm. void HeapSimulator::Free(const BufferValue* buffer, const HloInstruction* instruction) { auto shared_it = shared_buffers_.find(buffer); if (shared_it != shared_buffers_.end()) { std::shared_ptr<SharedGroup> group = shared_it->second; --group->refcount; if (group->refcount > 0) { return; } CHECK_EQ(group->refcount, 0) << "Free caused negative refcount on shared buffer: " << *buffer; buffer = group->canonical; } CHECK(allocated_buffers_.contains(buffer)) << "Free called on non-allocated buffer: " << *buffer; CHECK(!freed_buffers_.contains(buffer)) << "Free called on freed buffer: " << *buffer; freed_buffers_.insert(buffer); const int64 size = size_fn_(*buffer); algorithm_->Free(buffer, size); no_fragmentation_stats_->Free(buffer, size); FillDebugTrace(HeapSimulatorTrace::Event::FREE, buffer, instruction, nullptr); } // ShareBuffer associates buffers with their SharedGroup in shared_buffers_. // The 'buffer' must be a non-allocated, non-freed buffer, just like in calls to // Alloc. The 'shared' buffer must be a previously allocated or shared buffer. // Both 'buffer' and 'shared' will be associated with the same SharedGroup. void HeapSimulator::ShareBuffer(const BufferValue* buffer, const BufferValue* shared, const HloInstruction* instruction) { CHECK_LE(size_fn_(*buffer), size_fn_(*shared)) << "ShareBuffer oversized buffer" << *buffer << " shared: " << *shared; CHECK(!allocated_buffers_.contains(buffer)) << "ShareBuffer called on allocated buffer: " << *buffer; CHECK(!freed_buffers_.contains(buffer)) << "ShareBuffer called on freed buffer: " << *buffer; CHECK(!freed_buffers_.contains(shared)) << "ShareBuffer called on freed shared buffer: " << *shared; const BufferValue* canonical = nullptr; auto shared_it = shared_buffers_.find(shared); if (shared_it != shared_buffers_.end()) { // The 'shared' buffer already has a group; it might be the canonical, but // also might not be. Just add 'buffer' to the existing group. std::shared_ptr<SharedGroup> group = shared_it->second; canonical = group->canonical; ++group->refcount; shared_buffers_.emplace(buffer, group); } else { // The 'shared' buffer doesn't have a group; it must be the canonical. Add // both 'buffer' and 'shared' to a new group. CHECK(allocated_buffers_.contains(shared)) << "ShareBuffer called on non-allocated shared buffer: " << *shared; auto group = std::make_shared<SharedGroup>(); canonical = shared; group->canonical = canonical; group->refcount = 2; shared_buffers_.emplace(buffer, group); shared_buffers_.emplace(shared, group); } FillDebugTrace(HeapSimulatorTrace::Event::SHARE_WITH, buffer, instruction, canonical); } HeapSimulator::Result HeapSimulator::Finish() { Result result = algorithm_->Finish(); // Post-process the result to add chunks for shared buffers. An empty chunk // map means that either no buffers were allocated, or the heap was only // collecting statistics, e.g. NoFragmentationStatsHeap. if (!result.chunk_map.empty()) { for (const auto& share_pair : shared_buffers_) { const BufferValue* buffer = share_pair.first; std::shared_ptr<SharedGroup> group = share_pair.second; if (buffer != group->canonical) { // The canonical must already exist in the chunk_map, since we called // Alloc(canonical) on the underlying algorithm. Add non-canonical // chunks with the same offset as the canonical. Chunk chunk = FindOrDie(result.chunk_map, group->canonical); chunk.size = size_fn_(*buffer); result.chunk_map.emplace(buffer, chunk); } } // If we were told to assign specific buffers, make sure we've assigned // exactly that many buffers. if (options_.buffers_to_assign != nullptr) { CHECK_EQ(options_.buffers_to_assign->size(), result.chunk_map.size()); } } // Fragmentation is the difference between the actual and ideal sizes. const Result no_frag_result = no_fragmentation_stats_->Finish(); result.fragmentation_size = result.heap_size - no_frag_result.heap_size; // Copy the debug trace we collected to the final result. result.debug_trace.Swap(&debug_trace_); return result; } void HeapSimulator::FillDebugTrace(HeapSimulatorTrace::Event::Kind kind, const BufferValue* buffer, const HloInstruction* instruction, const BufferValue* share_with_canonical) { HeapSimulatorTrace::Event* event = debug_trace_.add_events(); event->set_kind(kind); event->set_buffer_id(buffer->id()); event->set_computation_name(instruction->parent()->name()); event->set_instruction_name(instruction->name()); if (kind == HeapSimulatorTrace::Event::SHARE_WITH) { CHECK(share_with_canonical != nullptr); event->set_share_with_canonical_id(share_with_canonical->id()); } else { CHECK(share_with_canonical == nullptr); } } void NoFragmentationStatsHeap::Alloc(const BufferValue* buffer, int64 size) { current_heap_size_ += size; if (current_heap_size_ > max_heap_size_) { max_heap_size_ = current_heap_size_; } } void NoFragmentationStatsHeap::AccountForSubcomputationMemory( const HloInstruction* instruction, int64 alloc_size_by_instruction, const absl::flat_hash_map<const HloComputation*, int64>& memory_by_computation) { // We only count the memory usage of the largest subcomputation, instead of // adding them all, because subcomputations won't execute in parallel. int64 max_subcomputation_bytes = 0; for (const auto* c : instruction->called_computations()) { auto it = memory_by_computation.find(c); if (it != memory_by_computation.end()) { int64 subcomputation_bytes = it->second; if (subcomputation_bytes > max_subcomputation_bytes) { max_subcomputation_bytes = subcomputation_bytes; } } } if (max_subcomputation_bytes > 0 && (instruction->opcode() == HloOpcode::kWhile || instruction->opcode() == HloOpcode::kCall || instruction->opcode() == HloOpcode::kConditional)) { // The output buffer of while/call/conditional is always aliased with the // output buffer of the root instruction in the body. Don't double count. max_subcomputation_bytes -= alloc_size_by_instruction; } max_heap_size_ = std::max(max_heap_size_, current_heap_size_ + max_subcomputation_bytes); } void NoFragmentationStatsHeap::Free(const BufferValue* buffer, int64 size) { current_heap_size_ -= size; } HeapSimulator::Result NoFragmentationStatsHeap::Finish() { // The result.chunk_map is empty, since we only collect stats, and don't // actually compute chunk assignments. Result result; result.heap_size = max_heap_size_; return result; } void DecreasingSizeRunsHeap::Alloc(const BufferValue* buffer, int64 size) { SetMode(kAlloc); run_.emplace_back(Op{buffer, size}); } void DecreasingSizeRunsHeap::Free(const BufferValue* buffer, int64 size) { CHECK(mode_ != kInit) << "Free called on empty heap: " << *buffer; SetMode(kFree); run_.emplace_back(Op{buffer, size}); } HeapSimulator::Result DecreasingSizeRunsHeap::Finish() { CallAndDrainRun(); return algorithm_->Finish(); } void DecreasingSizeRunsHeap::SetMode(Mode mode) { if (mode_ != mode) { CallAndDrainRun(); mode_ = mode; } } void DecreasingSizeRunsHeap::CallAndDrainRun() { if (mode_ == kInit) { CHECK(run_.empty()); return; } // Call ops in the run sorted by decreasing size, breaking ties by buffer id. absl::c_sort(run_, [](const Op& a, const Op& b) { if (a.size != b.size) { return a.size > b.size; } return a.buffer->id() < b.buffer->id(); }); for (const Op& op : run_) { if (mode_ == kAlloc) { algorithm_->Alloc(op.buffer, op.size); } else { algorithm_->Free(op.buffer, op.size); } } run_.clear(); } void LazyBestFitHeap::Alloc(const BufferValue* buffer, int64 size) { // Degenerate case: 0-sized buffers are always allocated at offset 0. if (size == 0) { result_.chunk_map.emplace(buffer, Chunk{0, 0}); } // First try to allocate from the best-fitting free chunk. auto best_fit_it = free_.lower_bound(Chunk{0, size}); while (best_fit_it != free_.end()) { // Account for alignment. const Chunk best = *best_fit_it; const int64 new_offset = RoundUpToNearest(best.offset, alignment_); const int64 new_end = new_offset + size; if (new_end > best.chunk_end()) { // We don't fit after accounting for alignment. ++best_fit_it; continue; } // The buffer is allocated a chunk out of the best-fitting free chunk. free_.erase(best_fit_it); result_.chunk_map.emplace(buffer, Chunk{new_offset, size}); // Add remaining portions of the best-fitting free chunk back into free_. AddFreeChunk(best.offset, new_offset - best.offset); AddFreeChunk(new_end, best.chunk_end() - new_end); return; } // The buffer doesn't completely fit into any existing free chunk. If the // last free chunk is adjacent to the end of the heap, allocate the buffer // re-using that space, increasing the heap size. // // Allocating the buffer now causes the heap to grow by less than the buffer // size, whereas if we allocated lazily in Free, the heap would grow by // exactly the buffer size. However it's still a greedy heuristical approach; // we might have ended up with a tighter packing by being lazy here. // // In theory we could also check if we could re-use space from the first free // chunk and grow the heap at the front, and choose whether to grow from the // front or back based on the amount of re-use. But that's more complicated, // and these are all heuristics anyways, so it isn't implemented. for (auto it = free_.begin(); it != free_.end(); ++it) { if (it->chunk_end() == result_.heap_size) { // Account for alignment in the last free chunk. const Chunk last = *it; const int64 new_offset = RoundUpToNearest(last.offset, alignment_); if (new_offset >= last.chunk_end()) { // There's no point in using the last free chunk if alignment causes us // to skip over it anyways. break; } // The buffer is allocated a chunk that includes the last free chunk. free_.erase(it); result_.chunk_map.emplace(buffer, Chunk{new_offset, size}); // Add remaining portion of the last free chunk back into free_. AddFreeChunk(last.offset, new_offset - last.offset); // Grow the heap. const int64 new_end = new_offset + size; CHECK_GT(new_end, result_.heap_size); CHECK_LT(new_end, result_.heap_size + size); result_.heap_size = new_end; return; } } // Otherwise lazily allocate the buffer in Free. result_.chunk_map.emplace(buffer, Chunk{kLazyAllocOffset, size}); } void LazyBestFitHeap::Free(const BufferValue* buffer, int64 size) { auto alloc_it = result_.chunk_map.find(buffer); CHECK(alloc_it != result_.chunk_map.end()) << "Free called on non-allocated buffer: " << *buffer; Chunk* alloc = &alloc_it->second; CHECK_EQ(alloc->size, size) << "Free with mismatched sizes: " << *buffer; if (alloc->offset != kLazyAllocOffset) { // The buffer was already allocated in Alloc, do a normal free. AddFreeChunk(alloc->offset, alloc->size); } else { // This buffer is lazily allocated, so we *can not* allocate out of existing // free chunks, since that might cause interference between buffers. The // buffer is allocated by growing the heap, accounting for alignment. alloc->offset = RoundUpToNearest(result_.heap_size, alignment_); const int64 new_end = alloc->chunk_end(); AddFreeChunk(result_.heap_size, new_end - result_.heap_size); CHECK_GT(new_end, result_.heap_size); CHECK_GE(new_end, result_.heap_size + alloc->size); result_.heap_size = new_end; } } void LazyBestFitHeap::AddFreeChunk(int64 offset, int64 size) { if (size <= 0) { return; } // Coalesce the chunk with adjacent free chunks on either side. We must // remove the free chunks from free_, since it's ordered by size. Chunk chunk{offset, size}; for (auto it = free_.begin(); it != free_.end();) { if (it->chunk_end() == chunk.offset || it->offset == chunk.chunk_end()) { chunk.offset = std::min(chunk.offset, it->offset); chunk.size += it->size; it = free_.erase(it); } else { ++it; } } // This is the only place we add free chunks to free_. It maintains the // invariant that all free chunks are disjoint and non-adjacent. free_.emplace(chunk); } HeapSimulator::Result LazyBestFitHeap::Finish() { if (!free_.empty()) { // When Finish is called, all calls to Alloc must have had corresponding // calls to Free, which will result in a single free chunk [0, heap_size). CHECK_EQ(free_.size(), 1); CHECK_EQ(free_.begin()->offset, 0); CHECK_EQ(free_.begin()->size, result_.heap_size); } return result_; } void GlobalDecreasingSizeBestFitHeap::Alloc(const BufferValue* buffer, int64 size) { // Degenerate case: 0-sized buffers are always allocated at offset 0. if (size == 0) { result_.chunk_map.emplace(buffer, Chunk{0, 0}); return; } auto emplace_result = buffer_intervals_.emplace( buffer, BufferInterval{buffer, size, current_time_, -1}); DCHECK(emplace_result.second); ++current_time_; } void GlobalDecreasingSizeBestFitHeap::Free(const BufferValue* buffer, int64 size) { // Degenerate case: 0-sized buffers are always allocated at offset 0. if (size == 0) { return; } BufferInterval& buffer_interval = FindOrDie(buffer_intervals_, buffer); DCHECK_EQ(buffer_interval.buffer, buffer); DCHECK_EQ(buffer_interval.size, size); DCHECK_EQ(buffer_interval.end, -1); buffer_interval.end = current_time_; ++current_time_; } namespace { // Node in BufferIntervalTree that stores the alloc and free times of a buffer, // and the chunk assigned to it. struct BufferIntervalTreeNode { // Alloc time. int64 start; // Free time. int64 end; // Maximum free time of all nodes in the subtree where this node is the root. int64 subtree_end; // Allocated chunk for the buffer. HeapSimulator::Chunk chunk; // Left child. BufferIntervalTreeNode* left; // Right child. BufferIntervalTreeNode* right; }; // An interval tree that can query buffers overlapping in time. class BufferIntervalTree { public: explicit BufferIntervalTree(int capacity) : node_storage_(capacity) {} using Chunk = HeapSimulator::Chunk; // Adds a buffer to the interval tree, with the time interval and allocated // chunk specified. void Add(int64 start, int64 end, const Chunk& chunk) { int index = node_count_; DCHECK_LT(index, node_storage_.size()); ++node_count_; node_storage_[index] = BufferIntervalTreeNode{start, end, end, chunk, nullptr, nullptr}; if (index == 0) { // This is root. return; } BufferIntervalTreeNode* parent = &node_storage_[0]; while (true) { parent->subtree_end = std::max(parent->subtree_end, end); if (parent->start > start) { if (parent->left == nullptr) { parent->left = &node_storage_[index]; return; } parent = parent->left; } else { if (parent->right == nullptr) { parent->right = &node_storage_[index]; return; } parent = parent->right; } } } // Returns vector of allocated chunks that overlap with the given time // interval. std::vector<Chunk> ChunksOverlappingInTime(int64 start, int64 end) { std::vector<Chunk> result; if (node_count_ == 0) { return result; } std::vector<BufferIntervalTreeNode*> visiting_stack; visiting_stack.push_back(&node_storage_[0]); while (!visiting_stack.empty()) { BufferIntervalTreeNode* top = visiting_stack.back(); visiting_stack.pop_back(); if (start > top->subtree_end) { continue; } if (top->left != nullptr) { visiting_stack.push_back(top->left); } if (top->start <= end && top->end >= start) { result.push_back(top->chunk); } if (end < top->start) { continue; } if (top->right != nullptr) { visiting_stack.push_back(top->right); } } return result; } private: int64 node_count_ = 0; std::vector<BufferIntervalTreeNode> node_storage_; }; } // namespace HeapSimulator::Result GlobalDecreasingSizeBestFitHeap::Finish() { std::vector<BufferInterval> sorted_buffer_intervals; for (auto& entry : buffer_intervals_) { sorted_buffer_intervals.push_back(entry.second); } absl::c_sort(sorted_buffer_intervals, [](const BufferInterval& x, const BufferInterval& y) { if (x.size != y.size) { return x.size > y.size; } if (x.end - x.start != y.end - y.start) { return x.end - x.start > y.end - y.start; } return x.buffer->id() < y.buffer->id(); }); BufferIntervalTree interval_tree(sorted_buffer_intervals.size()); for (auto& buffer_interval : sorted_buffer_intervals) { auto chunks_overlapping_in_time = interval_tree.ChunksOverlappingInTime( buffer_interval.start, buffer_interval.end); absl::c_sort( chunks_overlapping_in_time, [](const Chunk& x, const Chunk& y) { return x.offset < y.offset; }); // Find the minimum free chunk that can hold this buffer. Chunk min_fit_chunk{-1, INT64_MAX}; auto use_free_chunk_if_smaller = [&](int64 free_offset, int64 free_size) { if (free_size < buffer_interval.size) { return; } if (free_size < min_fit_chunk.size) { min_fit_chunk = {free_offset, free_size}; } }; int64 offset = 0; for (auto& chunk : chunks_overlapping_in_time) { if (offset < chunk.offset) { use_free_chunk_if_smaller(offset, chunk.offset - offset); } offset = std::max(offset, RoundUpToNearest(chunk.chunk_end(), alignment_)); } use_free_chunk_if_smaller(offset, result_.heap_size - offset); if (min_fit_chunk.offset == -1) { // Increase the heap size to fit in the last free chunk. result_.heap_size = offset + buffer_interval.size; min_fit_chunk = {offset, buffer_interval.size}; } min_fit_chunk.size = buffer_interval.size; const auto emplace_result = result_.chunk_map.emplace(buffer_interval.buffer, min_fit_chunk); DCHECK(emplace_result.second); interval_tree.Add(buffer_interval.start, buffer_interval.end, min_fit_chunk); } return result_; } HeapSimulator::Result ChooseBestHeapAlgorithm::Finish() { DCHECK(!algorithms_.empty()); std::vector<Result> results(algorithms_.size()); int64 min_size = INT64_MAX; int min_size_index = -1; for (int i = 0; i < algorithms_.size(); ++i) { results[i] = algorithms_[i]->Finish(); if (results[i].heap_size < min_size) { min_size = results[i].heap_size; min_size_index = i; } } DCHECK_GE(min_size_index, 0); return results[min_size_index]; } } // namespace xla
38.930085
80
0.678231
[ "vector" ]
4fced67799792b2094aab41016e339a4605880a7
7,918
cpp
C++
test/test_gpio/test_gpio.cpp
xmrhaelan/turpial-firmware
1ac3fd01448e2bf1061cb67f47d20d12d9b2e13c
[ "Apache-2.0" ]
null
null
null
test/test_gpio/test_gpio.cpp
xmrhaelan/turpial-firmware
1ac3fd01448e2bf1061cb67f47d20d12d9b2e13c
[ "Apache-2.0" ]
null
null
null
test/test_gpio/test_gpio.cpp
xmrhaelan/turpial-firmware
1ac3fd01448e2bf1061cb67f47d20d12d9b2e13c
[ "Apache-2.0" ]
null
null
null
/** * @file test_wifi_mode.cpp * @author Locha Mesh Developers (contact@locha.io) * @brief * @version 0.1 * @date 2019-12-11 * * @copyright Copyright (c) 2019 Locha Mesh project developers * @license Apache 2.0, see LICENSE file for details * platformio test -e featheresp32 -f test_nvs */ #include "driver/gpio.h" #include "driver/ledc.h" #include "freertos/FreeRTOS.h" #include "freertos/queue.h" #include "freertos/task.h" #include <esp_log.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unity.h> /** * Brief: * This test code shows how to configure gpio , how to use gpio interrupt and how to use PWM. * * GPIO status: * GPIO25: output * GPIO26: output * GPIO33: output * GPIO27: output, * GPIO32: input, pulled up, interrupt from rising edge. the GPIO32 is not able to work with interrupts * * Test: * */ #define LEDC_HS_TIMER LEDC_TIMER_0 #define LEDC_HS_MODE LEDC_HIGH_SPEED_MODE #define LEDC_HS_CH0_CHANNEL LEDC_CHANNEL_0 #define LEDC_HS_CH1_CHANNEL LEDC_CHANNEL_1 #define LEDC_LS_TIMER LEDC_TIMER_1 #define LEDC_LS_MODE LEDC_LOW_SPEED_MODE #define LEDC_LS_CH2_CHANNEL LEDC_CHANNEL_2 #define LEDC_TEST_CH_NUM (3) #define LEDC_TEST_DUTY (4000) #define LEDC_TEST_FADE_TIME (3000) #define LEDC_TEST_DUTY_ZERO (0) // to test with esp32 wrover kit we can use RGB GPIO /* #define LED_R 2 #define LED_G 0 #define LED_B 4 */ #define LED_R 25 //34 wrong in schematic #define LED_G 26 //35 wrong in schematic #define LED_B 33 //4 #define USER_BUTTON 21 //32 in schematic but not work with interrupt service //works 27,25,23,21,26 //not work 32,34,36 this pins not work with interrupt handler #define SYSOFF 27 //32 wrong in schematic not accept IRQ #define GPIO_OUTPUT_PIN_SEL ((1ULL << SYSOFF)) #define GPIO_INPUT_PIN_SEL ((1ULL << USER_BUTTON)) #define ESP_INTR_FLAG_DEFAULT 0 int gpio_level; bool validPress; int count = 0; bool toggle = false; ledc_channel_config_t ledc_channel[LEDC_TEST_CH_NUM]; static xQueueHandle gpio_evt_queue = NULL; static void IRAM_ATTR gpio_isr_handler(void* arg) { gpio_intr_disable(static_cast<gpio_num_t>(USER_BUTTON)); uint32_t gpio_num = (uint32_t)arg; xQueueSendFromISR(gpio_evt_queue, &gpio_num, NULL); //vTaskDelay(1000 / portTICK_PERIOD_MS); } static void gpioInit(void) { gpio_config_t io_conf; //disable interrupt io_conf.intr_type = static_cast<gpio_int_type_t>(GPIO_PIN_INTR_DISABLE); //set as output mode io_conf.mode = GPIO_MODE_OUTPUT; //bit mask of the pins that you want to set,e.g.GPIO0/2/4 io_conf.pin_bit_mask = GPIO_OUTPUT_PIN_SEL; //disable pull-down mode io_conf.pull_down_en = static_cast<gpio_pulldown_t>(0); //disable pull-up mode io_conf.pull_up_en = static_cast<gpio_pullup_t>(0); //configure GPIO with the given settings gpio_config(&io_conf); //interrupt of rising edge io_conf.intr_type = static_cast<gpio_int_type_t>(GPIO_PIN_INTR_POSEDGE); //bit mask of the pins, use GPIO0/27/32 here io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL; //set as input mode io_conf.mode = GPIO_MODE_INPUT; //enable pull-up mode io_conf.pull_up_en = static_cast<gpio_pullup_t>(1); gpio_config(&io_conf); //change gpio intrrupt type gpio_set_intr_type(static_cast<gpio_num_t>(USER_BUTTON), GPIO_INTR_ANYEDGE); //create a queue to handle gpio event from isr gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t)); //install gpio isr service gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT); gpio_isr_handler_add(static_cast<gpio_num_t>(USER_BUTTON), gpio_isr_handler, (void*)USER_BUTTON); } void pwmInit(void) { int ch; ledc_timer_config_t ledc_timer; ledc_timer.duty_resolution = LEDC_TIMER_13_BIT; // resolution of PWM duty ledc_timer.freq_hz = 5000; // frequency of PWM signal ledc_timer.speed_mode = LEDC_HS_MODE; // timer mode ledc_timer.timer_num = LEDC_HS_TIMER; // timer index // Set configuration of timer0 for high speed channels ledc_timer_config(&ledc_timer); // Prepare and set configuration of timer1 for low speed channels ledc_timer.speed_mode = LEDC_LS_MODE; ledc_timer.timer_num = LEDC_LS_TIMER; ledc_timer_config(&ledc_timer); //ledc_channel_config_t ledc_channel[LEDC_TEST_CH_NUM]; ledc_channel[0].channel = LEDC_HS_CH0_CHANNEL; ledc_channel[0].duty = 0; ledc_channel[0].gpio_num = LED_R; ledc_channel[0].speed_mode = LEDC_HS_MODE; ledc_channel[0].hpoint = 0; ledc_channel[0].timer_sel = LEDC_HS_TIMER; ledc_channel[1].channel = LEDC_HS_CH0_CHANNEL; ledc_channel[1].duty = 0; ledc_channel[1].gpio_num = LED_G; ledc_channel[1].speed_mode = LEDC_HS_MODE; ledc_channel[1].hpoint = 0; ledc_channel[1].timer_sel = LEDC_HS_TIMER; ledc_channel[2].channel = LEDC_HS_CH0_CHANNEL; ledc_channel[2].duty = 0; ledc_channel[2].gpio_num = LED_B; ledc_channel[2].speed_mode = LEDC_HS_MODE; ledc_channel[2].hpoint = 0; ledc_channel[2].timer_sel = LEDC_HS_TIMER; // Set LED Controller with previously prepared configuration for (ch = 0; ch < LEDC_TEST_CH_NUM; ch++) { ledc_channel_config(&ledc_channel[ch]); } // Initialize fade service. ledc_fade_func_install(0); } void gpio_task(void* arg) { for (;;) { validPress = true; // innocent until proven guilty uint32_t io_num; if (xQueueReceive(gpio_evt_queue, &io_num, portMAX_DELAY)) { gpio_level = gpio_get_level(static_cast<gpio_num_t>(io_num)); if (gpio_level != 0) { validPress = false; } if (validPress) { printf("*********************************GPIO[%d] valid button press received. Count: %d\n", io_num, count++); gpio_set_level(static_cast<gpio_num_t>(SYSOFF), toggle = !toggle); } gpio_intr_enable(static_cast<gpio_num_t>(USER_BUTTON)); } } } void runTest(void) { int cnt = 0; int ch; gpioInit(); pwmInit(); //start gpio task xTaskCreate(gpio_task, "gpio_task", 2048, NULL, 10, NULL); while (1) { printf("1. LEDC fade up to duty = %d\n", LEDC_TEST_DUTY); for (ch = 0; ch < LEDC_TEST_CH_NUM; ch++) { ledc_set_fade_with_time(ledc_channel[ch].speed_mode, ledc_channel[ch].channel, LEDC_TEST_DUTY, LEDC_TEST_FADE_TIME); ledc_fade_start(ledc_channel[ch].speed_mode, ledc_channel[ch].channel, LEDC_FADE_NO_WAIT); } vTaskDelay(LEDC_TEST_FADE_TIME / portTICK_PERIOD_MS); printf("2. LEDC fade down to duty = 0\n"); for (ch = 0; ch < LEDC_TEST_CH_NUM; ch++) { ledc_set_fade_with_time(ledc_channel[ch].speed_mode, ledc_channel[ch].channel, 0, LEDC_TEST_FADE_TIME); ledc_fade_start(ledc_channel[ch].speed_mode, ledc_channel[ch].channel, LEDC_FADE_NO_WAIT); } vTaskDelay(LEDC_TEST_FADE_TIME / portTICK_PERIOD_MS); printf("3. LEDC set duty = %d without fade\n", LEDC_TEST_DUTY); for (ch = 0; ch < LEDC_TEST_CH_NUM; ch++) { ledc_set_duty(ledc_channel[ch].speed_mode, ledc_channel[ch].channel, LEDC_TEST_DUTY); ledc_update_duty(ledc_channel[ch].speed_mode, ledc_channel[ch].channel); } vTaskDelay(1000 / portTICK_PERIOD_MS); printf("4. LEDC set duty = 0 without fade\n"); for (ch = 0; ch < LEDC_TEST_CH_NUM; ch++) { ledc_set_duty(ledc_channel[ch].speed_mode, ledc_channel[ch].channel, 0); ledc_update_duty(ledc_channel[ch].speed_mode, ledc_channel[ch].channel); } vTaskDelay(1000 / portTICK_PERIOD_MS); } } extern "C" void app_main() { //vTaskDelay(2000); UNITY_BEGIN(); RUN_TEST(runTest); UNITY_END(); }
31.927419
166
0.684264
[ "mesh" ]
4fd0fc596eecd1e4374ddb7398c643db181b3de2
3,926
cc
C++
example/disable_http2/disable_http2.cc
liangzhaorong/trafficserver
80d6440c1879d80d5f3dc0e3dcdc5de38d1e7ea1
[ "Apache-2.0" ]
2
2020-12-05T03:28:25.000Z
2021-07-10T06:03:57.000Z
example/disable_http2/disable_http2.cc
liangzhaorong/trafficserver
80d6440c1879d80d5f3dc0e3dcdc5de38d1e7ea1
[ "Apache-2.0" ]
3
2017-09-22T19:18:56.000Z
2021-06-21T18:07:14.000Z
example/disable_http2/disable_http2.cc
liangzhaorong/trafficserver
80d6440c1879d80d5f3dc0e3dcdc5de38d1e7ea1
[ "Apache-2.0" ]
null
null
null
/** @file An example plugin for accept object protocol set API. This clones the protocol sets attached to all the accept objects and unregisters HTTP/2 from those copies. The protocol set for incoming connections that match a list of domains are replaced with the copy, effectively disabling HTTP/2 for those domains. @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <ts/ts.h> #include <unordered_map> #include <unordered_set> #include <string> #include <cstring> #include <openssl/ssl.h> #define PLUGIN_NAME "disable_http2" typedef std::unordered_map<int, TSNextProtocolSet> AcceptorMapping; // stores protocolset keyed by NetAccept ID AcceptorMapping AcceptorMap; // Map of domains to tweak. using DomainSet = std::unordered_set<std::string>; DomainSet Domains; int CB_SNI(TSCont contp, TSEvent, void *cb_data) { auto vc = static_cast<TSVConn>(cb_data); TSSslConnection ssl_conn = TSVConnSSLConnectionGet(vc); auto *ssl = reinterpret_cast<SSL *>(ssl_conn); char const *sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (sni) { if (Domains.find(sni) != Domains.end()) { TSAcceptor na = TSAcceptorGet(vc); int nid = TSAcceptorIDGet(na); TSNextProtocolSet ps = AcceptorMap[nid]; // get our copy of the protocol set. TSRegisterProtocolSet(vc, ps); // replace default protocol set with the copy. } } TSVConnReenable(vc); return TS_SUCCESS; } int CB_NetAcceptReady(TSCont contp, TSEvent event, void *cb_data) { switch (event) { case TS_EVENT_LIFECYCLE_PORTS_READY: // The accept objects are all created and ready at this point. We // can now iterate over them. for (int i = 0, totalNA = TSAcceptorCount(); i < totalNA; ++i) { TSAcceptor netaccept = TSAcceptorGetbyID(i); // get a clone of the protoset associated with the netaccept TSNextProtocolSet nps = TSGetcloneProtoSet(netaccept); TSUnregisterProtocol(nps, TS_ALPN_PROTOCOL_HTTP_2_0); AcceptorMap[i] = nps; } break; default: break; } return 0; } void TSPluginInit(int argc, char const *argv[]) { int ret; TSPluginRegistrationInfo info; info.plugin_name = PLUGIN_NAME; info.vendor_name = "Apache Software Foundation"; info.support_email = "dev@trafficserver.apache.org"; ret = TSPluginRegister(&info); if (ret != TS_SUCCESS) { TSError("[%s] registration failed", PLUGIN_NAME); return; } else if (argc < 2) { TSError("[%s] Usage %s.so servername1 servername2 ... ", PLUGIN_NAME, PLUGIN_NAME); return; } else { TSDebug(PLUGIN_NAME, "registration succeeded"); } for (int i = 1; i < argc; i++) { TSDebug(PLUGIN_NAME, "%s added to the No-H2 list", argv[i]); Domains.emplace(std::string(argv[i], strlen(argv[i]))); } // These callbacks do not modify any state so no lock is needed. TSCont cb_sni = TSContCreate(&CB_SNI, nullptr); TSCont cb_netacc = TSContCreate(&CB_NetAcceptReady, nullptr); TSHttpHookAdd(TS_SSL_SERVERNAME_HOOK, cb_sni); TSLifecycleHookAdd(TS_LIFECYCLE_PORTS_READY_HOOK, cb_netacc); }
33.271186
111
0.708864
[ "object" ]
4fd190ec1149aaea08485a3258d80a873807365d
3,348
hpp
C++
src/boost/regex/v4/primary_transform.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
src/boost/regex/v4/primary_transform.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
1
2021-08-30T18:02:49.000Z
2021-08-30T18:02:49.000Z
src/boost/regex/v4/primary_transform.hpp
107-systems/107-Arduino-BoostUnits
fc3677ae79c1e75c99b3aa7813eb6ec83124b944
[ "MIT" ]
null
null
null
/* * * Copyright (c) 1998-2002 * John Maddock * * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ /* * LOCATION: see http://www.boost.org for most recent version. * FILE: primary_transform.hpp * VERSION: see "boost/version.hpp" * DESCRIPTION: Heuristically determines the sort string format in use * by the current locale. */ #ifndef BOOST_REGEX_PRIMARY_TRANSFORM #define BOOST_REGEX_PRIMARY_TRANSFORM #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable: 4103) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif #ifdef BOOST_MSVC #pragma warning(pop) #endif namespace boost{ namespace BOOST_REGEX_DETAIL_NS{ enum{ sort_C, sort_fixed, sort_delim, sort_unknown }; template <class S, class charT> unsigned count_chars(const S& s, charT c) { // // Count how many occurrences of character c occur // in string s: if c is a delimeter between collation // fields, then this should be the same value for all // sort keys: // unsigned int count = 0; for(unsigned pos = 0; pos < s.size(); ++pos) { if(s[pos] == c) ++count; } return count; } template <class traits, class charT> unsigned find_sort_syntax(const traits* pt, charT* delim) { // // compare 'a' with 'A' to see how similar they are, // should really use a-accute but we can't portably do that, // typedef typename traits::string_type string_type; typedef typename traits::char_type char_type; // Suppress incorrect warning for MSVC (void)pt; char_type a[2] = {'a', '\0', }; string_type sa(pt->transform(a, a+1)); if(sa == a) { *delim = 0; return sort_C; } char_type A[2] = { 'A', '\0', }; string_type sA(pt->transform(A, A+1)); char_type c[2] = { ';', '\0', }; string_type sc(pt->transform(c, c+1)); int pos = 0; while((pos <= static_cast<int>(sa.size())) && (pos <= static_cast<int>(sA.size())) && (sa[pos] == sA[pos])) ++pos; --pos; if(pos < 0) { *delim = 0; return sort_unknown; } // // at this point sa[pos] is either the end of a fixed width field // or the character that acts as a delimiter: // charT maybe_delim = sa[pos]; if((pos != 0) && (count_chars(sa, maybe_delim) == count_chars(sA, maybe_delim)) && (count_chars(sa, maybe_delim) == count_chars(sc, maybe_delim))) { *delim = maybe_delim; return sort_delim; } // // OK doen't look like a delimiter, try for fixed width field: // if((sa.size() == sA.size()) && (sa.size() == sc.size())) { // note assumes that the fixed width field is less than // (numeric_limits<charT>::max)(), should be true for all types // I can't imagine 127 character fields... *delim = static_cast<charT>(++pos); return sort_fixed; } // // don't know what it is: // *delim = 0; return sort_unknown; } } // namespace BOOST_REGEX_DETAIL_NS } // namespace boost #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable: 4103) #endif #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #ifdef BOOST_MSVC #pragma warning(pop) #endif #endif
22.77551
149
0.635902
[ "transform" ]
4fd5aaafd36b9ec4ab134fc46ad6fbf558692f04
10,861
hpp
C++
src/Evolution/Systems/CurvedScalarWave/Characteristics.hpp
erfz/spectre
dc772598a8197a4f2c4a729ee30dd4398f4cd591
[ "MIT" ]
1
2018-10-01T06:07:16.000Z
2018-10-01T06:07:16.000Z
src/Evolution/Systems/CurvedScalarWave/Characteristics.hpp
erfz/spectre
dc772598a8197a4f2c4a729ee30dd4398f4cd591
[ "MIT" ]
4
2018-06-04T20:26:40.000Z
2018-07-27T14:54:55.000Z
src/Evolution/Systems/CurvedScalarWave/Characteristics.hpp
erfz/spectre
dc772598a8197a4f2c4a729ee30dd4398f4cd591
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <cstddef> #include "DataStructures/DataBox/Tag.hpp" #include "DataStructures/Tensor/EagerMath/Magnitude.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "DataStructures/Variables.hpp" #include "Domain/FaceNormal.hpp" #include "Evolution/Systems/CurvedScalarWave/Constraints.hpp" #include "Evolution/Systems/CurvedScalarWave/TagsDeclarations.hpp" #include "PointwiseFunctions/GeneralRelativity/TagsDeclarations.hpp" #include "Utilities/TMPL.hpp" namespace CurvedScalarWave { /// @{ /*! * \brief Compute the characteristic speeds for the scalar wave system in curved * spacetime. * * Computes the speeds as described in "Optimal constraint projection for * hyperbolic evolution systems" by Holst et. al \cite Holst2004wt * [see text following Eq. (32)]. The characteristic fields' names used here * are similar to the paper: * * \f{align*} * \mathrm{SpECTRE} && \mathrm{Holst} \\ * v^{\hat \psi} && Z^1 \\ * v^{\hat 0}_{i} && Z^{2}_{i} \\ * v^{\hat \pm} && u^{1\pm} * \f} * * The corresponding characteristic speeds \f$\lambda\f$ are given in the text * following Eq. (38) of \cite Holst2004wt : * * \f{align*} * \lambda_{\hat \psi} =& -(1 + \gamma_1) n_k N^k \\ * \lambda_{\hat 0} =& -n_k N^k \\ * \lambda_{\hat \pm} =& -n_k N^k \pm N * \f} * * where \f$n_k\f$ is the unit normal to the surface. */ template <size_t SpatialDim> std::array<DataVector, 4> characteristic_speeds( const Scalar<DataVector>& gamma_1, const Scalar<DataVector>& lapse, const tnsr::I<DataVector, SpatialDim, Frame::Inertial>& shift, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept; template <size_t SpatialDim> void characteristic_speeds( gsl::not_null<std::array<DataVector, 4>*> char_speeds, const Scalar<DataVector>& gamma_1, const Scalar<DataVector>& lapse, const tnsr::I<DataVector, SpatialDim, Frame::Inertial>& shift, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept; template <size_t SpatialDim> struct CharacteristicSpeedsCompute : Tags::CharacteristicSpeeds<SpatialDim>, db::ComputeTag { using base = Tags::CharacteristicSpeeds<SpatialDim>; using return_type = typename base::type; using argument_tags = tmpl::list< Tags::ConstraintGamma1, gr::Tags::Lapse<DataVector>, gr::Tags::Shift<SpatialDim, Frame::Inertial, DataVector>, ::Tags::Normalized<domain::Tags::UnnormalizedFaceNormal<SpatialDim>>>; static constexpr void function( gsl::not_null<return_type*> result, const Scalar<DataVector>& gamma_1, const Scalar<DataVector>& lapse, const tnsr::I<DataVector, SpatialDim, Frame::Inertial>& shift, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept { characteristic_speeds<SpatialDim>(result, gamma_1, lapse, shift, unit_normal_one_form); } }; /// @} /// @{ /*! * \brief Computes characteristic fields from evolved fields * * \ref CharacteristicFieldsCompute and * \ref EvolvedFieldsFromCharacteristicFieldsCompute convert between * characteristic and evolved fields for the scalar-wave system in curved * spacetime. * * \ref CharacteristicFieldsCompute computes * characteristic fields as described in "Optimal constraint projection for * hyperbolic evolution systems" by Holst et. al \cite Holst2004wt . * Their names used here differ from this paper: * * \f{align*} * \mathrm{SpECTRE} && \mathrm{Holst} \\ * v^{\hat \psi} && Z^1 \\ * v^{\hat 0}_{i} && Z^{2}_{i} \\ * v^{\hat \pm} && u^{1\pm} * \f} * * The characteristic fields \f$u\f$ are given in terms of the evolved fields by * Eq. (33) - (35) of \cite Holst2004wt, respectively: * * \f{align*} * v^{\hat \psi} =& \psi \\ * v^{\hat 0}_{i} =& (\delta^k_i - n_i n^k) \Phi_{k} := P^k_i \Phi_{k} \\ * v^{\hat \pm} =& \Pi \pm n^i \Phi_{i} - \gamma_2\psi * \f} * * where \f$\psi\f$ is the scalar field, \f$\Pi\f$ and \f$\Phi_{i}\f$ are * evolved fields introduced by first derivatives of \f$\psi\f$, \f$\gamma_2\f$ * is a constraint damping parameter, and \f$n_k\f$ is the unit normal to the * surface. * * \ref EvolvedFieldsFromCharacteristicFieldsCompute computes evolved fields * \f$w\f$ in terms of the characteristic fields. This uses the inverse of * above relations (c.f. Eq. (36) - (38) of \cite Holst2004wt ): * * \f{align*} * \psi =& v^{\hat \psi}, \\ * \Pi =& \frac{1}{2}(v^{\hat +} + v^{\hat -}) + \gamma_2 v^{\hat \psi}, \\ * \Phi_{i} =& \frac{1}{2}(v^{\hat +} - v^{\hat -}) n_i + v^{\hat 0}_{i}. * \f} * * The corresponding characteristic speeds \f$\lambda\f$ are computed by * \ref CharacteristicSpeedsCompute . */ template <size_t SpatialDim> Variables< tmpl::list<Tags::VPsi, Tags::VZero<SpatialDim>, Tags::VPlus, Tags::VMinus>> characteristic_fields( const Scalar<DataVector>& gamma_2, const tnsr::II<DataVector, SpatialDim, Frame::Inertial>& inverse_spatial_metric, const Scalar<DataVector>& psi, const Scalar<DataVector>& pi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& phi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept; template <size_t SpatialDim> void characteristic_fields( gsl::not_null<Variables<tmpl::list<Tags::VPsi, Tags::VZero<SpatialDim>, Tags::VPlus, Tags::VMinus>>*> char_fields, const Scalar<DataVector>& gamma_2, const tnsr::II<DataVector, SpatialDim, Frame::Inertial>& inverse_spatial_metric, const Scalar<DataVector>& psi, const Scalar<DataVector>& pi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& phi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept; template <size_t SpatialDim> struct CharacteristicFieldsCompute : Tags::CharacteristicFields<SpatialDim>, db::ComputeTag { using base = Tags::CharacteristicFields<SpatialDim>; using return_type = typename base::type; using argument_tags = tmpl::list< Tags::ConstraintGamma2, gr::Tags::InverseSpatialMetric<SpatialDim, Frame::Inertial, DataVector>, Psi, Pi, Phi<SpatialDim>, ::Tags::Normalized<domain::Tags::UnnormalizedFaceNormal<SpatialDim>>>; static constexpr void function( gsl::not_null<return_type*> result, const Scalar<DataVector>& gamma_2, const tnsr::II<DataVector, SpatialDim, Frame::Inertial>& inverse_spatial_metric, const Scalar<DataVector>& psi, const Scalar<DataVector>& pi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& phi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept { characteristic_fields<SpatialDim>(result, gamma_2, inverse_spatial_metric, psi, pi, phi, unit_normal_one_form); } }; /// @} /// @{ /*! * \brief For expressions used here to compute evolved fields from * characteristic ones, see \ref CharacteristicFieldsCompute. */ template <size_t SpatialDim> Variables<tmpl::list<Psi, Pi, Phi<SpatialDim>>> evolved_fields_from_characteristic_fields( const Scalar<DataVector>& gamma_2, const Scalar<DataVector>& v_psi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& v_zero, const Scalar<DataVector>& v_plus, const Scalar<DataVector>& v_minus, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept; template <size_t SpatialDim> void evolved_fields_from_characteristic_fields( gsl::not_null<Variables<tmpl::list<Psi, Pi, Phi<SpatialDim>>>*> evolved_fields, const Scalar<DataVector>& gamma_2, const Scalar<DataVector>& v_psi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& v_zero, const Scalar<DataVector>& v_plus, const Scalar<DataVector>& v_minus, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept; template <size_t SpatialDim> struct EvolvedFieldsFromCharacteristicFieldsCompute : Tags::EvolvedFieldsFromCharacteristicFields<SpatialDim>, db::ComputeTag { using base = Tags::EvolvedFieldsFromCharacteristicFields<SpatialDim>; using return_type = typename base::type; using argument_tags = tmpl::list< Tags::ConstraintGamma2, Tags::VPsi, Tags::VZero<SpatialDim>, Tags::VPlus, Tags::VMinus, ::Tags::Normalized<domain::Tags::UnnormalizedFaceNormal<SpatialDim>>>; static constexpr void function( gsl::not_null<return_type*> result, const Scalar<DataVector>& gamma_2, const Scalar<DataVector>& v_psi, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& v_zero, const Scalar<DataVector>& v_plus, const Scalar<DataVector>& v_minus, const tnsr::i<DataVector, SpatialDim, Frame::Inertial>& unit_normal_one_form) noexcept { evolved_fields_from_characteristic_fields<SpatialDim>( result, gamma_2, v_psi, v_zero, v_plus, v_minus, unit_normal_one_form); } }; /// @} namespace Tags { /*! * \brief Computes the largest magnitude of the characteristic speeds. * * \details Returns the magnitude of the largest characteristic speed * along any direction at a given point in space, considering all * characteristic fields. This is useful, for e.g., in computing the * Courant factor. The coordinate characteristic speeds for this system are * \f$\{-(1+\gamma_1)n_k N^k, -n_k N^k, -n_k N^k \pm N\}\f$. At any point * in space, these are maximized when the normal vector is parallel to the * shift vector, i.e. \f$ n^j = N^j / \sqrt{N^i N_i}\f$, and \f$ n_k N^k * = g_{jk} N^j N^k / \sqrt{N^i N_i} = \sqrt{N^i N_i} =\f$ * `magnitude(shift, spatial_metric)`. The maximum characteristic speed * is therefore calculated as \f$ \rm{max}(\vert 1+\gamma_1\vert\sqrt{N^i * N_i},\, \sqrt{N^i N_i}+\vert N\vert) \f$. */ template <size_t SpatialDim> struct ComputeLargestCharacteristicSpeed : LargestCharacteristicSpeed, db::ComputeTag { using argument_tags = tmpl::list< Tags::ConstraintGamma1, gr::Tags::Lapse<DataVector>, gr::Tags::Shift<SpatialDim, Frame::Inertial, DataVector>, gr::Tags::SpatialMetric<SpatialDim, Frame::Inertial, DataVector>>; using return_type = double; using base = LargestCharacteristicSpeed; static void function( const gsl::not_null<double*> max_speed, const Scalar<DataVector>& gamma_1, const Scalar<DataVector>& lapse, const tnsr::I<DataVector, SpatialDim, Frame::Inertial>& shift, const tnsr::ii<DataVector, SpatialDim, Frame::Inertial>& spatial_metric) noexcept; }; } // namespace Tags } // namespace CurvedScalarWave
41.140152
80
0.691097
[ "vector" ]
4fd9551dd1e31c749daf86661d6a32dee14903fc
7,241
cc
C++
src/kudu/master/location_cache-test.cc
attilabukor/kudu
d4942c43880a7b0324388630ff640fe66f16c4b5
[ "Apache-2.0" ]
1,538
2016-08-08T22:34:30.000Z
2022-03-29T05:23:36.000Z
src/kudu/master/location_cache-test.cc
attilabukor/kudu
d4942c43880a7b0324388630ff640fe66f16c4b5
[ "Apache-2.0" ]
17
2017-05-18T16:05:14.000Z
2022-03-18T22:17:13.000Z
src/kudu/master/location_cache-test.cc
attilabukor/kudu
d4942c43880a7b0324388630ff640fe66f16c4b5
[ "Apache-2.0" ]
612
2016-08-12T04:09:37.000Z
2022-03-29T16:57:46.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/master/location_cache.h" #include <cstdint> #include <ostream> #include <string> #include <thread> #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include "kudu/gutil/ref_counted.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/util/metrics.h" #include "kudu/util/path_util.h" #include "kudu/util/status.h" #include "kudu/util/test_macros.h" #include "kudu/util/test_util.h" METRIC_DECLARE_counter(location_mapping_cache_hits); METRIC_DECLARE_counter(location_mapping_cache_queries); using std::string; using std::thread; using std::vector; using strings::Substitute; namespace kudu { namespace master { // Targeted test for LocationCache. class LocationCacheTest : public KuduTest { protected: void SetUp() override { KuduTest::SetUp(); metric_entity_ = METRIC_ENTITY_server.Instantiate(&metric_registry_, "LocationCacheTest"); } void CheckMetrics(int64_t expected_queries, int64_t expected_hits) { scoped_refptr<Counter> cache_queries(metric_entity_->FindOrCreateCounter( &METRIC_location_mapping_cache_queries)); ASSERT_NE(nullptr, cache_queries.get()); ASSERT_EQ(expected_queries, cache_queries->value()); scoped_refptr<Counter> cache_hits(metric_entity_->FindOrCreateCounter( &METRIC_location_mapping_cache_hits)); ASSERT_NE(nullptr, cache_hits.get()); ASSERT_EQ(expected_hits, cache_hits->value()); } MetricRegistry metric_registry_; scoped_refptr<MetricEntity> metric_entity_; }; TEST_F(LocationCacheTest, EmptyMappingCommand) { LocationCache cache(" ", metric_entity_.get()); string location; auto s = cache.GetLocation("na", &location); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); ASSERT_STR_CONTAINS( s.ToString(), "invalid empty location mapping command"); NO_FATALS(CheckMetrics(1, 0)); } TEST_F(LocationCacheTest, MappingCommandNotFound) { LocationCache cache("./notfound.sh", metric_entity_.get()); string location; auto s = cache.GetLocation("na", &location); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); ASSERT_STR_CONTAINS( s.ToString(), "failed to run location mapping command: "); } TEST_F(LocationCacheTest, MappingCommandFailureExitStatus) { LocationCache cache("/sbin/nologin", metric_entity_.get()); string location; auto s = cache.GetLocation("na", &location); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); ASSERT_STR_CONTAINS( s.ToString(), "failed to run location mapping command: "); NO_FATALS(CheckMetrics(1, 0)); } TEST_F(LocationCacheTest, MappingCommandEmptyOutput) { LocationCache cache("/bin/cat", metric_entity_.get()); string location; auto s = cache.GetLocation("/dev/null", &location); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); ASSERT_STR_CONTAINS( s.ToString(), "location mapping command returned invalid empty location"); NO_FATALS(CheckMetrics(1, 0)); } // Bad cases where the script returns locations with disallowed characters or // in the wrong format. TEST_F(LocationCacheTest, MappingCommandReturnsInvalidLocation) { const vector<string> bad_locations = { "\"\"", // Empty (doesn't begin with /). "foo", // Doesn't begin with /. "/foo$", // Contains the illegal character '$'. "\"/foo /bar\"", // Contains the illegal character ' '. }; for (const auto& l : bad_locations) { SCOPED_TRACE(Substitute("location '$0'", l)); const string cmd_path = JoinPathSegments(GetTestExecutableDirectory(), "testdata/first_argument.sh"); const string location_mapping_cmd = Substitute("$0 $1", cmd_path, l); LocationCache cache(location_mapping_cmd, metric_entity_.get()); string location; auto s = cache.GetLocation("na", &location); ASSERT_TRUE(s.IsRuntimeError()) << s.ToString(); ASSERT_STR_CONTAINS( s.ToString(), "location mapping command returned invalid location"); } NO_FATALS(CheckMetrics(bad_locations.size(), 0)); } TEST_F(LocationCacheTest, HappyPath) { const string kRefLocation = "/ref_location"; const string cmd_path = JoinPathSegments(GetTestExecutableDirectory(), "testdata/first_argument.sh"); const string location_mapping_cmd = Substitute("$0 $1", cmd_path, kRefLocation); LocationCache cache(location_mapping_cmd, metric_entity_.get()); NO_FATALS(CheckMetrics(0, 0)); string location; auto s = cache.GetLocation("key_0", &location); ASSERT_TRUE(s.ok()) << s.ToString(); ASSERT_EQ(kRefLocation, location); NO_FATALS(CheckMetrics(1, 0)); s = cache.GetLocation("key_1", &location); ASSERT_TRUE(s.ok()) << s.ToString(); ASSERT_EQ(kRefLocation, location); NO_FATALS(CheckMetrics(2, 0)); s = cache.GetLocation("key_1", &location); ASSERT_TRUE(s.ok()) << s.ToString(); ASSERT_EQ(kRefLocation, location); NO_FATALS(CheckMetrics(3, 1)); s = cache.GetLocation("key_0", &location); ASSERT_TRUE(s.ok()) << s.ToString(); ASSERT_EQ(kRefLocation, location); NO_FATALS(CheckMetrics(4, 2)); } TEST_F(LocationCacheTest, ConcurrentRequests) { static constexpr auto kNumThreads = 32; const string kRefLocation = "/ref_location"; const string cmd_path = JoinPathSegments(GetTestExecutableDirectory(), "testdata/first_argument.sh"); const string location_mapping_cmd = Substitute("$0 $1", cmd_path, kRefLocation); LocationCache cache(location_mapping_cmd, metric_entity_.get()); NO_FATALS(CheckMetrics(0, 0)); for (auto iter = 0; iter < 2; ++iter) { vector<thread> threads; threads.reserve(kNumThreads); for (auto idx = 0; idx < kNumThreads; ++idx) { threads.emplace_back([&cache, &kRefLocation, idx]() { string location; auto s = cache.GetLocation(Substitute("key_$0", idx), &location); CHECK(s.ok()) << s.ToString(); CHECK_EQ(kRefLocation, location); }); } for (auto& t : threads) { t.join(); } // Expecting to account for every query, and the follow-up iteration // should result in every query hitting the cache. NO_FATALS(CheckMetrics(kNumThreads * (iter + 1), kNumThreads * iter)); } } } // namespace master } // namespace kudu
36.205
80
0.689131
[ "vector" ]
4fda0e7aec1fa9809d97440a6fcf7fbcd6cf0a9d
19,837
cpp
C++
third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8TestTypedefs.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/UnionTypesCore.h" #include "bindings/core/v8/V8DOMConfiguration.h" #include "bindings/core/v8/V8ObjectConstructor.h" #include "bindings/core/v8/V8TestCallbackInterface.h" #include "bindings/core/v8/V8TestInterface.h" #include "bindings/core/v8/V8TestInterfaceEmpty.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "core/frame/LocalDOMWindow.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo V8TestTypedefs::wrapperTypeInfo = { gin::kEmbedderBlink, V8TestTypedefs::domTemplate, V8TestTypedefs::refObject, V8TestTypedefs::derefObject, V8TestTypedefs::trace, 0, 0, V8TestTypedefs::preparePrototypeObject, V8TestTypedefs::installConditionallyEnabledProperties, "TestTypedefs", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::RefCountedObject }; #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in TestTypedefs.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // bindings/core/v8/ScriptWrappable.h. const WrapperTypeInfo& TestTypedefs::s_wrapperTypeInfo = V8TestTypedefs::wrapperTypeInfo; namespace TestTypedefsV8Internal { template<class CallbackInfo> static bool TestTypedefsCreateDataProperty(v8::Local<v8::Name> name, v8::Local<v8::Value> v8Value, const CallbackInfo& info) { ASSERT(info.This()->IsObject()); return v8CallBoolean(v8::Local<v8::Object>::Cast(info.This())->CreateDataProperty(info.GetIsolate()->GetCurrentContext(), name, v8Value)); } static void TestTypedefsConstructorAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter"); do { v8::Local<v8::Value> data = info.Data(); ASSERT(data->IsExternal()); V8PerContextData* perContextData = V8PerContextData::from(info.Holder()->CreationContext()); if (!perContextData) break; const WrapperTypeInfo* wrapperTypeInfo = WrapperTypeInfo::unwrap(data); if (!wrapperTypeInfo) break; TestTypedefsCreateDataProperty(v8String(info.GetIsolate(), wrapperTypeInfo->interfaceName), v8Value, info); } while (false); // do ... while (false) just for use of break TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void uLongLongAttributeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); TestTypedefs* impl = V8TestTypedefs::toImpl(holder); v8SetReturnValue(info, static_cast<double>(impl->uLongLongAttribute())); } static void uLongLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter"); TestTypedefsV8Internal::uLongLongAttributeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void uLongLongAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); ExceptionState exceptionState(ExceptionState::SetterContext, "uLongLongAttribute", "TestTypedefs", holder, info.GetIsolate()); TestTypedefs* impl = V8TestTypedefs::toImpl(holder); unsigned long long cppValue = toUInt64(info.GetIsolate(), v8Value, NormalConversion, exceptionState); if (exceptionState.throwIfNeeded()) return; impl->setULongLongAttribute(cppValue); } static void uLongLongAttributeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Value> v8Value = info[0]; TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter"); TestTypedefsV8Internal::uLongLongAttributeAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void tAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Local<v8::String> propertyName = v8AtomicString(info.GetIsolate(), "tAttribute"); TestTypedefsCreateDataProperty(propertyName, v8Value, info); } static void tAttributeAttributeSetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter"); TestTypedefsV8Internal::tAttributeAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void voidMethodArrayOfLongsArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "voidMethodArrayOfLongsArg", "TestTypedefs", info.Holder(), info.GetIsolate()); TestTypedefs* impl = V8TestTypedefs::toImpl(info.Holder()); Vector<int> arrayOfLongsArg; { if (UNLIKELY(info.Length() <= 0)) { impl->voidMethodArrayOfLongsArg(); return; } arrayOfLongsArg = toImplArray<Vector<int>>(info[0], 1, info.GetIsolate(), exceptionState); if (exceptionState.throwIfNeeded()) return; } impl->voidMethodArrayOfLongsArg(arrayOfLongsArg); } static void voidMethodArrayOfLongsArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); TestTypedefsV8Internal::voidMethodArrayOfLongsArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void voidMethodFloatArgStringArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "voidMethodFloatArgStringArg", "TestTypedefs", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 2)) { setMinimumArityTypeError(exceptionState, 2, info.Length()); exceptionState.throwIfNeeded(); return; } TestTypedefs* impl = V8TestTypedefs::toImpl(info.Holder()); float floatArg; V8StringResource<> stringArg; { floatArg = toRestrictedFloat(info.GetIsolate(), info[0], exceptionState); if (exceptionState.throwIfNeeded()) return; stringArg = info[1]; if (!stringArg.prepare()) return; } impl->voidMethodFloatArgStringArg(floatArg, stringArg); } static void voidMethodFloatArgStringArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); TestTypedefsV8Internal::voidMethodFloatArgStringArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void voidMethodTestCallbackInterfaceTypeArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 1)) { V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "voidMethodTestCallbackInterfaceTypeArg", "TestTypedefs", 1, info.Length()), info.GetIsolate()); return; } TestTypedefs* impl = V8TestTypedefs::toImpl(info.Holder()); TestCallbackInterface* testCallbackInterfaceTypeArg; { if (info.Length() <= 0 || !info[0]->IsFunction()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("voidMethodTestCallbackInterfaceTypeArg", "TestTypedefs", "The callback provided as parameter 1 is not a function.")); return; } testCallbackInterfaceTypeArg = V8TestCallbackInterface::create(v8::Local<v8::Function>::Cast(info[0]), ScriptState::current(info.GetIsolate())); } impl->voidMethodTestCallbackInterfaceTypeArg(testCallbackInterfaceTypeArg); } static void voidMethodTestCallbackInterfaceTypeArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); TestTypedefsV8Internal::voidMethodTestCallbackInterfaceTypeArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void uLongLongMethodTestInterfaceEmptyTypeSequenceArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "uLongLongMethodTestInterfaceEmptyTypeSequenceArg", "TestTypedefs", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 1)) { setMinimumArityTypeError(exceptionState, 1, info.Length()); exceptionState.throwIfNeeded(); return; } TestTypedefs* impl = V8TestTypedefs::toImpl(info.Holder()); Vector<RefPtr<TestInterfaceEmpty>> testInterfaceEmptyTypeSequenceArg; { testInterfaceEmptyTypeSequenceArg = (toRefPtrNativeArray<TestInterfaceEmpty, V8TestInterfaceEmpty>(info[0], 1, info.GetIsolate(), exceptionState)); if (exceptionState.throwIfNeeded()) return; } v8SetReturnValue(info, static_cast<double>(impl->uLongLongMethodTestInterfaceEmptyTypeSequenceArg(testInterfaceEmptyTypeSequenceArg))); } static void uLongLongMethodTestInterfaceEmptyTypeSequenceArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); TestTypedefsV8Internal::uLongLongMethodTestInterfaceEmptyTypeSequenceArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void testInterfaceOrTestInterfaceEmptyMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestTypedefs* impl = V8TestTypedefs::toImpl(info.Holder()); TestInterfaceOrTestInterfaceEmpty result; impl->testInterfaceOrTestInterfaceEmptyMethod(result); v8SetReturnValue(info, result); } static void testInterfaceOrTestInterfaceEmptyMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); TestTypedefsV8Internal::testInterfaceOrTestInterfaceEmptyMethodMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void domStringOrDoubleMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestTypedefs* impl = V8TestTypedefs::toImpl(info.Holder()); StringOrDouble result; impl->domStringOrDoubleMethod(result); v8SetReturnValue(info, result); } static void domStringOrDoubleMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); TestTypedefsV8Internal::domStringOrDoubleMethodMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void arrayOfStringsMethodArrayOfStringsArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "arrayOfStringsMethodArrayOfStringsArg", "TestTypedefs", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 1)) { setMinimumArityTypeError(exceptionState, 1, info.Length()); exceptionState.throwIfNeeded(); return; } TestTypedefs* impl = V8TestTypedefs::toImpl(info.Holder()); Vector<String> arrayOfStringsArg; { arrayOfStringsArg = toImplArray<Vector<String>>(info[0], 1, info.GetIsolate(), exceptionState); if (exceptionState.throwIfNeeded()) return; } v8SetReturnValue(info, toV8(impl->arrayOfStringsMethodArrayOfStringsArg(arrayOfStringsArg), info.Holder(), info.GetIsolate())); } static void arrayOfStringsMethodArrayOfStringsArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); TestTypedefsV8Internal::arrayOfStringsMethodArrayOfStringsArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void stringArrayMethodStringArrayArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "stringArrayMethodStringArrayArg", "TestTypedefs", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 1)) { setMinimumArityTypeError(exceptionState, 1, info.Length()); exceptionState.throwIfNeeded(); return; } TestTypedefs* impl = V8TestTypedefs::toImpl(info.Holder()); Vector<String> stringArrayArg; { stringArrayArg = toImplArray<Vector<String>>(info[0], 1, info.GetIsolate(), exceptionState); if (exceptionState.throwIfNeeded()) return; } v8SetReturnValue(info, toV8(impl->stringArrayMethodStringArrayArg(stringArrayArg), info.Holder(), info.GetIsolate())); } static void stringArrayMethodStringArrayArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod"); TestTypedefsV8Internal::stringArrayMethodStringArrayArgMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution"); } static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) { if (UNLIKELY(info.Length() < 1)) { V8ThrowException::throwException(createMinimumArityTypeErrorForConstructor(info.GetIsolate(), "TestTypedefs", 1, info.Length()), info.GetIsolate()); return; } V8StringResource<> stringArg; { stringArg = info[0]; if (!stringArg.prepare()) return; } RefPtr<TestTypedefs> impl = TestTypedefs::create(stringArg); v8::Local<v8::Object> wrapper = info.Holder(); wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestTypedefs::wrapperTypeInfo, wrapper); v8SetReturnValue(info, wrapper); } } // namespace TestTypedefsV8Internal // Suppress warning: global constructors, because AttributeConfiguration is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif static const V8DOMConfiguration::AttributeConfiguration V8TestTypedefsAttributes[] = { {"tAttribute", v8ConstructorAttributeGetter, TestTypedefsV8Internal::tAttributeAttributeSetterCallback, 0, 0, const_cast<WrapperTypeInfo*>(&V8TestInterface::wrapperTypeInfo), static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::DontEnum), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnInstance, V8DOMConfiguration::CheckHolder}, }; #if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG) #pragma clang diagnostic pop #endif static const V8DOMConfiguration::AccessorConfiguration V8TestTypedefsAccessors[] = { {"uLongLongAttribute", TestTypedefsV8Internal::uLongLongAttributeAttributeGetterCallback, TestTypedefsV8Internal::uLongLongAttributeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder}, }; static const V8DOMConfiguration::MethodConfiguration V8TestTypedefsMethods[] = { {"voidMethodArrayOfLongsArg", TestTypedefsV8Internal::voidMethodArrayOfLongsArgMethodCallback, 0, 0, V8DOMConfiguration::ExposedToAllScripts}, {"voidMethodFloatArgStringArg", TestTypedefsV8Internal::voidMethodFloatArgStringArgMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts}, {"voidMethodTestCallbackInterfaceTypeArg", TestTypedefsV8Internal::voidMethodTestCallbackInterfaceTypeArgMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts}, {"uLongLongMethodTestInterfaceEmptyTypeSequenceArg", TestTypedefsV8Internal::uLongLongMethodTestInterfaceEmptyTypeSequenceArgMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts}, {"testInterfaceOrTestInterfaceEmptyMethod", TestTypedefsV8Internal::testInterfaceOrTestInterfaceEmptyMethodMethodCallback, 0, 0, V8DOMConfiguration::ExposedToAllScripts}, {"domStringOrDoubleMethod", TestTypedefsV8Internal::domStringOrDoubleMethodMethodCallback, 0, 0, V8DOMConfiguration::ExposedToAllScripts}, {"arrayOfStringsMethodArrayOfStringsArg", TestTypedefsV8Internal::arrayOfStringsMethodArrayOfStringsArgMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts}, {"stringArrayMethodStringArrayArg", TestTypedefsV8Internal::stringArrayMethodStringArrayArgMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts}, }; void V8TestTypedefs::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "DOMConstructor"); if (!info.IsConstructCall()) { V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::constructorNotCallableAsFunction("TestTypedefs")); return; } if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) { v8SetReturnValue(info, info.Holder()); return; } TestTypedefsV8Internal::constructor(info); } static void installV8TestTypedefsTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "TestTypedefs", v8::Local<v8::FunctionTemplate>(), V8TestTypedefs::internalFieldCount, V8TestTypedefsAttributes, WTF_ARRAY_LENGTH(V8TestTypedefsAttributes), V8TestTypedefsAccessors, WTF_ARRAY_LENGTH(V8TestTypedefsAccessors), V8TestTypedefsMethods, WTF_ARRAY_LENGTH(V8TestTypedefsMethods)); functionTemplate->SetCallHandler(V8TestTypedefs::constructorCallback); functionTemplate->SetLength(1); v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instanceTemplate); v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototypeTemplate); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Local<v8::FunctionTemplate> V8TestTypedefs::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TestTypedefsTemplate); } bool V8TestTypedefs::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Local<v8::Object> V8TestTypedefs::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } TestTypedefs* V8TestTypedefs::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) { return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0; } void V8TestTypedefs::refObject(ScriptWrappable* scriptWrappable) { scriptWrappable->toImpl<TestTypedefs>()->ref(); } void V8TestTypedefs::derefObject(ScriptWrappable* scriptWrappable) { scriptWrappable->toImpl<TestTypedefs>()->deref(); } } // namespace blink
48.031477
494
0.768161
[ "object", "vector" ]
4fdc650f38bd194c035360f4fc6f3f5655f9be0b
33,452
cpp
C++
applications/FluidDynamicsApplication/custom_elements/fluid_element.cpp
cwx-ae/Kratos
25e73148a1db56a142650a1e19f195124888c6cd
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/FluidDynamicsApplication/custom_elements/fluid_element.cpp
cwx-ae/Kratos
25e73148a1db56a142650a1e19f195124888c6cd
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/FluidDynamicsApplication/custom_elements/fluid_element.cpp
cwx-ae/Kratos
25e73148a1db56a142650a1e19f195124888c6cd
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Jordi Cotela // #include "fluid_element.h" #include "includes/cfd_variables.h" #include "includes/checks.h" #include "custom_utilities/qsvms_data.h" #include "custom_utilities/time_integrated_qsvms_data.h" #include "custom_utilities/qsvms_dem_coupled_data.h" #include "custom_utilities/fic_data.h" #include "custom_utilities/time_integrated_fic_data.h" #include "custom_utilities/symbolic_stokes_data.h" #include "custom_utilities/two_fluid_navier_stokes_data.h" #include "custom_utilities/weakly_compressible_navier_stokes_data.h" #include "utilities/element_size_calculator.h" #include "custom_utilities/vorticity_utilities.h" namespace Kratos { /////////////////////////////////////////////////////////////////////////////////////////////////// // Life cycle template< class TElementData > FluidElement<TElementData>::FluidElement(IndexType NewId): Element(NewId) {} template< class TElementData > FluidElement<TElementData>::FluidElement(IndexType NewId, const NodesArrayType& ThisNodes): Element(NewId,ThisNodes) {} template< class TElementData > FluidElement<TElementData>::FluidElement(IndexType NewId, GeometryType::Pointer pGeometry): Element(NewId,pGeometry) {} template< class TElementData > FluidElement<TElementData>::FluidElement(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties): Element(NewId,pGeometry,pProperties) {} template< class TElementData > FluidElement<TElementData>::~FluidElement() {} /////////////////////////////////////////////////////////////////////////////////////////////////// // Public Operations template< class TElementData > Element::Pointer FluidElement<TElementData>::Create(IndexType NewId,NodesArrayType const& ThisNodes,PropertiesType::Pointer pProperties) const { KRATOS_TRY; KRATOS_ERROR << "Attempting to Create base FluidElement instances." << std::endl; KRATOS_CATCH(""); } template< class TElementData > Element::Pointer FluidElement<TElementData>::Create(IndexType NewId, GeometryType::Pointer pGeom, PropertiesType::Pointer pProperties) const { KRATOS_TRY; KRATOS_ERROR << "Attempting to Create base FluidElement instances." << std::endl; KRATOS_CATCH(""); } template< class TElementData > void FluidElement<TElementData>::Initialize(const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; // If we are restarting, the constitutive law will be already defined if (mpConstitutiveLaw == nullptr) { const Properties& r_properties = this->GetProperties(); KRATOS_ERROR_IF_NOT(r_properties.Has(CONSTITUTIVE_LAW)) << "In initialization of Element " << this->Info() << ": No CONSTITUTIVE_LAW defined for property " << r_properties.Id() << "." << std::endl; mpConstitutiveLaw = r_properties[CONSTITUTIVE_LAW]->Clone(); const GeometryType& r_geometry = this->GetGeometry(); const auto& r_shape_functions = r_geometry.ShapeFunctionsValues(GeometryData::GI_GAUSS_1); mpConstitutiveLaw->InitializeMaterial(r_properties,r_geometry,row(r_shape_functions,0)); } KRATOS_CATCH(""); } template <class TElementData> void FluidElement<TElementData>::CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, const ProcessInfo& rCurrentProcessInfo) { // Resize and intialize output if (rLeftHandSideMatrix.size1() != LocalSize) rLeftHandSideMatrix.resize(LocalSize, LocalSize, false); if (rRightHandSideVector.size() != LocalSize) rRightHandSideVector.resize(LocalSize, false); noalias(rLeftHandSideMatrix) = ZeroMatrix(LocalSize, LocalSize); noalias(rRightHandSideVector) = ZeroVector(LocalSize); if (TElementData::ElementManagesTimeIntegration) { // Get Shape function data Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_derivatives; this->CalculateGeometryData( gauss_weights, shape_functions, shape_derivatives); const unsigned int number_of_gauss_points = gauss_weights.size(); TElementData data; data.Initialize(*this, rCurrentProcessInfo); // Iterate over integration points to evaluate local contribution for (unsigned int g = 0; g < number_of_gauss_points; g++) { this->UpdateIntegrationPointData( data, g, gauss_weights[g], row(shape_functions, g),shape_derivatives[g]); this->AddTimeIntegratedSystem( data, rLeftHandSideMatrix, rRightHandSideVector); } } } template <class TElementData> void FluidElement<TElementData>::CalculateLeftHandSide(MatrixType& rLeftHandSideMatrix, const ProcessInfo& rCurrentProcessInfo) { // Resize and intialize output if (rLeftHandSideMatrix.size1() != LocalSize) rLeftHandSideMatrix.resize(LocalSize, LocalSize, false); noalias(rLeftHandSideMatrix) = ZeroMatrix(LocalSize, LocalSize); if (TElementData::ElementManagesTimeIntegration) { // Get Shape function data Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_derivatives; this->CalculateGeometryData( gauss_weights, shape_functions, shape_derivatives); const unsigned int number_of_gauss_points = gauss_weights.size(); TElementData data; data.Initialize(*this, rCurrentProcessInfo); // Iterate over integration points to evaluate local contribution for (unsigned int g = 0; g < number_of_gauss_points; g++) { this->UpdateIntegrationPointData( data, g, gauss_weights[g], row(shape_functions, g),shape_derivatives[g]); this->AddTimeIntegratedLHS(data, rLeftHandSideMatrix); } } } template <class TElementData> void FluidElement<TElementData>::CalculateRightHandSide(VectorType& rRightHandSideVector, const ProcessInfo& rCurrentProcessInfo) { if (rRightHandSideVector.size() != LocalSize) rRightHandSideVector.resize(LocalSize, false); noalias(rRightHandSideVector) = ZeroVector(LocalSize); if (TElementData::ElementManagesTimeIntegration) { // Get Shape function data Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_derivatives; this->CalculateGeometryData( gauss_weights, shape_functions, shape_derivatives); const unsigned int number_of_gauss_points = gauss_weights.size(); TElementData data; data.Initialize(*this, rCurrentProcessInfo); // Iterate over integration points to evaluate local contribution for (unsigned int g = 0; g < number_of_gauss_points; g++) { this->UpdateIntegrationPointData( data, g, gauss_weights[g], row(shape_functions, g),shape_derivatives[g]); this->AddTimeIntegratedRHS(data, rRightHandSideVector); } } } template <class TElementData> void FluidElement<TElementData>::CalculateLocalVelocityContribution( MatrixType& rDampMatrix, VectorType& rRightHandSideVector, const ProcessInfo& rCurrentProcessInfo) { // Resize and intialize output if( rDampMatrix.size1() != LocalSize ) rDampMatrix.resize(LocalSize,LocalSize,false); if( rRightHandSideVector.size() != LocalSize ) rRightHandSideVector.resize(LocalSize,false); noalias(rDampMatrix) = ZeroMatrix(LocalSize,LocalSize); noalias(rRightHandSideVector) = ZeroVector(LocalSize); if (!TElementData::ElementManagesTimeIntegration) { // Get Shape function data Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_derivatives; this->CalculateGeometryData( gauss_weights, shape_functions, shape_derivatives); const unsigned int number_of_gauss_points = gauss_weights.size(); TElementData data; data.Initialize(*this, rCurrentProcessInfo); // Iterate over integration points to evaluate local contribution for (unsigned int g = 0; g < number_of_gauss_points; g++) { const auto& r_dndx = shape_derivatives[g]; this->UpdateIntegrationPointData( data, g, gauss_weights[g], row(shape_functions, g),r_dndx); this->AddVelocitySystem(data, rDampMatrix, rRightHandSideVector); } } } template <class TElementData> void FluidElement<TElementData>::CalculateMassMatrix(MatrixType& rMassMatrix, const ProcessInfo& rCurrentProcessInfo) { // Resize and intialize output if (rMassMatrix.size1() != LocalSize) rMassMatrix.resize(LocalSize, LocalSize, false); noalias(rMassMatrix) = ZeroMatrix(LocalSize, LocalSize); if (!TElementData::ElementManagesTimeIntegration) { // Get Shape function data Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_derivatives; this->CalculateGeometryData( gauss_weights, shape_functions, shape_derivatives); const unsigned int number_of_gauss_points = gauss_weights.size(); TElementData data; data.Initialize(*this, rCurrentProcessInfo); // Iterate over integration points to evaluate local contribution for (unsigned int g = 0; g < number_of_gauss_points; g++) { this->UpdateIntegrationPointData( data, g, gauss_weights[g], row(shape_functions, g),shape_derivatives[g]); this->AddMassLHS(data, rMassMatrix); } } } template< class TElementData > void FluidElement< TElementData >::EquationIdVector(EquationIdVectorType &rResult, const ProcessInfo &rCurrentProcessInfo) const { const GeometryType& r_geometry = this->GetGeometry(); unsigned int LocalIndex = 0; if (rResult.size() != LocalSize) rResult.resize(LocalSize, false); const unsigned int xpos = this->GetGeometry()[0].GetDofPosition(VELOCITY_X); const unsigned int ppos = this->GetGeometry()[0].GetDofPosition(PRESSURE); for (unsigned int i = 0; i < NumNodes; ++i) { rResult[LocalIndex++] = r_geometry[i].GetDof(VELOCITY_X,xpos).EquationId(); rResult[LocalIndex++] = r_geometry[i].GetDof(VELOCITY_Y,xpos+1).EquationId(); if (Dim == 3) rResult[LocalIndex++] = r_geometry[i].GetDof(VELOCITY_Z,xpos+2).EquationId(); rResult[LocalIndex++] = r_geometry[i].GetDof(PRESSURE,ppos).EquationId(); } } template< class TElementData > void FluidElement< TElementData >::GetDofList(DofsVectorType &rElementalDofList, const ProcessInfo &rCurrentProcessInfo) const { const GeometryType& r_geometry = this->GetGeometry(); if (rElementalDofList.size() != LocalSize) rElementalDofList.resize(LocalSize); const unsigned int xpos = this->GetGeometry()[0].GetDofPosition(VELOCITY_X); const unsigned int ppos = this->GetGeometry()[0].GetDofPosition(PRESSURE); unsigned int LocalIndex = 0; for (unsigned int i = 0; i < NumNodes; ++i) { rElementalDofList[LocalIndex++] = r_geometry[i].pGetDof(VELOCITY_X,xpos); rElementalDofList[LocalIndex++] = r_geometry[i].pGetDof(VELOCITY_Y,xpos+1); if (Dim == 3) rElementalDofList[LocalIndex++] = r_geometry[i].pGetDof(VELOCITY_Z,xpos+2); rElementalDofList[LocalIndex++] = r_geometry[i].pGetDof(PRESSURE,ppos); } } /////////////////////////////////////////////////////////////////////////////////////////////////// template< class TElementData > void FluidElement<TElementData>::GetFirstDerivativesVector(Vector &rValues, int Step) const { const GeometryType& r_geometry = this->GetGeometry(); if (rValues.size() != LocalSize) rValues.resize(LocalSize,false); unsigned int Index = 0; for (unsigned int i = 0; i < NumNodes; i++) { const array_1d<double,3>& rVel = r_geometry[i].FastGetSolutionStepValue(VELOCITY,Step); for (unsigned int d = 0; d < Dim; d++) rValues[Index++] = rVel[d]; rValues[Index++] = r_geometry[i].FastGetSolutionStepValue(PRESSURE,Step); } } template< class TElementData > void FluidElement<TElementData>::GetSecondDerivativesVector(Vector &rValues, int Step) const { const GeometryType& r_geometry = this->GetGeometry(); if (rValues.size() != LocalSize) rValues.resize(LocalSize,false); unsigned int index = 0; for (unsigned int i = 0; i < NumNodes; i++) { const array_1d<double,3>& r_acceleration = r_geometry[i].FastGetSolutionStepValue(ACCELERATION,Step); for (unsigned int d = 0; d < Dim; d++) rValues[index++] = r_acceleration[d]; rValues[index++] = 0.0; // skip pressure Dof } } template< class TElementData > GeometryData::IntegrationMethod FluidElement<TElementData>::GetIntegrationMethod() const { return GeometryData::GI_GAUSS_2; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Inquiry template< class TElementData > int FluidElement<TElementData>::Check(const ProcessInfo &rCurrentProcessInfo) const { // Generic geometry check int out = Element::Check(rCurrentProcessInfo); if (out != 0) { return out; } // Check variables used by TElementData out = TElementData::Check(*this, rCurrentProcessInfo); KRATOS_ERROR_IF_NOT(out == 0) << "Something is wrong with the elemental data of Element " << this->Info() << std::endl; const GeometryType& r_geometry = this->GetGeometry(); for(unsigned int i=0; i<NumNodes; ++i) { const Node<3>& rNode = r_geometry[i]; KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(ACCELERATION,rNode); // Check that required dofs exist KRATOS_CHECK_DOF_IN_NODE(VELOCITY_X,rNode); KRATOS_CHECK_DOF_IN_NODE(VELOCITY_Y,rNode); if (Dim == 3) KRATOS_CHECK_DOF_IN_NODE(VELOCITY_Z,rNode); KRATOS_CHECK_DOF_IN_NODE(PRESSURE,rNode); } // If this is a 2D problem, check that nodes are in XY plane if ( Dim == 2) { for (unsigned int i=0; i<NumNodes; ++i) { if (r_geometry[i].Z() != 0.0) KRATOS_ERROR << "Node " << r_geometry[i].Id() << "has non-zero Z coordinate." << std::endl; } } // Check the constitutive law KRATOS_ERROR_IF(mpConstitutiveLaw == nullptr) << "Constitutive Law not initialized for Element " << this->Info() << std::endl; constexpr auto dimension = Dim; // I need to set this here otherwise it gives me a linking error when attempting to '<<' Dim. KRATOS_ERROR_IF(mpConstitutiveLaw->WorkingSpaceDimension() != Dim) << "Wrong dimension: The " << mpConstitutiveLaw->WorkingSpaceDimension() << "D constitutive law " << mpConstitutiveLaw->Info() << " is not compatible with " << dimension << "D element " << this->Info() << "." << std::endl; out = mpConstitutiveLaw->Check(this->GetProperties(),r_geometry,rCurrentProcessInfo); KRATOS_ERROR_IF_NOT( out == 0) << "The Constitutive Law provided for Element " << this->Info() << " is not correct." << std::endl; return out; } /////////////////////////////////////////////////////////////////////////////////////////////////// template< class TElementData > void FluidElement<TElementData>::CalculateOnIntegrationPoints( Variable<array_1d<double, 3 > > const& rVariable, std::vector<array_1d<double, 3 > >& rValues, ProcessInfo const& rCurrentProcessInfo) { if (rVariable == VORTICITY) { // Get Shape function data Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_function_gradients; this->CalculateGeometryData(gauss_weights,shape_functions,shape_function_gradients); VorticityUtilities<Dim>::CalculateVorticityVector(this->GetGeometry(),shape_function_gradients,rValues); } } template< class TElementData > void FluidElement<TElementData>::CalculateOnIntegrationPoints( Variable<double> const& rVariable, std::vector<double>& rValues, ProcessInfo const& rCurrentProcessInfo) { if (rVariable == Q_VALUE) { // Get Shape function data Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_function_gradients; this->CalculateGeometryData(gauss_weights,shape_functions,shape_function_gradients); VorticityUtilities<Dim>::CalculateQValue(this->GetGeometry(),shape_function_gradients,rValues); } else if (rVariable == VORTICITY_MAGNITUDE) { // Get Shape function data Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_function_gradients; this->CalculateGeometryData(gauss_weights,shape_functions,shape_function_gradients); VorticityUtilities<Dim>::CalculateVorticityMagnitude(this->GetGeometry(),shape_function_gradients,rValues); } else if (rVariable == UPDATE_STATISTICS) { KRATOS_DEBUG_ERROR_IF(!rCurrentProcessInfo.Has(STATISTICS_CONTAINER)) << "Trying to compute turbulent statistics, but ProcessInfo does not have STATISTICS_CONTAINER defined." << std::endl; rCurrentProcessInfo.GetValue(STATISTICS_CONTAINER)->UpdateStatistics(this); } } template <class TElementData> void FluidElement<TElementData>::CalculateOnIntegrationPoints( Variable<array_1d<double, 6>> const& rVariable, std::vector<array_1d<double, 6>>& rValues, ProcessInfo const& rCurrentProcessInfo) {} template <class TElementData> void FluidElement<TElementData>::CalculateOnIntegrationPoints( Variable<Vector> const& rVariable, std::vector<Vector>& rValues, ProcessInfo const& rCurrentProcessInfo) {} template <class TElementData> void FluidElement<TElementData>::CalculateOnIntegrationPoints( Variable<Matrix> const& rVariable, std::vector<Matrix>& rValues, ProcessInfo const& rCurrentProcessInfo) {} /////////////////////////////////////////////////////////////////////////////////////////////////// // Input and output template< class TElementData > std::string FluidElement<TElementData>::Info() const { std::stringstream buffer; buffer << "FluidElement #" << Id(); return buffer.str(); } template< class TElementData > void FluidElement<TElementData>::PrintInfo(std::ostream& rOStream) const { rOStream << "FluidElement" << Dim << "D"; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Protected functions /////////////////////////////////////////////////////////////////////////////////////////////////// template <class TElementData> double FluidElement<TElementData>::GetAtCoordinate( const typename TElementData::NodalScalarData& rValues, const typename TElementData::ShapeFunctionsType& rN) const { double result = 0.0; for (size_t i = 0; i < NumNodes; i++) { result += rN[i] * rValues[i]; } return result; } template <class TElementData> array_1d<double, 3> FluidElement<TElementData>::GetAtCoordinate( const typename TElementData::NodalVectorData& rValues, const typename TElementData::ShapeFunctionsType& rN) const { array_1d<double, 3> result = ZeroVector(3); for (size_t i = 0; i < NumNodes; i++) { for (size_t j = 0; j < Dim; j++) { result[j] += rN[i] * rValues(i, j); } } return result; } template <class TElementData> BoundedMatrix<double, TElementData::Dim, TElementData::Dim> FluidElement<TElementData>::GetAtCoordinate( const typename TElementData::NodalTensorData &rValues, const typename TElementData::ShapeFunctionsType &rN) const { BoundedMatrix<double,Dim,Dim> result = ZeroMatrix(Dim,Dim); for (size_t i = 0; i < NumNodes; i++) { noalias(result) += rN[i] * rValues[i]; } return result; } template <class TElementData> double FluidElement<TElementData>::GetAtCoordinate( const double Value, const typename TElementData::ShapeFunctionsType& rN) const { return Value; } template <class TElementData> void FluidElement<TElementData>::UpdateIntegrationPointData( TElementData& rData, unsigned int IntegrationPointIndex, double Weight, const typename TElementData::MatrixRowType& rN, const typename TElementData::ShapeDerivativesType& rDN_DX) const { rData.UpdateGeometryValues(IntegrationPointIndex, Weight, rN, rDN_DX); this->CalculateMaterialResponse(rData); } template <class TElementData> void FluidElement<TElementData>::CalculateMaterialResponse(TElementData& rData) const { this->CalculateStrainRate(rData); auto& Values = rData.ConstitutiveLawValues; const Vector& shape_functions_vector = rData.N; const Matrix& shape_functions_derivative_matrix = rData.DN_DX; Values.SetShapeFunctionsValues(shape_functions_vector); Values.SetShapeFunctionsDerivatives(shape_functions_derivative_matrix); //ATTENTION: here we assume that only one constitutive law is employed for all of the gauss points in the element. //this is ok under the hypothesis that no history dependent behavior is employed mpConstitutiveLaw->CalculateMaterialResponseCauchy(Values); mpConstitutiveLaw->CalculateValue(Values,EFFECTIVE_VISCOSITY,rData.EffectiveViscosity); } template <class TElementData> void FluidElement<TElementData>::CalculateStrainRate(TElementData& rData) const { Internals::StrainRateSpecialization<TElementData,Dim>::Calculate( rData.StrainRate, rData.Velocity, rData.DN_DX); } template< class TElementData > void FluidElement<TElementData>::CalculateGeometryData(Vector &rGaussWeights, Matrix &rNContainer, ShapeFunctionDerivativesArrayType &rDN_DX) const { const GeometryData::IntegrationMethod integration_method = this->GetIntegrationMethod(); const GeometryType& r_geometry = this->GetGeometry(); const unsigned int number_of_gauss_points = r_geometry.IntegrationPointsNumber(integration_method); Vector DetJ; r_geometry.ShapeFunctionsIntegrationPointsGradients(rDN_DX,DetJ,integration_method); if (rNContainer.size1() != number_of_gauss_points || rNContainer.size2() != NumNodes) { rNContainer.resize(number_of_gauss_points,NumNodes,false); } rNContainer = r_geometry.ShapeFunctionsValues(integration_method); const GeometryType::IntegrationPointsArrayType& IntegrationPoints = r_geometry.IntegrationPoints(integration_method); if (rGaussWeights.size() != number_of_gauss_points) { rGaussWeights.resize(number_of_gauss_points,false); } for (unsigned int g = 0; g < number_of_gauss_points; g++) rGaussWeights[g] = DetJ[g] * IntegrationPoints[g].Weight(); } template <class TElementData> void FluidElement<TElementData>::Calculate( const Variable<double> &rVariable, double &rOutput, const ProcessInfo &rCurrentProcessInfo) { Element::Calculate(rVariable, rOutput, rCurrentProcessInfo); } template <class TElementData> void FluidElement<TElementData>::Calculate( const Variable<array_1d<double, 3>> &rVariable, array_1d<double, 3> &rOutput, const ProcessInfo &rCurrentProcessInfo) { Element::Calculate(rVariable, rOutput, rCurrentProcessInfo); } template <class TElementData> void FluidElement<TElementData>::Calculate( const Variable<Vector >& rVariable, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo ) { noalias( rOutput ) = ZeroVector( StrainSize ); if (rVariable == FLUID_STRESS) { // creating a new data container that goes out of scope after the function is left TElementData data_local; // transferring the velocity (among other variables) data_local.Initialize(*this, rCurrentProcessInfo); Vector gauss_weights; Matrix shape_functions; ShapeFunctionDerivativesArrayType shape_derivatives; // computing DN_DX values for the strain rate this->CalculateGeometryData(gauss_weights, shape_functions, shape_derivatives); const unsigned int number_of_gauss_points = gauss_weights.size(); double sum_of_gauss_weights = 0.0; for (unsigned int g = 0; g < number_of_gauss_points; g++){ this->UpdateIntegrationPointData(data_local, g, gauss_weights[g], row(shape_functions, g), shape_derivatives[g]); const Vector gauss_point_contribution = data_local.ShearStress; noalias( rOutput ) += gauss_point_contribution * gauss_weights[g]; sum_of_gauss_weights += gauss_weights[g]; } for (unsigned int i = 0; i < StrainSize; i++){ rOutput[i] = ( 1.0 / sum_of_gauss_weights ) * rOutput[i]; } } else { Element::Calculate(rVariable, rOutput, rCurrentProcessInfo); } } template <class TElementData> void FluidElement<TElementData>::Calculate( const Variable<Matrix> &rVariable, Matrix &rOutput, const ProcessInfo &rCurrentProcessInfo) { Element::Calculate(rVariable, rOutput, rCurrentProcessInfo); } /////////////////////////////////////////////////////////////////////////////////////////////////// template< class TElementData > void FluidElement<TElementData>::ConvectionOperator(Vector &rResult, const array_1d<double,3> &rConvVel, const ShapeFunctionDerivativesType &DN_DX) const { if(rResult.size() != NumNodes) rResult.resize(NumNodes,false); for (unsigned int i = 0; i < NumNodes; i++) { rResult[i] = rConvVel[0]*DN_DX(i,0); for(unsigned int k = 1; k < Dim; k++) rResult[i] += rConvVel[k]*DN_DX(i,k); } } template <class TElementData> void FluidElement<TElementData>::AddTimeIntegratedSystem( TElementData& rData, MatrixType& rLHS, VectorType& rRHS) { KRATOS_TRY; KRATOS_ERROR << "Calling base FluidElement::AddTimeIntegratedSystem " "implementation. This method is not supported by your " "element." << std::endl; KRATOS_CATCH(""); } template <class TElementData> void FluidElement<TElementData>::AddTimeIntegratedLHS( TElementData& rData, MatrixType& rLHS) { KRATOS_TRY; KRATOS_ERROR << "Calling base FluidElement::AddTimeIntegratedLHS " "implementation. This method is not supported by your " "element." << std::endl; KRATOS_CATCH(""); } template <class TElementData> void FluidElement<TElementData>::AddTimeIntegratedRHS( TElementData& rData, VectorType& rRHS) { KRATOS_TRY; KRATOS_ERROR << "Calling base FluidElement::AddTimeIntegratedRHS " "implementation. This method is not supported by your " "element." << std::endl; KRATOS_CATCH(""); } template <class TElementData> void FluidElement<TElementData>::AddVelocitySystem( TElementData& rData, MatrixType& rLocalLHS, VectorType& rLocalRHS) { KRATOS_TRY; KRATOS_ERROR << "Calling base FluidElement::AddVelocitySystem " "implementation. This method is not supported by your " "element." << std::endl; KRATOS_CATCH(""); } template <class TElementData> void FluidElement<TElementData>::AddMassLHS( TElementData& rData, MatrixType& rMassMatrix) { KRATOS_TRY; KRATOS_ERROR << "Calling base FluidElement::AddMassLHS " "implementation. This method is not supported by your " "element." << std::endl; KRATOS_CATCH(""); } template <class TElementData> void FluidElement<TElementData>::AddBoundaryTraction(TElementData& rData, const Vector& rUnitNormal, MatrixType& rLHS, VectorType& rRHS) { KRATOS_TRY; KRATOS_ERROR << "Calling base FluidElement::AddBoundaryTraction " "implementation. This method is not supported by your " "element." << std::endl; KRATOS_CATCH(""); } template <class TElementData> void FluidElement<TElementData>::GetCurrentValuesVector( const TElementData& rData, array_1d<double,LocalSize>& rValues) const { int local_index = 0; const auto& r_velocities = rData.Velocity; const auto& r_pressures = rData.Pressure; for (unsigned int i = 0; i < NumNodes; ++i) { for (unsigned int d = 0; d < Dim; ++d) // Velocity Dofs rValues[local_index++] = r_velocities(i, d); rValues[local_index++] = r_pressures[i]; // Pressure Dof } } template< class TElementData > ConstitutiveLaw::Pointer FluidElement<TElementData>::GetConstitutiveLaw() { return this->mpConstitutiveLaw; } template< class TElementData > const ConstitutiveLaw::Pointer FluidElement<TElementData>::GetConstitutiveLaw() const { return this->mpConstitutiveLaw; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Private functions /////////////////////////////////////////////////////////////////////////////////////////////////// // serializer template< class TElementData > void FluidElement<TElementData>::save(Serializer& rSerializer) const { KRATOS_SERIALIZE_SAVE_BASE_CLASS(rSerializer, Element ); rSerializer.save("mpConstitutiveLaw",this->mpConstitutiveLaw); } template< class TElementData > void FluidElement<TElementData>::load(Serializer& rSerializer) { KRATOS_SERIALIZE_LOAD_BASE_CLASS(rSerializer, Element); rSerializer.load("mpConstitutiveLaw",this->mpConstitutiveLaw); } /////////////////////////////////////////////////////////////////////////////////////////////////// namespace Internals { template< class TElementData > void StrainRateSpecialization<TElementData,2>::Calculate( Vector& rStrainRate, const typename TElementData::NodalVectorData& rVelocities, const typename TElementData::ShapeDerivativesType& rDNDX) { noalias(rStrainRate) = ZeroVector(3); for (unsigned int i = 0; i < TElementData::NumNodes; i++) { rStrainRate[0] += rDNDX(i,0)*rVelocities(i,0); rStrainRate[1] += rDNDX(i,1)*rVelocities(i,1); rStrainRate[2] += rDNDX(i,0)*rVelocities(i,1) + rDNDX(i,1)*rVelocities(i,0); } } template< class TElementData > void StrainRateSpecialization<TElementData,3>::Calculate( Vector& rStrainRate, const typename TElementData::NodalVectorData& rVelocities, const typename TElementData::ShapeDerivativesType& rDNDX) { noalias(rStrainRate) = ZeroVector(6); for (unsigned int i = 0; i < TElementData::NumNodes; i++) { rStrainRate[0] += rDNDX(i,0)*rVelocities(i,0); rStrainRate[1] += rDNDX(i,1)*rVelocities(i,1); rStrainRate[2] += rDNDX(i,2)*rVelocities(i,2); rStrainRate[3] += rDNDX(i,0)*rVelocities(i,1) + rDNDX(i,1)*rVelocities(i,0); rStrainRate[4] += rDNDX(i,1)*rVelocities(i,2) + rDNDX(i,2)*rVelocities(i,1); rStrainRate[5] += rDNDX(i,0)*rVelocities(i,2) + rDNDX(i,2)*rVelocities(i,0); } } } // namespace Internals /////////////////////////////////////////////////////////////////////////////////////////////////// // Template class instantiation template class FluidElement< SymbolicStokesData<2,3> >; template class FluidElement< SymbolicStokesData<2,4> >; template class FluidElement< SymbolicStokesData<3,4> >; template class FluidElement< SymbolicStokesData<3,6> >; template class FluidElement< SymbolicStokesData<3,8> >; template class FluidElement< WeaklyCompressibleNavierStokesData<2,3> >; template class FluidElement< WeaklyCompressibleNavierStokesData<3,4> >; template class FluidElement< QSVMSData<2,3> >; template class FluidElement< QSVMSData<3,4> >; template class FluidElement< QSVMSData<2,4> >; template class FluidElement< QSVMSData<3,8> >; template class FluidElement< TimeIntegratedQSVMSData<2,3> >; template class FluidElement< TimeIntegratedQSVMSData<3,4> >; template class FluidElement< QSVMSDEMCoupledData<2,3> >; template class FluidElement< QSVMSDEMCoupledData<3,4> >; template class FluidElement< QSVMSDEMCoupledData<2,4> >; template class FluidElement< QSVMSDEMCoupledData<3,8> >; template class FluidElement< FICData<2,3> >; template class FluidElement< FICData<3,4> >; template class FluidElement< FICData<2,4> >; template class FluidElement< FICData<3,8> >; template class FluidElement< TimeIntegratedFICData<2,3> >; template class FluidElement< TimeIntegratedFICData<3,4> >; template class FluidElement< TwoFluidNavierStokesData<2, 3> >; template class FluidElement< TwoFluidNavierStokesData<3, 4> >; /////////////////////////////////////////////////////////////////////////////////////////////////// }
35.436441
196
0.666149
[ "geometry", "shape", "vector" ]
4fdcef85d1f23561e628a07f885dace10ba91805
70,835
cc
C++
chrome/browser/history/history_backend.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
chrome/browser/history/history_backend.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/history/history_backend.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/history/history_backend.h" #include <set> #include "base/compiler_specific.h" #include "base/file_util.h" #include "base/histogram.h" #include "base/message_loop.h" #include "base/scoped_ptr.h" #include "base/scoped_vector.h" #include "base/string_util.h" #include "base/time.h" #include "chrome/browser/autocomplete/history_url_provider.h" #include "chrome/browser/bookmarks/bookmark_service.h" #include "chrome/browser/history/download_types.h" #include "chrome/browser/history/history_notifications.h" #include "chrome/browser/history/history_publisher.h" #include "chrome/browser/history/in_memory_history_backend.h" #include "chrome/browser/history/page_usage_data.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/notification_type.h" #include "chrome/common/sqlite_utils.h" #include "chrome/common/url_constants.h" #include "googleurl/src/gurl.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/registry_controlled_domain.h" using base::Time; using base::TimeDelta; using base::TimeTicks; /* The HistoryBackend consists of a number of components: HistoryDatabase (stores past 3 months of history) URLDatabase (stores a list of URLs) DownloadDatabase (stores a list of downloads) VisitDatabase (stores a list of visits for the URLs) VisitSegmentDatabase (stores groups of URLs for the most visited view). ArchivedDatabase (stores history older than 3 months) URLDatabase (stores a list of URLs) DownloadDatabase (stores a list of downloads) VisitDatabase (stores a list of visits for the URLs) (this does not store visit segments as they expire after 3 mos.) TextDatabaseManager (manages multiple text database for different times) TextDatabase (represents a single month of full-text index). ...more TextDatabase objects... ExpireHistoryBackend (manages moving things from HistoryDatabase to the ArchivedDatabase and deleting) */ namespace history { // How long we keep segment data for in days. Currently 3 months. // This value needs to be greater or equal to // MostVisitedModel::kMostVisitedScope but we don't want to introduce a direct // dependency between MostVisitedModel and the history backend. static const int kSegmentDataRetention = 90; // The number of milliseconds we'll wait to do a commit, so that things are // batched together. static const int kCommitIntervalMs = 10000; // The amount of time before we re-fetch the favicon. static const int kFavIconRefetchDays = 7; // GetSessionTabs returns all open tabs, or tabs closed kSessionCloseTimeWindow // seconds ago. static const int kSessionCloseTimeWindowSecs = 10; // The maximum number of items we'll allow in the redirect list before // deleting some. static const int kMaxRedirectCount = 32; // The number of days old a history entry can be before it is considered "old" // and is archived. static const int kArchiveDaysThreshold = 90; // This task is run on a timer so that commits happen at regular intervals // so they are batched together. The important thing about this class is that // it supports canceling of the task so the reference to the backend will be // freed. The problem is that when history is shutting down, there is likely // to be one of these commits still pending and holding a reference. // // The backend can call Cancel to have this task release the reference. The // task will still run (if we ever get to processing the event before // shutdown), but it will not do anything. // // Note that this is a refcounted object and is not a task in itself. It should // be assigned to a RunnableMethod. // // TODO(brettw): bug 1165182: This should be replaced with a // ScopedRunnableMethodFactory which will handle everything automatically (like // we do in ExpireHistoryBackend). class CommitLaterTask : public base::RefCounted<CommitLaterTask> { public: explicit CommitLaterTask(HistoryBackend* history_backend) : history_backend_(history_backend) { } // The backend will call this function if it is being destroyed so that we // release our reference. void Cancel() { history_backend_ = NULL; } void RunCommit() { if (history_backend_.get()) history_backend_->Commit(); } private: friend class base::RefCounted<CommitLaterTask>; ~CommitLaterTask() {} scoped_refptr<HistoryBackend> history_backend_; }; // Handles querying first the main database, then the full text database if that // fails. It will optionally keep track of all URLs seen so duplicates can be // eliminated. This is used by the querying sub-functions. // // TODO(brettw): This class may be able to be simplified or eliminated. After // this was written, QueryResults can efficiently look up by URL, so the need // for this extra set of previously queried URLs is less important. class HistoryBackend::URLQuerier { public: URLQuerier(URLDatabase* main_db, URLDatabase* archived_db, bool track_unique) : main_db_(main_db), archived_db_(archived_db), track_unique_(track_unique) { } // When we're tracking unique URLs, returns true if this URL has been // previously queried. Only call when tracking unique URLs. bool HasURL(const GURL& url) { DCHECK(track_unique_); return unique_urls_.find(url) != unique_urls_.end(); } bool GetRowForURL(const GURL& url, URLRow* row) { if (!main_db_->GetRowForURL(url, row)) { if (!archived_db_ || !archived_db_->GetRowForURL(url, row)) { // This row is neither in the main nor the archived DB. return false; } } if (track_unique_) unique_urls_.insert(url); return true; } private: URLDatabase* main_db_; // Guaranteed non-NULL. URLDatabase* archived_db_; // Possibly NULL. bool track_unique_; // When track_unique_ is set, this is updated with every URL seen so far. std::set<GURL> unique_urls_; DISALLOW_COPY_AND_ASSIGN(URLQuerier); }; // HistoryBackend -------------------------------------------------------------- HistoryBackend::HistoryBackend(const FilePath& history_dir, Delegate* delegate, BookmarkService* bookmark_service) : delegate_(delegate), history_dir_(history_dir), ALLOW_THIS_IN_INITIALIZER_LIST(expirer_(this, bookmark_service)), recent_redirects_(kMaxRedirectCount), backend_destroy_message_loop_(NULL), backend_destroy_task_(NULL), segment_queried_(false), bookmark_service_(bookmark_service) { } HistoryBackend::~HistoryBackend() { DCHECK(!scheduled_commit_) << "Deleting without cleanup"; ReleaseDBTasks(); // First close the databases before optionally running the "destroy" task. if (db_.get()) { // Commit the long-running transaction. db_->CommitTransaction(); db_.reset(); } if (thumbnail_db_.get()) { thumbnail_db_->CommitTransaction(); thumbnail_db_.reset(); } if (archived_db_.get()) { archived_db_->CommitTransaction(); archived_db_.reset(); } if (text_database_.get()) { text_database_->CommitTransaction(); text_database_.reset(); } if (backend_destroy_task_) { // Notify an interested party (typically a unit test) that we're done. DCHECK(backend_destroy_message_loop_); backend_destroy_message_loop_->PostTask(FROM_HERE, backend_destroy_task_); } } void HistoryBackend::Init(bool force_fail) { if (!force_fail) InitImpl(); delegate_->DBLoaded(); } void HistoryBackend::SetOnBackendDestroyTask(MessageLoop* message_loop, Task* task) { if (backend_destroy_task_) { DLOG(WARNING) << "Setting more than one destroy task, overriding"; delete backend_destroy_task_; } backend_destroy_message_loop_ = message_loop; backend_destroy_task_ = task; } void HistoryBackend::Closing() { // Any scheduled commit will have a reference to us, we must make it // release that reference before we can be destroyed. CancelScheduledCommit(); // Release our reference to the delegate, this reference will be keeping the // history service alive. delegate_.reset(); } void HistoryBackend::NotifyRenderProcessHostDestruction(const void* host) { tracker_.NotifyRenderProcessHostDestruction(host); } FilePath HistoryBackend::GetThumbnailFileName() const { return history_dir_.Append(chrome::kThumbnailsFilename); } FilePath HistoryBackend::GetArchivedFileName() const { return history_dir_.Append(chrome::kArchivedHistoryFilename); } SegmentID HistoryBackend::GetLastSegmentID(VisitID from_visit) { // Set is used to detect referrer loops. Should not happen, but can // if the database is corrupt. std::set<VisitID> visit_set; VisitID visit_id = from_visit; while (visit_id) { VisitRow row; if (!db_->GetRowForVisit(visit_id, &row)) return 0; if (row.segment_id) return row.segment_id; // Found a visit in this change with a segment. // Check the referrer of this visit, if any. visit_id = row.referring_visit; if (visit_set.find(visit_id) != visit_set.end()) { NOTREACHED() << "Loop in referer chain, giving up"; break; } visit_set.insert(visit_id); } return 0; } SegmentID HistoryBackend::UpdateSegments(const GURL& url, VisitID from_visit, VisitID visit_id, PageTransition::Type transition_type, const Time ts) { if (!db_.get()) return 0; // We only consider main frames. if (!PageTransition::IsMainFrame(transition_type)) return 0; SegmentID segment_id = 0; PageTransition::Type t = PageTransition::StripQualifier(transition_type); // Are we at the beginning of a new segment? if (t == PageTransition::TYPED || t == PageTransition::AUTO_BOOKMARK) { // If so, create or get the segment. std::string segment_name = db_->ComputeSegmentName(url); URLID url_id = db_->GetRowForURL(url, NULL); if (!url_id) return 0; if (!(segment_id = db_->GetSegmentNamed(segment_name))) { if (!(segment_id = db_->CreateSegment(url_id, segment_name))) { NOTREACHED(); return 0; } } else { // Note: if we update an existing segment, we update the url used to // represent that segment in order to minimize stale most visited // images. db_->UpdateSegmentRepresentationURL(segment_id, url_id); } } else { // Note: it is possible there is no segment ID set for this visit chain. // This can happen if the initial navigation wasn't AUTO_BOOKMARK or // TYPED. (For example GENERATED). In this case this visit doesn't count // toward any segment. if (!(segment_id = GetLastSegmentID(from_visit))) return 0; } // Set the segment in the visit. if (!db_->SetSegmentID(visit_id, segment_id)) { NOTREACHED(); return 0; } // Finally, increase the counter for that segment / day. if (!db_->IncreaseSegmentVisitCount(segment_id, ts, 1)) { NOTREACHED(); return 0; } return segment_id; } void HistoryBackend::AddPage(scoped_refptr<HistoryAddPageArgs> request) { DLOG(INFO) << "Adding page " << request->url.possibly_invalid_spec(); if (!db_.get()) return; // Will be filled with the URL ID and the visit ID of the last addition. std::pair<URLID, VisitID> last_ids(0, tracker_.GetLastVisit( request->id_scope, request->page_id, request->referrer)); VisitID from_visit_id = last_ids.second; // If a redirect chain is given, we expect the last item in that chain to be // the final URL. DCHECK(request->redirects.size() == 0 || request->redirects.back() == request->url); // Avoid duplicating times in the database, at least as long as pages are // added in order. However, we don't want to disallow pages from recording // times earlier than our last_recorded_time_, because someone might set // their machine's clock back. if (last_requested_time_ == request->time) { last_recorded_time_ = last_recorded_time_ + TimeDelta::FromMicroseconds(1); } else { last_requested_time_ = request->time; last_recorded_time_ = last_requested_time_; } // If the user is adding older history, we need to make sure our times // are correct. if (request->time < first_recorded_time_) first_recorded_time_ = request->time; PageTransition::Type transition = PageTransition::StripQualifier(request->transition); bool is_keyword_generated = (transition == PageTransition::KEYWORD_GENERATED); if (request->redirects.size() <= 1) { // The single entry is both a chain start and end. PageTransition::Type t = request->transition | PageTransition::CHAIN_START | PageTransition::CHAIN_END; // No redirect case (one element means just the page itself). last_ids = AddPageVisit(request->url, last_recorded_time_, last_ids.second, t); // Update the segment for this visit. KEYWORD_GENERATED visits should not // result in changing most visited, so we don't update segments (most // visited db). if (!is_keyword_generated) { UpdateSegments(request->url, from_visit_id, last_ids.second, t, last_recorded_time_); } } else { // Redirect case. Add the redirect chain. PageTransition::Type redirect_info = PageTransition::CHAIN_START; if (request->redirects[0].SchemeIs(chrome::kAboutScheme)) { // When the redirect source + referrer is "about" we skip it. This // happens when a page opens a new frame/window to about:blank and then // script sets the URL to somewhere else (used to hide the referrer). It // would be nice to keep all these redirects properly but we don't ever // see the initial about:blank load, so we don't know where the // subsequent client redirect came from. // // In this case, we just don't bother hooking up the source of the // redirects, so we remove it. request->redirects.erase(request->redirects.begin()); } else if (request->transition & PageTransition::CLIENT_REDIRECT) { redirect_info = PageTransition::CLIENT_REDIRECT; // The first entry in the redirect chain initiated a client redirect. // We don't add this to the database since the referrer is already // there, so we skip over it but change the transition type of the first // transition to client redirect. // // The referrer is invalid when restoring a session that features an // https tab that redirects to a different host or to http. In this // case we don't need to reconnect the new redirect with the existing // chain. if (request->referrer.is_valid()) { DCHECK(request->referrer == request->redirects[0]); request->redirects.erase(request->redirects.begin()); // If the navigation entry for this visit has replaced that for the // first visit, remove the CHAIN_END marker from the first visit. This // can be called a lot, for example, the page cycler, and most of the // time we won't have changed anything. VisitRow visit_row; if (request->did_replace_entry && db_->GetRowForVisit(last_ids.second, &visit_row) && visit_row.transition | PageTransition::CHAIN_END) { visit_row.transition &= ~PageTransition::CHAIN_END; db_->UpdateVisitRow(visit_row); } } } for (size_t redirect_index = 0; redirect_index < request->redirects.size(); redirect_index++) { PageTransition::Type t = transition | redirect_info; // If this is the last transition, add a CHAIN_END marker if (redirect_index == (request->redirects.size() - 1)) t = t | PageTransition::CHAIN_END; // Record all redirect visits with the same timestamp. We don't display // them anyway, and if we ever decide to, we can reconstruct their order // from the redirect chain. last_ids = AddPageVisit(request->redirects[redirect_index], last_recorded_time_, last_ids.second, t); if (t & PageTransition::CHAIN_START) { // Update the segment for this visit. UpdateSegments(request->redirects[redirect_index], from_visit_id, last_ids.second, t, last_recorded_time_); } // Subsequent transitions in the redirect list must all be sever // redirects. redirect_info = PageTransition::SERVER_REDIRECT; } // Last, save this redirect chain for later so we can set titles & favicons // on the redirected pages properly. It is indexed by the destination page. recent_redirects_.Put(request->url, request->redirects); } // TODO(brettw) bug 1140015: Add an "add page" notification so the history // views can keep in sync. // Add the last visit to the tracker so we can get outgoing transitions. // TODO(evanm): Due to http://b/1194536 we lose the referrers of a subframe // navigation anyway, so last_visit_id is always zero for them. But adding // them here confuses main frame history, so we skip them for now. if (transition != PageTransition::AUTO_SUBFRAME && transition != PageTransition::MANUAL_SUBFRAME && !is_keyword_generated) { tracker_.AddVisit(request->id_scope, request->page_id, request->url, last_ids.second); } if (text_database_.get()) { text_database_->AddPageURL(request->url, last_ids.first, last_ids.second, last_recorded_time_); } ScheduleCommit(); } void HistoryBackend::InitImpl() { DCHECK(!db_.get()) << "Initializing HistoryBackend twice"; // In the rare case where the db fails to initialize a dialog may get shown // the blocks the caller, yet allows other messages through. For this reason // we only set db_ to the created database if creation is successful. That // way other methods won't do anything as db_ is still NULL. TimeTicks beginning_time = TimeTicks::Now(); // Compute the file names. Note that the index file can be removed when the // text db manager is finished being hooked up. FilePath history_name = history_dir_.Append(chrome::kHistoryFilename); FilePath thumbnail_name = GetThumbnailFileName(); FilePath archived_name = GetArchivedFileName(); FilePath tmp_bookmarks_file = history_dir_.Append( chrome::kHistoryBookmarksFileName); // History database. db_.reset(new HistoryDatabase()); switch (db_->Init(history_name, tmp_bookmarks_file)) { case sql::INIT_OK: break; case sql::INIT_FAILURE: // A NULL db_ will cause all calls on this object to notice this error // and to not continue. delegate_->NotifyProfileError(IDS_COULDNT_OPEN_PROFILE_ERROR); db_.reset(); return; case sql::INIT_TOO_NEW: delegate_->NotifyProfileError(IDS_PROFILE_TOO_NEW_ERROR); db_.reset(); return; default: NOTREACHED(); } // Fill the in-memory database and send it back to the history service on the // main thread. InMemoryHistoryBackend* mem_backend = new InMemoryHistoryBackend; if (mem_backend->Init(history_name)) delegate_->SetInMemoryBackend(mem_backend); // Takes ownership of pointer. else delete mem_backend; // Error case, run without the in-memory DB. db_->BeginExclusiveMode(); // Must be after the mem backend read the data. // Create the history publisher which needs to be passed on to the text and // thumbnail databases for publishing history. history_publisher_.reset(new HistoryPublisher()); if (!history_publisher_->Init()) { // The init may fail when there are no indexers wanting our history. // Hence no need to log the failure. history_publisher_.reset(); } // Full-text database. This has to be first so we can pass it to the // HistoryDatabase for migration. text_database_.reset(new TextDatabaseManager(history_dir_, db_.get(), db_.get())); if (!text_database_->Init(history_publisher_.get())) { LOG(WARNING) << "Text database initialization failed, running without it."; text_database_.reset(); } if (db_->needs_version_17_migration()) { // See needs_version_17_migration() decl for more. In this case, we want // to erase all the text database files. This must be done after the text // database manager has been initialized, since it knows about all the // files it manages. text_database_->DeleteAll(); } // Thumbnail database. thumbnail_db_.reset(new ThumbnailDatabase()); if (thumbnail_db_->Init(thumbnail_name, history_publisher_.get()) != sql::INIT_OK) { // Unlike the main database, we don't error out when the database is too // new because this error is much less severe. Generally, this shouldn't // happen since the thumbnail and main datbase versions should be in sync. // We'll just continue without thumbnails & favicons in this case or any // other error. LOG(WARNING) << "Could not initialize the thumbnail database."; thumbnail_db_.reset(); } // Archived database. if (db_->needs_version_17_migration()) { // See needs_version_17_migration() decl for more. In this case, we want // to delete the archived database and need to do so before we try to // open the file. We can ignore any error (maybe the file doesn't exist). file_util::Delete(archived_name, false); } archived_db_.reset(new ArchivedDatabase()); if (!archived_db_->Init(archived_name)) { LOG(WARNING) << "Could not initialize the archived database."; archived_db_.reset(); } // Tell the expiration module about all the nice databases we made. This must // happen before db_->Init() is called since the callback ForceArchiveHistory // may need to expire stuff. // // *sigh*, this can all be cleaned up when that migration code is removed. // The main DB initialization should intuitively be first (not that it // actually matters) and the expirer should be set last. expirer_.SetDatabases(db_.get(), archived_db_.get(), thumbnail_db_.get(), text_database_.get()); // Open the long-running transaction. db_->BeginTransaction(); if (thumbnail_db_.get()) thumbnail_db_->BeginTransaction(); if (archived_db_.get()) archived_db_->BeginTransaction(); if (text_database_.get()) text_database_->BeginTransaction(); // Get the first item in our database. db_->GetStartDate(&first_recorded_time_); // Start expiring old stuff. expirer_.StartArchivingOldStuff(TimeDelta::FromDays(kArchiveDaysThreshold)); HISTOGRAM_TIMES("History.InitTime", TimeTicks::Now() - beginning_time); } std::pair<URLID, VisitID> HistoryBackend::AddPageVisit( const GURL& url, Time time, VisitID referring_visit, PageTransition::Type transition) { // Top-level frame navigations are visible, everything else is hidden bool new_hidden = !PageTransition::IsMainFrame(transition); // NOTE: This code must stay in sync with // ExpireHistoryBackend::ExpireURLsForVisits(). // TODO(pkasting): http://b/1148304 We shouldn't be marking so many URLs as // typed, which would eliminate the need for this code. int typed_increment = 0; PageTransition::Type transition_type = PageTransition::StripQualifier(transition); if ((transition_type == PageTransition::TYPED && !PageTransition::IsRedirect(transition)) || transition_type == PageTransition::KEYWORD_GENERATED) typed_increment = 1; // See if this URL is already in the DB. URLRow url_info(url); URLID url_id = db_->GetRowForURL(url, &url_info); if (url_id) { // Update of an existing row. if (PageTransition::StripQualifier(transition) != PageTransition::RELOAD) url_info.set_visit_count(url_info.visit_count() + 1); if (typed_increment) url_info.set_typed_count(url_info.typed_count() + typed_increment); url_info.set_last_visit(time); // Only allow un-hiding of pages, never hiding. if (!new_hidden) url_info.set_hidden(false); db_->UpdateURLRow(url_id, url_info); } else { // Addition of a new row. url_info.set_visit_count(1); url_info.set_typed_count(typed_increment); url_info.set_last_visit(time); url_info.set_hidden(new_hidden); url_id = db_->AddURL(url_info); if (!url_id) { NOTREACHED() << "Adding URL failed."; return std::make_pair(0, 0); } url_info.id_ = url_id; // We don't actually add the URL to the full text index at this point. It // might be nice to do this so that even if we get no title or body, the // user can search for URL components and get the page. // // However, in most cases, we'll get at least a title and usually contents, // and this add will be redundant, slowing everything down. As a result, // we ignore this edge case. } // Add the visit with the time to the database. VisitRow visit_info(url_id, time, referring_visit, transition, 0); VisitID visit_id = db_->AddVisit(&visit_info); if (visit_info.visit_time < first_recorded_time_) first_recorded_time_ = visit_info.visit_time; // Broadcast a notification of the visit. if (visit_id) { URLVisitedDetails* details = new URLVisitedDetails; details->transition = transition; details->row = url_info; // TODO(meelapshah) Disabled due to potential PageCycler regression. // Re-enable this. // GetMostRecentRedirectsTo(url, &details->redirects); BroadcastNotifications(NotificationType::HISTORY_URL_VISITED, details); } return std::make_pair(url_id, visit_id); } // Note: this method is only for testing purposes. void HistoryBackend::AddPagesWithDetails(const std::vector<URLRow>& urls) { if (!db_.get()) return; scoped_ptr<URLsModifiedDetails> modified(new URLsModifiedDetails); for (std::vector<URLRow>::const_iterator i = urls.begin(); i != urls.end(); ++i) { DCHECK(!i->last_visit().is_null()); // We will add to either the archived database or the main one depending on // the date of the added visit. URLDatabase* url_database; VisitDatabase* visit_database; if (i->last_visit() < expirer_.GetCurrentArchiveTime()) { if (!archived_db_.get()) return; // No archived database to save it to, just forget this. url_database = archived_db_.get(); visit_database = archived_db_.get(); } else { url_database = db_.get(); visit_database = db_.get(); } URLRow existing_url; URLID url_id = url_database->GetRowForURL(i->url(), &existing_url); if (!url_id) { // Add the page if it doesn't exist. url_id = url_database->AddURL(*i); if (!url_id) { NOTREACHED() << "Could not add row to DB"; return; } if (i->typed_count() > 0) modified->changed_urls.push_back(*i); } // Add the page to the full text index. This function is also used for // importing. Even though we don't have page contents, we can at least // add the title and URL to the index so they can be searched. We don't // bother to delete any already-existing FTS entries for the URL, since // this is normally called on import. // // If you ever import *after* first run (selecting import from the menu), // then these additional entries will "shadow" the originals when querying // for the most recent match only, and the user won't get snippets. This is // a very minor issue, and fixing it will make import slower, so we don't // bother. bool has_indexed = false; if (text_database_.get()) { // We do not have to make it update the visit database, below, we will // create the visit entry with the indexed flag set. has_indexed = text_database_->AddPageData(i->url(), url_id, 0, i->last_visit(), i->title(), std::wstring()); } // Make up a visit to correspond to that page. VisitRow visit_info(url_id, i->last_visit(), 0, PageTransition::LINK | PageTransition::CHAIN_START | PageTransition::CHAIN_END, 0); visit_info.is_indexed = has_indexed; if (!visit_database->AddVisit(&visit_info)) { NOTREACHED() << "Adding visit failed."; return; } if (visit_info.visit_time < first_recorded_time_) first_recorded_time_ = visit_info.visit_time; } // Broadcast a notification for typed URLs that have been modified. This // will be picked up by the in-memory URL database on the main thread. // // TODO(brettw) bug 1140015: Add an "add page" notification so the history // views can keep in sync. BroadcastNotifications(NotificationType::HISTORY_TYPED_URLS_MODIFIED, modified.release()); ScheduleCommit(); } void HistoryBackend::SetPageTitle(const GURL& url, const std::wstring& title) { if (!db_.get()) return; // Search for recent redirects which should get the same title. We make a // dummy list containing the exact URL visited if there are no redirects so // the processing below can be the same. history::RedirectList dummy_list; history::RedirectList* redirects; RedirectCache::iterator iter = recent_redirects_.Get(url); if (iter != recent_redirects_.end()) { redirects = &iter->second; // This redirect chain should have the destination URL as the last item. DCHECK(!redirects->empty()); DCHECK(redirects->back() == url); } else { // No redirect chain stored, make up one containing the URL we want so we // can use the same logic below. dummy_list.push_back(url); redirects = &dummy_list; } bool typed_url_changed = false; std::vector<URLRow> changed_urls; for (size_t i = 0; i < redirects->size(); i++) { URLRow row; URLID row_id = db_->GetRowForURL(redirects->at(i), &row); if (row_id && row.title() != title) { row.set_title(title); db_->UpdateURLRow(row_id, row); changed_urls.push_back(row); if (row.typed_count() > 0) typed_url_changed = true; } } // Broadcast notifications for typed URLs that have changed. This will // update the in-memory database. // // TODO(brettw) bug 1140020: Broadcast for all changes (not just typed), // in which case some logic can be removed. if (typed_url_changed) { URLsModifiedDetails* modified = new URLsModifiedDetails; for (size_t i = 0; i < changed_urls.size(); i++) { if (changed_urls[i].typed_count() > 0) modified->changed_urls.push_back(changed_urls[i]); } BroadcastNotifications(NotificationType::HISTORY_TYPED_URLS_MODIFIED, modified); } // Update the full text index. if (text_database_.get()) text_database_->AddPageTitle(url, title); // Only bother committing if things changed. if (!changed_urls.empty()) ScheduleCommit(); } void HistoryBackend::IterateURLs(HistoryService::URLEnumerator* iterator) { if (db_.get()) { HistoryDatabase::URLEnumerator e; if (db_->InitURLEnumeratorForEverything(&e)) { URLRow info; while (e.GetNextURL(&info)) { iterator->OnURL(info.url()); } iterator->OnComplete(true); // Success. return; } } iterator->OnComplete(false); // Failure. } void HistoryBackend::QueryURL(scoped_refptr<QueryURLRequest> request, const GURL& url, bool want_visits) { if (request->canceled()) return; bool success = false; URLRow* row = &request->value.a; VisitVector* visits = &request->value.b; if (db_.get()) { if (db_->GetRowForURL(url, row)) { // Have a row. success = true; // Optionally query the visits. if (want_visits) db_->GetVisitsForURL(row->id(), visits); } } request->ForwardResult(QueryURLRequest::TupleType(request->handle(), success, row, visits)); } // Segment usage --------------------------------------------------------------- void HistoryBackend::DeleteOldSegmentData() { if (db_.get()) db_->DeleteSegmentData(Time::Now() - TimeDelta::FromDays(kSegmentDataRetention)); } void HistoryBackend::SetSegmentPresentationIndex(SegmentID segment_id, int index) { if (db_.get()) db_->SetSegmentPresentationIndex(segment_id, index); } void HistoryBackend::QuerySegmentUsage( scoped_refptr<QuerySegmentUsageRequest> request, const Time from_time, int max_result_count) { if (request->canceled()) return; if (db_.get()) { db_->QuerySegmentUsage(from_time, max_result_count, &request->value.get()); // If this is the first time we query segments, invoke // DeleteOldSegmentData asynchronously. We do this to cleanup old // entries. if (!segment_queried_) { segment_queried_ = true; MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &HistoryBackend::DeleteOldSegmentData)); } } request->ForwardResult( QuerySegmentUsageRequest::TupleType(request->handle(), &request->value.get())); } // Keyword visits -------------------------------------------------------------- void HistoryBackend::SetKeywordSearchTermsForURL(const GURL& url, TemplateURL::IDType keyword_id, const std::wstring& term) { if (!db_.get()) return; // Get the ID for this URL. URLRow url_row; if (!db_->GetRowForURL(url, &url_row)) { // There is a small possibility the url was deleted before the keyword // was added. Ignore the request. return; } db_->SetKeywordSearchTermsForURL(url_row.id(), keyword_id, term); ScheduleCommit(); } void HistoryBackend::DeleteAllSearchTermsForKeyword( TemplateURL::IDType keyword_id) { if (!db_.get()) return; db_->DeleteAllSearchTermsForKeyword(keyword_id); // TODO(sky): bug 1168470. Need to move from archive dbs too. ScheduleCommit(); } void HistoryBackend::GetMostRecentKeywordSearchTerms( scoped_refptr<GetMostRecentKeywordSearchTermsRequest> request, TemplateURL::IDType keyword_id, const std::wstring& prefix, int max_count) { if (request->canceled()) return; if (db_.get()) { db_->GetMostRecentKeywordSearchTerms(keyword_id, prefix, max_count, &(request->value)); } request->ForwardResult( GetMostRecentKeywordSearchTermsRequest::TupleType(request->handle(), &request->value)); } // Downloads ------------------------------------------------------------------- // Get all the download entries from the database. void HistoryBackend::QueryDownloads( scoped_refptr<DownloadQueryRequest> request) { if (request->canceled()) return; if (db_.get()) db_->QueryDownloads(&request->value); request->ForwardResult(DownloadQueryRequest::TupleType(&request->value)); } // Update a particular download entry. void HistoryBackend::UpdateDownload(int64 received_bytes, int32 state, int64 db_handle) { if (db_.get()) db_->UpdateDownload(received_bytes, state, db_handle); } // Update the path of a particular download entry. void HistoryBackend::UpdateDownloadPath(const std::wstring& path, int64 db_handle) { if (db_.get()) db_->UpdateDownloadPath(path, db_handle); } // Create a new download entry and pass back the db_handle to it. void HistoryBackend::CreateDownload( scoped_refptr<DownloadCreateRequest> request, const DownloadCreateInfo& create_info) { int64 db_handle = 0; if (!request->canceled()) { if (db_.get()) db_handle = db_->CreateDownload(create_info); request->ForwardResult(DownloadCreateRequest::TupleType(create_info, db_handle)); } } void HistoryBackend::RemoveDownload(int64 db_handle) { if (db_.get()) db_->RemoveDownload(db_handle); } void HistoryBackend::RemoveDownloadsBetween(const Time remove_begin, const Time remove_end) { if (db_.get()) db_->RemoveDownloadsBetween(remove_begin, remove_end); } void HistoryBackend::SearchDownloads( scoped_refptr<DownloadSearchRequest> request, const std::wstring& search_text) { if (request->canceled()) return; if (db_.get()) db_->SearchDownloads(&request->value, search_text); request->ForwardResult(DownloadSearchRequest::TupleType(request->handle(), &request->value)); } void HistoryBackend::QueryHistory(scoped_refptr<QueryHistoryRequest> request, const std::wstring& text_query, const QueryOptions& options) { if (request->canceled()) return; TimeTicks beginning_time = TimeTicks::Now(); if (db_.get()) { if (text_query.empty()) { // Basic history query for the main database. QueryHistoryBasic(db_.get(), db_.get(), options, &request->value); // Now query the archived database. This is a bit tricky because we don't // want to query it if the queried time range isn't going to find anything // in it. // TODO(brettw) bug 1171036: do blimpie querying for the archived database // as well. // if (archived_db_.get() && // expirer_.GetCurrentArchiveTime() - TimeDelta::FromDays(7)) { } else { // Full text history query. QueryHistoryFTS(text_query, options, &request->value); } } request->ForwardResult(QueryHistoryRequest::TupleType(request->handle(), &request->value)); UMA_HISTOGRAM_TIMES("History.QueryHistory", TimeTicks::Now() - beginning_time); } // Basic time-based querying of history. void HistoryBackend::QueryHistoryBasic(URLDatabase* url_db, VisitDatabase* visit_db, const QueryOptions& options, QueryResults* result) { // First get all visits. VisitVector visits; visit_db->GetVisibleVisitsInRange(options.begin_time, options.end_time, options.max_count, &visits); DCHECK(options.max_count == 0 || static_cast<int>(visits.size()) <= options.max_count); // Now add them and the URL rows to the results. URLResult url_result; for (size_t i = 0; i < visits.size(); i++) { const VisitRow visit = visits[i]; // Add a result row for this visit, get the URL info from the DB. if (!url_db->GetURLRow(visit.url_id, &url_result)) continue; // DB out of sync and URL doesn't exist, try to recover. if (!url_result.url().is_valid()) continue; // Don't report invalid URLs in case of corruption. // The archived database may be out of sync with respect to starring, // titles, last visit date, etc. Therefore, we query the main DB if the // current URL database is not the main one. if (url_db == db_.get()) { // Currently querying the archived DB, update with the main database to // catch any interesting stuff. This will update it if it exists in the // main DB, and do nothing otherwise. db_->GetRowForURL(url_result.url(), &url_result); } url_result.set_visit_time(visit.visit_time); // We don't set any of the query-specific parts of the URLResult, since // snippets and stuff don't apply to basic querying. result->AppendURLBySwapping(&url_result); } if (options.begin_time <= first_recorded_time_) result->set_reached_beginning(true); } void HistoryBackend::QueryHistoryFTS(const std::wstring& text_query, const QueryOptions& options, QueryResults* result) { if (!text_database_.get()) return; // Full text query, first get all the FTS results in the time range. std::vector<TextDatabase::Match> fts_matches; Time first_time_searched; text_database_->GetTextMatches(text_query, options, &fts_matches, &first_time_searched); URLQuerier querier(db_.get(), archived_db_.get(), true); // Now get the row and visit information for each one. URLResult url_result; // Declare outside loop to prevent re-construction. for (size_t i = 0; i < fts_matches.size(); i++) { if (options.max_count != 0 && static_cast<int>(result->size()) >= options.max_count) break; // Got too many items. // Get the URL, querying the main and archived databases as necessary. If // this is not found, the history and full text search databases are out // of sync and we give up with this result. if (!querier.GetRowForURL(fts_matches[i].url, &url_result)) continue; if (!url_result.url().is_valid()) continue; // Don't report invalid URLs in case of corruption. // Copy over the FTS stuff that the URLDatabase doesn't know about. // We do this with swap() to avoid copying, since we know we don't // need the original any more. Note that we override the title with the // one from FTS, since that will match the title_match_positions (the // FTS title and the history DB title may differ). url_result.set_title(fts_matches[i].title); url_result.title_match_positions_.swap( fts_matches[i].title_match_positions); url_result.snippet_.Swap(&fts_matches[i].snippet); // The visit time also comes from the full text search database. Since it // has the time, we can avoid an extra query of the visits table. url_result.set_visit_time(fts_matches[i].time); // Add it to the vector, this will clear our |url_row| object as a // result of the swap. result->AppendURLBySwapping(&url_result); } if (options.begin_time <= first_recorded_time_) result->set_reached_beginning(true); } // Frontend to GetMostRecentRedirectsFrom from the history thread. void HistoryBackend::QueryRedirectsFrom( scoped_refptr<QueryRedirectsRequest> request, const GURL& url) { if (request->canceled()) return; bool success = GetMostRecentRedirectsFrom(url, &request->value); request->ForwardResult(QueryRedirectsRequest::TupleType( request->handle(), url, success, &request->value)); } void HistoryBackend::QueryRedirectsTo( scoped_refptr<QueryRedirectsRequest> request, const GURL& url) { if (request->canceled()) return; bool success = GetMostRecentRedirectsTo(url, &request->value); request->ForwardResult(QueryRedirectsRequest::TupleType( request->handle(), url, success, &request->value)); } void HistoryBackend::GetVisitCountToHost( scoped_refptr<GetVisitCountToHostRequest> request, const GURL& url) { if (request->canceled()) return; int count = 0; Time first_visit; const bool success = (db_.get() && db_->GetVisitCountToHost(url, &count, &first_visit)); request->ForwardResult(GetVisitCountToHostRequest::TupleType( request->handle(), success, count, first_visit)); } void HistoryBackend::QueryTopURLsAndRedirects( scoped_refptr<QueryTopURLsAndRedirectsRequest> request, int result_count) { if (request->canceled()) return; if (!db_.get()) { request->ForwardResult(QueryTopURLsAndRedirectsRequest::TupleType( request->handle(), false, NULL, NULL)); return; } std::vector<GURL>* top_urls = &request->value.a; history::RedirectMap* redirects = &request->value.b; ScopedVector<PageUsageData> data; db_->QuerySegmentUsage(base::Time::Now() - base::TimeDelta::FromDays(90), result_count, &data.get()); for (size_t i = 0; i < data.size(); ++i) { top_urls->push_back(data[i]->GetURL()); RefCountedVector<GURL>* list = new RefCountedVector<GURL>; GetMostRecentRedirectsFrom(top_urls->back(), &list->data); (*redirects)[top_urls->back()] = list; } request->ForwardResult(QueryTopURLsAndRedirectsRequest::TupleType( request->handle(), true, top_urls, redirects)); } void HistoryBackend::GetRedirectsFromSpecificVisit( VisitID cur_visit, history::RedirectList* redirects) { // Follow any redirects from the given visit and add them to the list. // It *should* be impossible to get a circular chain here, but we check // just in case to avoid infinite loops. GURL cur_url; std::set<VisitID> visit_set; visit_set.insert(cur_visit); while (db_->GetRedirectFromVisit(cur_visit, &cur_visit, &cur_url)) { if (visit_set.find(cur_visit) != visit_set.end()) { NOTREACHED() << "Loop in visit chain, giving up"; return; } visit_set.insert(cur_visit); redirects->push_back(cur_url); } } void HistoryBackend::GetRedirectsToSpecificVisit( VisitID cur_visit, history::RedirectList* redirects) { // Follow redirects going to cur_visit. These are added to |redirects| in // the order they are found. If a redirect chain looks like A -> B -> C and // |cur_visit| = C, redirects will be {B, A} in that order. if (!db_.get()) return; GURL cur_url; std::set<VisitID> visit_set; visit_set.insert(cur_visit); while (db_->GetRedirectToVisit(cur_visit, &cur_visit, &cur_url)) { if (visit_set.find(cur_visit) != visit_set.end()) { NOTREACHED() << "Loop in visit chain, giving up"; return; } visit_set.insert(cur_visit); redirects->push_back(cur_url); } } bool HistoryBackend::GetMostRecentRedirectsFrom( const GURL& from_url, history::RedirectList* redirects) { redirects->clear(); if (!db_.get()) return false; URLID from_url_id = db_->GetRowForURL(from_url, NULL); VisitID cur_visit = db_->GetMostRecentVisitForURL(from_url_id, NULL); if (!cur_visit) return false; // No visits for URL. GetRedirectsFromSpecificVisit(cur_visit, redirects); return true; } bool HistoryBackend::GetMostRecentRedirectsTo( const GURL& to_url, history::RedirectList* redirects) { redirects->clear(); if (!db_.get()) return false; URLID to_url_id = db_->GetRowForURL(to_url, NULL); VisitID cur_visit = db_->GetMostRecentVisitForURL(to_url_id, NULL); if (!cur_visit) return false; // No visits for URL. GetRedirectsToSpecificVisit(cur_visit, redirects); return true; } void HistoryBackend::ScheduleAutocomplete(HistoryURLProvider* provider, HistoryURLProviderParams* params) { // ExecuteWithDB should handle the NULL database case. provider->ExecuteWithDB(this, db_.get(), params); } void HistoryBackend::SetPageContents(const GURL& url, const std::wstring& contents) { // This is histogrammed in the text database manager. if (!text_database_.get()) return; text_database_->AddPageContents(url, contents); } void HistoryBackend::SetPageThumbnail( const GURL& url, const SkBitmap& thumbnail, const ThumbnailScore& score) { if (!db_.get() || !thumbnail_db_.get()) return; URLRow url_row; URLID url_id = db_->GetRowForURL(url, &url_row); if (url_id) { thumbnail_db_->SetPageThumbnail(url, url_id, thumbnail, score, url_row.last_visit()); } ScheduleCommit(); } void HistoryBackend::GetPageThumbnail( scoped_refptr<GetPageThumbnailRequest> request, const GURL& page_url) { if (request->canceled()) return; scoped_refptr<RefCountedBytes> data; GetPageThumbnailDirectly(page_url, &data); request->ForwardResult(GetPageThumbnailRequest::TupleType( request->handle(), data)); } void HistoryBackend::GetPageThumbnailDirectly( const GURL& page_url, scoped_refptr<RefCountedBytes>* data) { if (thumbnail_db_.get()) { *data = new RefCountedBytes; // Time the result. TimeTicks beginning_time = TimeTicks::Now(); history::RedirectList redirects; URLID url_id; bool success = false; // If there are some redirects, try to get a thumbnail from the last // redirect destination. if (GetMostRecentRedirectsFrom(page_url, &redirects) && !redirects.empty()) { if ((url_id = db_->GetRowForURL(redirects.back(), NULL))) success = thumbnail_db_->GetPageThumbnail(url_id, &(*data)->data); } // If we don't have a thumbnail from redirects, try the URL directly. if (!success) { if ((url_id = db_->GetRowForURL(page_url, NULL))) success = thumbnail_db_->GetPageThumbnail(url_id, &(*data)->data); } // In this rare case, we start to mine the older redirect sessions // from the visit table to try to find a thumbnail. if (!success) { success = GetThumbnailFromOlderRedirect(page_url, &(*data)->data); } if (!success) *data = NULL; // This will tell the callback there was an error. UMA_HISTOGRAM_TIMES("History.GetPageThumbnail", TimeTicks::Now() - beginning_time); } } bool HistoryBackend::GetThumbnailFromOlderRedirect( const GURL& page_url, std::vector<unsigned char>* data) { // Look at a few previous visit sessions. VisitVector older_sessions; URLID page_url_id = db_->GetRowForURL(page_url, NULL); static const int kVisitsToSearchForThumbnail = 4; db_->GetMostRecentVisitsForURL( page_url_id, kVisitsToSearchForThumbnail, &older_sessions); // Iterate across all those previous visits, and see if any of the // final destinations of those redirect chains have a good thumbnail // for us. bool success = false; for (VisitVector::const_iterator it = older_sessions.begin(); !success && it != older_sessions.end(); ++it) { history::RedirectList redirects; if (it->visit_id) { GetRedirectsFromSpecificVisit(it->visit_id, &redirects); if (!redirects.empty()) { URLID url_id; if ((url_id = db_->GetRowForURL(redirects.back(), NULL))) success = thumbnail_db_->GetPageThumbnail(url_id, data); } } } return success; } void HistoryBackend::GetFavIcon(scoped_refptr<GetFavIconRequest> request, const GURL& icon_url) { UpdateFavIconMappingAndFetchImpl(NULL, icon_url, request); } void HistoryBackend::UpdateFavIconMappingAndFetch( scoped_refptr<GetFavIconRequest> request, const GURL& page_url, const GURL& icon_url) { UpdateFavIconMappingAndFetchImpl(&page_url, icon_url, request); } void HistoryBackend::SetFavIconOutOfDateForPage(const GURL& page_url) { if (!thumbnail_db_.get() || !db_.get()) return; URLRow url_row; URLID url_id = db_->GetRowForURL(page_url, &url_row); if (!url_id || !url_row.favicon_id()) return; thumbnail_db_->SetFavIconLastUpdateTime(url_row.favicon_id(), Time()); ScheduleCommit(); } void HistoryBackend::SetImportedFavicons( const std::vector<ImportedFavIconUsage>& favicon_usage) { if (!db_.get() || !thumbnail_db_.get()) return; Time now = Time::Now(); // Track all URLs that had their favicons set or updated. std::set<GURL> favicons_changed; for (size_t i = 0; i < favicon_usage.size(); i++) { FavIconID favicon_id = thumbnail_db_->GetFavIconIDForFavIconURL( favicon_usage[i].favicon_url); if (!favicon_id) { // This favicon doesn't exist yet, so we create it using the given data. favicon_id = thumbnail_db_->AddFavIcon(favicon_usage[i].favicon_url); if (!favicon_id) continue; // Unable to add the favicon. thumbnail_db_->SetFavIcon(favicon_id, favicon_usage[i].png_data, now); } // Save the mapping from all the URLs to the favicon. BookmarkService* bookmark_service = GetBookmarkService(); for (std::set<GURL>::const_iterator url = favicon_usage[i].urls.begin(); url != favicon_usage[i].urls.end(); ++url) { URLRow url_row; if (!db_->GetRowForURL(*url, &url_row)) { // If the URL is present as a bookmark, add the url in history to // save the favicon mapping. This will match with what history db does // for regular bookmarked URLs with favicons - when history db is // cleaned, we keep an entry in the db with 0 visits as long as that // url is bookmarked. if (bookmark_service && bookmark_service_->IsBookmarked(*url)) { URLRow url_info(*url); url_info.set_visit_count(0); url_info.set_typed_count(0); url_info.set_last_visit(base::Time()); url_info.set_hidden(false); url_info.set_favicon_id(favicon_id); db_->AddURL(url_info); favicons_changed.insert(*url); } } else if (url_row.favicon_id() == 0) { // URL is present in history, update the favicon *only* if it // is not set already. url_row.set_favicon_id(favicon_id); db_->UpdateURLRow(url_row.id(), url_row); favicons_changed.insert(*url); } } } if (!favicons_changed.empty()) { // Send the notification about the changed favicon URLs. FavIconChangeDetails* changed_details = new FavIconChangeDetails; changed_details->urls.swap(favicons_changed); BroadcastNotifications(NotificationType::FAVICON_CHANGED, changed_details); } } void HistoryBackend::UpdateFavIconMappingAndFetchImpl( const GURL* page_url, const GURL& icon_url, scoped_refptr<GetFavIconRequest> request) { if (request->canceled()) return; bool know_favicon = false; bool expired = true; scoped_refptr<RefCountedBytes> data; if (thumbnail_db_.get()) { const FavIconID favicon_id = thumbnail_db_->GetFavIconIDForFavIconURL(icon_url); if (favicon_id) { data = new RefCountedBytes; know_favicon = true; Time last_updated; if (thumbnail_db_->GetFavIcon(favicon_id, &last_updated, &data->data, NULL)) { expired = (Time::Now() - last_updated) > TimeDelta::FromDays(kFavIconRefetchDays); } if (page_url) SetFavIconMapping(*page_url, favicon_id); } // else case, haven't cached entry yet. Caller is responsible for // downloading the favicon and invoking SetFavIcon. } request->ForwardResult(GetFavIconRequest::TupleType( request->handle(), know_favicon, data, expired, icon_url)); } void HistoryBackend::GetFavIconForURL( scoped_refptr<GetFavIconRequest> request, const GURL& page_url) { if (request->canceled()) return; bool know_favicon = false; bool expired = false; GURL icon_url; scoped_refptr<RefCountedBytes> data; if (db_.get() && thumbnail_db_.get()) { // Time the query. TimeTicks beginning_time = TimeTicks::Now(); URLRow url_info; data = new RefCountedBytes; Time last_updated; if (db_->GetRowForURL(page_url, &url_info) && url_info.favicon_id() && thumbnail_db_->GetFavIcon(url_info.favicon_id(), &last_updated, &data->data, &icon_url)) { know_favicon = true; expired = (Time::Now() - last_updated) > TimeDelta::FromDays(kFavIconRefetchDays); } UMA_HISTOGRAM_TIMES("History.GetFavIconForURL", TimeTicks::Now() - beginning_time); } request->ForwardResult( GetFavIconRequest::TupleType(request->handle(), know_favicon, data, expired, icon_url)); } void HistoryBackend::SetFavIcon( const GURL& page_url, const GURL& icon_url, scoped_refptr<RefCountedBytes> data) { DCHECK(data.get()); if (!thumbnail_db_.get() || !db_.get()) return; FavIconID id = thumbnail_db_->GetFavIconIDForFavIconURL(icon_url); if (!id) id = thumbnail_db_->AddFavIcon(icon_url); // Set the image data. thumbnail_db_->SetFavIcon(id, data->data, Time::Now()); SetFavIconMapping(page_url, id); } void HistoryBackend::SetFavIconMapping(const GURL& page_url, FavIconID id) { // Find all the pages whose favicons we should set, we want to set it for // all the pages in the redirect chain if it redirected. history::RedirectList dummy_list; history::RedirectList* redirects; RedirectCache::iterator iter = recent_redirects_.Get(page_url); if (iter != recent_redirects_.end()) { redirects = &iter->second; // This redirect chain should have the destination URL as the last item. DCHECK(!redirects->empty()); DCHECK(redirects->back() == page_url); } else { // No redirect chain stored, make up one containing the URL we want to we // can use the same logic below. dummy_list.push_back(page_url); redirects = &dummy_list; } std::set<GURL> favicons_changed; // Save page <-> favicon association. for (history::RedirectList::const_iterator i(redirects->begin()); i != redirects->end(); ++i) { URLRow row; if (!db_->GetRowForURL(*i, &row) || row.favicon_id() == id) continue; FavIconID old_id = row.favicon_id(); if (old_id == id) continue; row.set_favicon_id(id); db_->UpdateURLRow(row.id(), row); if (old_id) { // The page's favicon ID changed. This means that the one we just // changed from could have been orphaned, and we need to re-check it. // This is not super fast, but this case will get triggered rarely, // since normally a page will always map to the same favicon ID. It // will mostly happen for favicons we import. if (!db_->IsFavIconUsed(old_id) && thumbnail_db_.get()) thumbnail_db_->DeleteFavIcon(old_id); } favicons_changed.insert(row.url()); } // Send the notification about the changed favicons. FavIconChangeDetails* changed_details = new FavIconChangeDetails; changed_details->urls.swap(favicons_changed); BroadcastNotifications(NotificationType::FAVICON_CHANGED, changed_details); ScheduleCommit(); } void HistoryBackend::Commit() { if (!db_.get()) return; // Note that a commit may not actually have been scheduled if a caller // explicitly calls this instead of using ScheduleCommit. Likewise, we // may reset the flag written by a pending commit. But this is OK! It // will merely cause extra commits (which is kind of the idea). We // could optimize more for this case (we may get two extra commits in // some cases) but it hasn't been important yet. CancelScheduledCommit(); db_->CommitTransaction(); DCHECK(db_->transaction_nesting() == 0) << "Somebody left a transaction open"; db_->BeginTransaction(); if (thumbnail_db_.get()) { thumbnail_db_->CommitTransaction(); DCHECK(thumbnail_db_->transaction_nesting() == 0) << "Somebody left a transaction open"; thumbnail_db_->BeginTransaction(); } if (archived_db_.get()) { archived_db_->CommitTransaction(); archived_db_->BeginTransaction(); } if (text_database_.get()) { text_database_->CommitTransaction(); text_database_->BeginTransaction(); } } void HistoryBackend::ScheduleCommit() { if (scheduled_commit_.get()) return; scheduled_commit_ = new CommitLaterTask(this); MessageLoop::current()->PostDelayedTask(FROM_HERE, NewRunnableMethod(scheduled_commit_.get(), &CommitLaterTask::RunCommit), kCommitIntervalMs); } void HistoryBackend::CancelScheduledCommit() { if (scheduled_commit_) { scheduled_commit_->Cancel(); scheduled_commit_ = NULL; } } void HistoryBackend::ProcessDBTaskImpl() { if (!db_.get()) { // db went away, release all the refs. ReleaseDBTasks(); return; } // Remove any canceled tasks. while (!db_task_requests_.empty() && db_task_requests_.front()->canceled()) { db_task_requests_.front()->Release(); db_task_requests_.pop_front(); } if (db_task_requests_.empty()) return; // Run the first task. HistoryDBTaskRequest* request = db_task_requests_.front(); db_task_requests_.pop_front(); if (request->value->RunOnDBThread(this, db_.get())) { // The task is done. Notify the callback. request->ForwardResult(HistoryDBTaskRequest::TupleType()); // We AddRef'd the request before adding, need to release it now. request->Release(); } else { // Tasks wants to run some more. Schedule it at the end of current tasks. db_task_requests_.push_back(request); // And process it after an invoke later. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( this, &HistoryBackend::ProcessDBTaskImpl)); } } void HistoryBackend::ReleaseDBTasks() { for (std::list<HistoryDBTaskRequest*>::iterator i = db_task_requests_.begin(); i != db_task_requests_.end(); ++i) { (*i)->Release(); } db_task_requests_.clear(); } //////////////////////////////////////////////////////////////////////////////// // // Generic operations // //////////////////////////////////////////////////////////////////////////////// void HistoryBackend::DeleteURL(const GURL& url) { expirer_.DeleteURL(url); db_->GetStartDate(&first_recorded_time_); // Force a commit, if the user is deleting something for privacy reasons, we // want to get it on disk ASAP. Commit(); } void HistoryBackend::ExpireHistoryBetween( scoped_refptr<ExpireHistoryRequest> request, Time begin_time, Time end_time) { if (request->canceled()) return; if (db_.get()) { if (begin_time.is_null() && end_time.is_null()) { // Special case deleting all history so it can be faster and to reduce the // possibility of an information leak. DeleteAllHistory(); } else { // Clearing parts of history, have the expirer do the depend expirer_.ExpireHistoryBetween(begin_time, end_time); // Force a commit, if the user is deleting something for privacy reasons, // we want to get it on disk ASAP. Commit(); } } if (begin_time <= first_recorded_time_) db_->GetStartDate(&first_recorded_time_); request->ForwardResult(ExpireHistoryRequest::TupleType()); if (history_publisher_.get()) history_publisher_->DeleteUserHistoryBetween(begin_time, end_time); } void HistoryBackend::URLsNoLongerBookmarked(const std::set<GURL>& urls) { if (!db_.get()) return; for (std::set<GURL>::const_iterator i = urls.begin(); i != urls.end(); ++i) { URLRow url_row; if (!db_->GetRowForURL(*i, &url_row)) continue; // The URL isn't in the db; nothing to do. VisitVector visits; db_->GetVisitsForURL(url_row.id(), &visits); if (visits.empty()) expirer_.DeleteURL(*i); // There are no more visits; nuke the URL. } } void HistoryBackend::ProcessDBTask( scoped_refptr<HistoryDBTaskRequest> request) { DCHECK(request.get()); if (request->canceled()) return; bool task_scheduled = !db_task_requests_.empty(); // Make sure we up the refcount of the request. ProcessDBTaskImpl will // release when done with the task. request->AddRef(); db_task_requests_.push_back(request.get()); if (!task_scheduled) { // No other tasks are scheduled. Process request now. ProcessDBTaskImpl(); } } void HistoryBackend::BroadcastNotifications( NotificationType type, HistoryDetails* details_deleted) { DCHECK(delegate_.get()); delegate_->BroadcastNotifications(type, details_deleted); } // Deleting -------------------------------------------------------------------- void HistoryBackend::DeleteAllHistory() { // Our approach to deleting all history is: // 1. Copy the bookmarks and their dependencies to new tables with temporary // names. // 2. Delete the original tables. Since tables can not share pages, we know // that any data we don't want to keep is now in an unused page. // 3. Renaming the temporary tables to match the original. // 4. Vacuuming the database to delete the unused pages. // // Since we are likely to have very few bookmarks and their dependencies // compared to all history, this is also much faster than just deleting from // the original tables directly. // Get the bookmarked URLs. std::vector<GURL> starred_urls; BookmarkService* bookmark_service = GetBookmarkService(); if (bookmark_service) bookmark_service_->GetBookmarks(&starred_urls); std::vector<URLRow> kept_urls; for (size_t i = 0; i < starred_urls.size(); i++) { URLRow row; if (!db_->GetRowForURL(starred_urls[i], &row)) continue; // Clear the last visit time so when we write these rows they are "clean." row.set_last_visit(Time()); row.set_visit_count(0); row.set_typed_count(0); kept_urls.push_back(row); } // Clear thumbnail and favicon history. The favicons for the given URLs will // be kept. if (!ClearAllThumbnailHistory(&kept_urls)) { LOG(ERROR) << "Thumbnail history could not be cleared"; // We continue in this error case. If the user wants to delete their // history, we should delete as much as we can. } // ClearAllMainHistory will change the IDs of the URLs in kept_urls. Therfore, // we clear the list afterwards to make sure nobody uses this invalid data. if (!ClearAllMainHistory(kept_urls)) LOG(ERROR) << "Main history could not be cleared"; kept_urls.clear(); // Delete FTS files & archived history. if (text_database_.get()) { // We assume that the text database has one transaction on them that we need // to close & restart (the long-running history transaction). text_database_->CommitTransaction(); text_database_->DeleteAll(); text_database_->BeginTransaction(); } if (archived_db_.get()) { // Close the database and delete the file. archived_db_.reset(); FilePath archived_file_name = GetArchivedFileName(); file_util::Delete(archived_file_name, false); // Now re-initialize the database (which may fail). archived_db_.reset(new ArchivedDatabase()); if (!archived_db_->Init(archived_file_name)) { LOG(WARNING) << "Could not initialize the archived database."; archived_db_.reset(); } else { // Open our long-running transaction on this database. archived_db_->BeginTransaction(); } } db_->GetStartDate(&first_recorded_time_); // Send out the notfication that history is cleared. The in-memory datdabase // will pick this up and clear itself. URLsDeletedDetails* details = new URLsDeletedDetails; details->all_history = true; BroadcastNotifications(NotificationType::HISTORY_URLS_DELETED, details); } bool HistoryBackend::ClearAllThumbnailHistory( std::vector<URLRow>* kept_urls) { if (!thumbnail_db_.get()) { // When we have no reference to the thumbnail database, maybe there was an // error opening it. In this case, we just try to blow it away to try to // fix the error if it exists. This may fail, in which case either the // file doesn't exist or there's no more we can do. file_util::Delete(GetThumbnailFileName(), false); return true; } // Create the duplicate favicon table, this is where the favicons we want // to keep will be stored. if (!thumbnail_db_->InitTemporaryFavIconsTable()) return false; // This maps existing favicon IDs to the ones in the temporary table. typedef std::map<FavIconID, FavIconID> FavIconMap; FavIconMap copied_favicons; // Copy all unique favicons to the temporary table, and update all the // URLs to have the new IDs. for (std::vector<URLRow>::iterator i = kept_urls->begin(); i != kept_urls->end(); ++i) { FavIconID old_id = i->favicon_id(); if (!old_id) continue; // URL has no favicon. FavIconID new_id; FavIconMap::const_iterator found = copied_favicons.find(old_id); if (found == copied_favicons.end()) { new_id = thumbnail_db_->CopyToTemporaryFavIconTable(old_id); copied_favicons[old_id] = new_id; } else { // We already encountered a URL that used this favicon, use the ID we // previously got. new_id = found->second; } i->set_favicon_id(new_id); } // Rename the duplicate favicon table back and recreate the other tables. // This will make the database consistent again. thumbnail_db_->CommitTemporaryFavIconTable(); thumbnail_db_->RecreateThumbnailTable(); // Vacuum to remove all the pages associated with the dropped tables. There // must be no transaction open on the table when we do this. We assume that // our long-running transaction is open, so we complete it and start it again. DCHECK(thumbnail_db_->transaction_nesting() == 1); thumbnail_db_->CommitTransaction(); thumbnail_db_->Vacuum(); thumbnail_db_->BeginTransaction(); return true; } bool HistoryBackend::ClearAllMainHistory( const std::vector<URLRow>& kept_urls) { // Create the duplicate URL table. We will copy the kept URLs into this. if (!db_->CreateTemporaryURLTable()) return false; // Insert the URLs into the temporary table, we need to keep a map of changed // IDs since the ID will be different in the new table. typedef std::map<URLID, URLID> URLIDMap; URLIDMap old_to_new; // Maps original ID to new one. for (std::vector<URLRow>::const_iterator i = kept_urls.begin(); i != kept_urls.end(); ++i) { URLID new_id = db_->AddTemporaryURL(*i); old_to_new[i->id()] = new_id; } // Replace the original URL table with the temporary one. if (!db_->CommitTemporaryURLTable()) return false; // Delete the old tables and recreate them empty. db_->RecreateAllTablesButURL(); // Vacuum to reclaim the space from the dropped tables. This must be done // when there is no transaction open, and we assume that our long-running // transaction is currently open. db_->CommitTransaction(); db_->Vacuum(); db_->BeginTransaction(); db_->GetStartDate(&first_recorded_time_); return true; } BookmarkService* HistoryBackend::GetBookmarkService() { if (bookmark_service_) bookmark_service_->BlockTillLoaded(); return bookmark_service_; } } // namespace history
35.524072
80
0.675132
[ "object", "vector" ]
4fdf9bb0a2465eb9911498e075ff7de966cd65a5
40,365
cpp
C++
src/dbus/server/dbus_thread_object.cpp
gjc13/ot-br-posix
001a7937db72354d8bb2c0de5171bd89e16affbf
[ "BSD-3-Clause" ]
null
null
null
src/dbus/server/dbus_thread_object.cpp
gjc13/ot-br-posix
001a7937db72354d8bb2c0de5171bd89e16affbf
[ "BSD-3-Clause" ]
null
null
null
src/dbus/server/dbus_thread_object.cpp
gjc13/ot-br-posix
001a7937db72354d8bb2c0de5171bd89e16affbf
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <string.h> #include <openthread/border_router.h> #include <openthread/channel_monitor.h> #include <openthread/instance.h> #include <openthread/joiner.h> #include <openthread/link_raw.h> #include <openthread/ncp.h> #include <openthread/netdata.h> #include <openthread/thread_ftd.h> #include <openthread/platform/radio.h> #include "common/byteswap.hpp" #include "dbus/common/constants.hpp" #include "dbus/server/dbus_agent.hpp" #include "dbus/server/dbus_thread_object.hpp" using std::placeholders::_1; using std::placeholders::_2; static std::string GetDeviceRoleName(otDeviceRole aRole) { std::string roleName; switch (aRole) { case OT_DEVICE_ROLE_DISABLED: roleName = OTBR_ROLE_NAME_DISABLED; break; case OT_DEVICE_ROLE_DETACHED: roleName = OTBR_ROLE_NAME_DETACHED; break; case OT_DEVICE_ROLE_CHILD: roleName = OTBR_ROLE_NAME_CHILD; break; case OT_DEVICE_ROLE_ROUTER: roleName = OTBR_ROLE_NAME_ROUTER; break; case OT_DEVICE_ROLE_LEADER: roleName = OTBR_ROLE_NAME_LEADER; break; } return roleName; } static uint64_t ConvertOpenThreadUint64(const uint8_t *aValue) { uint64_t val = 0; for (size_t i = 0; i < sizeof(uint64_t); i++) { val = (val << 8) | aValue[i]; } return val; } namespace otbr { namespace DBus { DBusThreadObject::DBusThreadObject(DBusConnection * aConnection, const std::string & aInterfaceName, otbr::Ncp::ControllerOpenThread *aNcp) : DBusObject(aConnection, OTBR_DBUS_OBJECT_PREFIX + aInterfaceName) , mNcp(aNcp) { } otbrError DBusThreadObject::Init(void) { otbrError error = DBusObject::Init(); auto threadHelper = mNcp->GetThreadHelper(); threadHelper->AddDeviceRoleHandler(std::bind(&DBusThreadObject::DeviceRoleHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_SCAN_METHOD, std::bind(&DBusThreadObject::ScanHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_ATTACH_METHOD, std::bind(&DBusThreadObject::AttachHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_FACTORY_RESET_METHOD, std::bind(&DBusThreadObject::FactoryResetHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_RESET_METHOD, std::bind(&DBusThreadObject::ResetHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_JOINER_START_METHOD, std::bind(&DBusThreadObject::JoinerStartHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_JOINER_STOP_METHOD, std::bind(&DBusThreadObject::JoinerStopHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PERMIT_UNSECURE_JOIN_METHOD, std::bind(&DBusThreadObject::PermitUnsecureJoinHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_ADD_ON_MESH_PREFIX_METHOD, std::bind(&DBusThreadObject::AddOnMeshPrefixHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_REMOVE_ON_MESH_PREFIX_METHOD, std::bind(&DBusThreadObject::RemoveOnMeshPrefixHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_ADD_EXTERNAL_ROUTE_METHOD, std::bind(&DBusThreadObject::AddExternalRouteHandler, this, _1)); RegisterMethod(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_REMOVE_EXTERNAL_ROUTE_METHOD, std::bind(&DBusThreadObject::RemoveExternalRouteHandler, this, _1)); RegisterMethod(DBUS_INTERFACE_INTROSPECTABLE, DBUS_INTROSPECT_METHOD, std::bind(&DBusThreadObject::IntrospectHandler, this, _1)); RegisterSetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_MESH_LOCAL_PREFIX, std::bind(&DBusThreadObject::SetMeshLocalPrefixHandler, this, _1)); RegisterSetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_LEGACY_ULA_PREFIX, std::bind(&DBusThreadObject::SetLegacyUlaPrefixHandler, this, _1)); RegisterSetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_LINK_MODE, std::bind(&DBusThreadObject::SetLinkModeHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_LINK_MODE, std::bind(&DBusThreadObject::GetLinkModeHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_DEVICE_ROLE, std::bind(&DBusThreadObject::GetDeviceRoleHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_NETWORK_NAME, std::bind(&DBusThreadObject::GetNetworkNameHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_PANID, std::bind(&DBusThreadObject::GetPanIdHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_EXTPANID, std::bind(&DBusThreadObject::GetExtPanIdHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_CHANNEL, std::bind(&DBusThreadObject::GetChannelHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_MASTER_KEY, std::bind(&DBusThreadObject::GetMasterKeyHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_CCA_FAILURE_RATE, std::bind(&DBusThreadObject::GetCcaFailureRateHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_LINK_COUNTERS, std::bind(&DBusThreadObject::GetLinkCountersHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_IP6_COUNTERS, std::bind(&DBusThreadObject::GetIp6CountersHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_SUPPORTED_CHANNEL_MASK, std::bind(&DBusThreadObject::GetSupportedChannelMaskHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_RLOC16, std::bind(&DBusThreadObject::GetRloc16Handler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_EXTENDED_ADDRESS, std::bind(&DBusThreadObject::GetExtendedAddressHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_ROUTER_ID, std::bind(&DBusThreadObject::GetRouterIdHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_LEADER_DATA, std::bind(&DBusThreadObject::GetLeaderDataHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_NETWORK_DATA_PRPOERTY, std::bind(&DBusThreadObject::GetNetworkDataHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_STABLE_NETWORK_DATA_PRPOERTY, std::bind(&DBusThreadObject::GetStableNetworkDataHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_LOCAL_LEADER_WEIGHT, std::bind(&DBusThreadObject::GetLocalLeaderWeightHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_CHANNEL_MONITOR_SAMPLE_COUNT, std::bind(&DBusThreadObject::GetChannelMonitorSampleCountHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_CHANNEL_MONITOR_ALL_CHANNEL_QUALITIES, std::bind(&DBusThreadObject::GetChannelMonitorAllChannelQualities, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_CHILD_TABLE, std::bind(&DBusThreadObject::GetChildTableHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_NEIGHBOR_TABLE_PROEPRTY, std::bind(&DBusThreadObject::GetNeighborTableHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_PARTITION_ID_PROEPRTY, std::bind(&DBusThreadObject::GetPartitionIDHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_INSTANT_RSSI, std::bind(&DBusThreadObject::GetInstantRssiHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_RADIO_TX_POWER, std::bind(&DBusThreadObject::GetRadioTxPowerHandler, this, _1)); RegisterGetPropertyHandler(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_EXTERNAL_ROUTES, std::bind(&DBusThreadObject::GetExternalRoutesHandler, this, _1)); return error; } void DBusThreadObject::DeviceRoleHandler(otDeviceRole aDeviceRole) { SignalPropertyChanged(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_DEVICE_ROLE, GetDeviceRoleName(aDeviceRole)); } void DBusThreadObject::ScanHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); threadHelper->Scan(std::bind(&DBusThreadObject::ReplyScanResult, this, aRequest, _1, _2)); } void DBusThreadObject::ReplyScanResult(DBusRequest & aRequest, otError aError, const std::vector<otActiveScanResult> &aResult) { std::vector<ActiveScanResult> results; if (aError != OT_ERROR_NONE) { aRequest.ReplyOtResult(aError); } else { for (const auto &r : aResult) { ActiveScanResult result; result.mExtAddress = ConvertOpenThreadUint64(r.mExtAddress.m8); result.mExtendedPanId = ConvertOpenThreadUint64(r.mExtendedPanId.m8); result.mNetworkName = r.mNetworkName.m8; result.mSteeringData = std::vector<uint8_t>(r.mSteeringData.m8, r.mSteeringData.m8 + r.mSteeringData.mLength); result.mPanId = r.mPanId; result.mJoinerUdpPort = r.mJoinerUdpPort; result.mChannel = r.mChannel; result.mRssi = r.mRssi; result.mLqi = r.mLqi; result.mVersion = r.mVersion; result.mIsNative = r.mIsNative; result.mIsJoinable = r.mIsJoinable; results.emplace_back(result); } aRequest.Reply(std::tie(results)); } } void DBusThreadObject::AttachHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); std::string name; uint16_t panid; uint64_t extPanId; std::vector<uint8_t> masterKey; std::vector<uint8_t> pskc; uint32_t channelMask; auto args = std::tie(masterKey, panid, name, extPanId, pskc, channelMask); if (DBusMessageToTuple(*aRequest.GetMessage(), args) != OTBR_ERROR_NONE) { aRequest.ReplyOtResult(OT_ERROR_INVALID_ARGS); } else { threadHelper->Attach(name, panid, extPanId, masterKey, pskc, channelMask, [aRequest](otError aError) mutable { aRequest.ReplyOtResult(aError); }); } } void DBusThreadObject::FactoryResetHandler(DBusRequest &aRequest) { aRequest.ReplyOtResult(OT_ERROR_NONE); otInstanceFactoryReset(mNcp->GetThreadHelper()->GetInstance()); mNcp->Reset(); mNcp->GetThreadHelper()->AddDeviceRoleHandler(std::bind(&DBusThreadObject::DeviceRoleHandler, this, _1)); SignalPropertyChanged(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_DEVICE_ROLE, GetDeviceRoleName(OT_DEVICE_ROLE_DISABLED)); } void DBusThreadObject::ResetHandler(DBusRequest &aRequest) { mNcp->Reset(); mNcp->GetThreadHelper()->AddDeviceRoleHandler(std::bind(&DBusThreadObject::DeviceRoleHandler, this, _1)); SignalPropertyChanged(OTBR_DBUS_THREAD_INTERFACE, OTBR_DBUS_PROPERTY_DEVICE_ROLE, GetDeviceRoleName(OT_DEVICE_ROLE_DISABLED)); aRequest.ReplyOtResult(OT_ERROR_NONE); } void DBusThreadObject::JoinerStartHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); std::string pskd, provisionUrl, vendorName, vendorModel, vendorSwVersion, vendorData; auto args = std::tie(pskd, provisionUrl, vendorName, vendorModel, vendorSwVersion, vendorData); if (DBusMessageToTuple(*aRequest.GetMessage(), args) != OTBR_ERROR_NONE) { aRequest.ReplyOtResult(OT_ERROR_INVALID_ARGS); } else { threadHelper->JoinerStart(pskd, provisionUrl, vendorName, vendorModel, vendorSwVersion, vendorData, [aRequest](otError aError) mutable { aRequest.ReplyOtResult(aError); }); } } void DBusThreadObject::JoinerStopHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); otJoinerStop(threadHelper->GetInstance()); aRequest.ReplyOtResult(OT_ERROR_NONE); } void DBusThreadObject::PermitUnsecureJoinHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); uint16_t port; uint32_t timeout; auto args = std::tie(port, timeout); if (DBusMessageToTuple(*aRequest.GetMessage(), args) != OTBR_ERROR_NONE) { aRequest.ReplyOtResult(OT_ERROR_INVALID_ARGS); } else { aRequest.ReplyOtResult(threadHelper->PermitUnsecureJoin(port, timeout)); } } void DBusThreadObject::AddOnMeshPrefixHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); OnMeshPrefix onMeshPrefix; auto args = std::tie(onMeshPrefix); otError error = OT_ERROR_NONE; otBorderRouterConfig config; VerifyOrExit(DBusMessageToTuple(*aRequest.GetMessage(), args) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); // size is guaranteed by parsing std::copy(onMeshPrefix.mPrefix.mPrefix.begin(), onMeshPrefix.mPrefix.mPrefix.end(), &config.mPrefix.mPrefix.mFields.m8[0]); config.mPrefix.mLength = onMeshPrefix.mPrefix.mLength; config.mPreference = onMeshPrefix.mPreference; config.mSlaac = onMeshPrefix.mSlaac; config.mDhcp = onMeshPrefix.mDhcp; config.mConfigure = onMeshPrefix.mConfigure; config.mDefaultRoute = onMeshPrefix.mDefaultRoute; config.mOnMesh = onMeshPrefix.mOnMesh; config.mStable = onMeshPrefix.mStable; SuccessOrExit(error = otBorderRouterAddOnMeshPrefix(threadHelper->GetInstance(), &config)); SuccessOrExit(error = otBorderRouterRegister(threadHelper->GetInstance())); exit: aRequest.ReplyOtResult(error); } void DBusThreadObject::RemoveOnMeshPrefixHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); Ip6Prefix onMeshPrefix; auto args = std::tie(onMeshPrefix); otError error = OT_ERROR_NONE; otIp6Prefix prefix; VerifyOrExit(DBusMessageToTuple(*aRequest.GetMessage(), args) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); // size is guaranteed by parsing std::copy(onMeshPrefix.mPrefix.begin(), onMeshPrefix.mPrefix.end(), &prefix.mPrefix.mFields.m8[0]); prefix.mLength = onMeshPrefix.mLength; SuccessOrExit(error = otBorderRouterRemoveOnMeshPrefix(threadHelper->GetInstance(), &prefix)); SuccessOrExit(error = otBorderRouterRegister(threadHelper->GetInstance())); exit: aRequest.ReplyOtResult(error); } void DBusThreadObject::AddExternalRouteHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); ExternalRoute route; auto args = std::tie(route); otError error = OT_ERROR_NONE; otExternalRouteConfig otRoute; otIp6Prefix & prefix = otRoute.mPrefix; VerifyOrExit(DBusMessageToTuple(*aRequest.GetMessage(), args) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); // size is guaranteed by parsing std::copy(route.mPrefix.mPrefix.begin(), route.mPrefix.mPrefix.end(), &prefix.mPrefix.mFields.m8[0]); prefix.mLength = route.mPrefix.mLength; otRoute.mPreference = route.mPreference; otRoute.mStable = route.mStable; SuccessOrExit(error = otBorderRouterAddRoute(threadHelper->GetInstance(), &otRoute)); if (route.mStable) { SuccessOrExit(error = otBorderRouterRegister(threadHelper->GetInstance())); } exit: aRequest.ReplyOtResult(error); } void DBusThreadObject::RemoveExternalRouteHandler(DBusRequest &aRequest) { auto threadHelper = mNcp->GetThreadHelper(); Ip6Prefix routePrefix; auto args = std::tie(routePrefix); otError error = OT_ERROR_NONE; otIp6Prefix prefix; VerifyOrExit(DBusMessageToTuple(*aRequest.GetMessage(), args) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); // size is guaranteed by parsing std::copy(routePrefix.mPrefix.begin(), routePrefix.mPrefix.end(), &prefix.mPrefix.mFields.m8[0]); prefix.mLength = routePrefix.mLength; SuccessOrExit(error = otBorderRouterRemoveRoute(threadHelper->GetInstance(), &prefix)); SuccessOrExit(error = otBorderRouterRegister(threadHelper->GetInstance())); exit: aRequest.ReplyOtResult(error); } void DBusThreadObject::IntrospectHandler(DBusRequest &aRequest) { std::string xmlString( #include "dbus/server/introspect.hpp" ); aRequest.Reply(std::tie(xmlString)); } otError DBusThreadObject::SetMeshLocalPrefixHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otMeshLocalPrefix prefix; std::array<uint8_t, OTBR_IP6_PREFIX_SIZE> data{}; otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageExtractFromVariant(&aIter, data) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); memcpy(&prefix.m8, &data.front(), sizeof(prefix.m8)); error = otThreadSetMeshLocalPrefix(threadHelper->GetInstance(), &prefix); exit: return error; } otError DBusThreadObject::SetLegacyUlaPrefixHandler(DBusMessageIter &aIter) { std::array<uint8_t, OTBR_IP6_PREFIX_SIZE> data; otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageExtractFromVariant(&aIter, data) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); otNcpHandleDidReceiveNewLegacyUlaPrefix(&data[0]); exit: return error; } otError DBusThreadObject::SetLinkModeHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); LinkModeConfig cfg; otLinkModeConfig otCfg; otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageExtractFromVariant(&aIter, cfg) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); otCfg.mDeviceType = cfg.mDeviceType; otCfg.mNetworkData = cfg.mNetworkData; otCfg.mSecureDataRequests = cfg.mSecureDataRequests; otCfg.mRxOnWhenIdle = cfg.mRxOnWhenIdle; error = otThreadSetLinkMode(threadHelper->GetInstance(), otCfg); exit: return error; } otError DBusThreadObject::GetLinkModeHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otLinkModeConfig otCfg = otThreadGetLinkMode(threadHelper->GetInstance()); LinkModeConfig cfg; otError error = OT_ERROR_NONE; cfg.mDeviceType = otCfg.mDeviceType; cfg.mNetworkData = otCfg.mNetworkData; cfg.mSecureDataRequests = otCfg.mSecureDataRequests; cfg.mRxOnWhenIdle = otCfg.mRxOnWhenIdle; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, cfg) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetDeviceRoleHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otDeviceRole role = otThreadGetDeviceRole(threadHelper->GetInstance()); std::string roleName = GetDeviceRoleName(role); ; otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, roleName) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetNetworkNameHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); std::string networkName = otThreadGetNetworkName(threadHelper->GetInstance()); otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, networkName) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetPanIdHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); uint16_t panId = otLinkGetPanId(threadHelper->GetInstance()); otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, panId) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetExtPanIdHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); const otExtendedPanId *extPanId = otThreadGetExtendedPanId(threadHelper->GetInstance()); uint64_t extPanIdVal; otError error = OT_ERROR_NONE; extPanIdVal = ConvertOpenThreadUint64(extPanId->m8); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, extPanIdVal) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetChannelHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); uint16_t channel = otLinkGetChannel(threadHelper->GetInstance()); otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, channel) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetMasterKeyHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); const otMasterKey * masterKey = otThreadGetMasterKey(threadHelper->GetInstance()); std::vector<uint8_t> keyVal(masterKey->m8, masterKey->m8 + sizeof(masterKey->m8)); otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, keyVal) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetCcaFailureRateHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); uint16_t failureRate = otLinkGetCcaFailureRate(threadHelper->GetInstance()); otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, failureRate) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetLinkCountersHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); const otMacCounters *otCounters = otLinkGetCounters(threadHelper->GetInstance()); MacCounters counters; otError error = OT_ERROR_NONE; counters.mTxTotal = otCounters->mTxTotal; counters.mTxUnicast = otCounters->mTxUnicast; counters.mTxBroadcast = otCounters->mTxBroadcast; counters.mTxAckRequested = otCounters->mTxAckRequested; counters.mTxAcked = otCounters->mTxAcked; counters.mTxNoAckRequested = otCounters->mTxNoAckRequested; counters.mTxData = otCounters->mTxData; counters.mTxDataPoll = otCounters->mTxDataPoll; counters.mTxBeacon = otCounters->mTxBeacon; counters.mTxBeaconRequest = otCounters->mTxBeaconRequest; counters.mTxOther = otCounters->mTxOther; counters.mTxRetry = otCounters->mTxRetry; counters.mTxErrCca = otCounters->mTxErrCca; counters.mTxErrAbort = otCounters->mTxErrAbort; counters.mTxErrBusyChannel = otCounters->mTxErrBusyChannel; counters.mRxTotal = otCounters->mRxTotal; counters.mRxUnicast = otCounters->mTxUnicast; counters.mRxBroadcast = otCounters->mRxBroadcast; counters.mRxData = otCounters->mRxData; counters.mRxDataPoll = otCounters->mTxDataPoll; counters.mRxBeacon = otCounters->mRxBeacon; counters.mRxBeaconRequest = otCounters->mRxBeaconRequest; counters.mRxOther = otCounters->mRxOther; counters.mRxAddressFiltered = otCounters->mRxAddressFiltered; counters.mRxDestAddrFiltered = otCounters->mRxDestAddrFiltered; counters.mRxDuplicated = otCounters->mRxDuplicated; counters.mRxErrNoFrame = otCounters->mRxErrNoFrame; counters.mRxErrUnknownNeighbor = otCounters->mRxErrUnknownNeighbor; counters.mRxErrInvalidSrcAddr = otCounters->mRxErrInvalidSrcAddr; counters.mRxErrSec = otCounters->mRxErrSec; counters.mRxErrFcs = otCounters->mRxErrFcs; counters.mRxErrOther = otCounters->mRxErrOther; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, counters) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetIp6CountersHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); const otIpCounters *otCounters = otThreadGetIp6Counters(threadHelper->GetInstance()); IpCounters counters; otError error = OT_ERROR_NONE; counters.mTxSuccess = otCounters->mTxSuccess; counters.mTxFailure = otCounters->mTxFailure; counters.mRxSuccess = otCounters->mRxSuccess; counters.mRxFailure = otCounters->mRxFailure; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, counters) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetSupportedChannelMaskHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); uint32_t channelMask = otLinkGetSupportedChannelMask(threadHelper->GetInstance()); otError error = OT_ERROR_NONE; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, channelMask) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetRloc16Handler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint16_t rloc16 = otThreadGetRloc16(threadHelper->GetInstance()); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, rloc16) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetExtendedAddressHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; const otExtAddress *addr = otLinkGetExtendedAddress(threadHelper->GetInstance()); uint64_t extendedAddress = ConvertOpenThreadUint64(addr->m8); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, extendedAddress) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetRouterIdHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint16_t rloc16 = otThreadGetRloc16(threadHelper->GetInstance()); otRouterInfo info; VerifyOrExit(otThreadGetRouterInfo(threadHelper->GetInstance(), rloc16, &info) == OT_ERROR_NONE, error = OT_ERROR_INVALID_STATE); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, info.mRouterId) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetLeaderDataHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; struct otLeaderData data; LeaderData leaderData; SuccessOrExit(error = otThreadGetLeaderData(threadHelper->GetInstance(), &data)); leaderData.mPartitionId = data.mPartitionId; leaderData.mWeighting = data.mWeighting; leaderData.mDataVersion = data.mDataVersion; leaderData.mStableDataVersion = data.mStableDataVersion; leaderData.mLeaderRouterId = data.mLeaderRouterId; VerifyOrExit(DBusMessageEncodeToVariant(&aIter, leaderData) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetNetworkDataHandler(DBusMessageIter &aIter) { static constexpr size_t kNetworkDataMaxSize = 255; auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint8_t data[kNetworkDataMaxSize]; uint8_t len = sizeof(data); std::vector<uint8_t> networkData; SuccessOrExit(error = otNetDataGet(threadHelper->GetInstance(), /*stable=*/false, data, &len)); networkData = std::vector<uint8_t>(&data[0], &data[len]); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, networkData) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetStableNetworkDataHandler(DBusMessageIter &aIter) { static constexpr size_t kNetworkDataMaxSize = 255; auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint8_t data[kNetworkDataMaxSize]; uint8_t len = sizeof(data); std::vector<uint8_t> networkData; SuccessOrExit(error = otNetDataGet(threadHelper->GetInstance(), /*stable=*/true, data, &len)); networkData = std::vector<uint8_t>(&data[0], &data[len]); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, networkData) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetLocalLeaderWeightHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint8_t weight = otThreadGetLocalLeaderWeight(threadHelper->GetInstance()); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, weight) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetChannelMonitorSampleCountHandler(DBusMessageIter &aIter) { #if OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint32_t cnt = otChannelMonitorGetSampleCount(threadHelper->GetInstance()); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, cnt) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; #else // OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE (void)aIter; return OT_ERROR_NOT_IMPLEMENTED; #endif // OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE } otError DBusThreadObject::GetChannelMonitorAllChannelQualities(DBusMessageIter &aIter) { #if OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint32_t channelMask = otLinkGetSupportedChannelMask(threadHelper->GetInstance()); constexpr uint8_t kNumChannels = sizeof(channelMask) * 8; // 8 bit per byte std::vector<ChannelQuality> quality; for (uint8_t i = 0; i < kNumChannels; i++) { if (channelMask & (1U << i)) { uint16_t occupancy = otChannelMonitorGetChannelOccupancy(threadHelper->GetInstance(), i); quality.emplace_back(ChannelQuality{i, occupancy}); } } VerifyOrExit(DBusMessageEncodeToVariant(&aIter, quality) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; #else // OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE (void)aIter; return OT_ERROR_NOT_IMPLEMENTED; #endif // OPENTHREAD_CONFIG_CHANNEL_MONITOR_ENABLE } otError DBusThreadObject::GetChildTableHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint16_t childIndex = 0; otChildInfo childInfo; std::vector<ChildInfo> childTable; while (otThreadGetChildInfoByIndex(threadHelper->GetInstance(), childIndex, &childInfo) == OT_ERROR_NONE) { ChildInfo info; info.mExtAddress = ConvertOpenThreadUint64(childInfo.mExtAddress.m8); info.mTimeout = childInfo.mTimeout; info.mAge = childInfo.mAge; info.mChildId = childInfo.mChildId; info.mNetworkDataVersion = childInfo.mNetworkDataVersion; info.mLinkQualityIn = childInfo.mLinkQualityIn; info.mAverageRssi = childInfo.mAverageRssi; info.mLastRssi = childInfo.mLastRssi; info.mFrameErrorRate = childInfo.mFrameErrorRate; info.mMessageErrorRate = childInfo.mMessageErrorRate; info.mRxOnWhenIdle = childInfo.mRxOnWhenIdle; info.mSecureDataRequest = childInfo.mSecureDataRequest; info.mFullThreadDevice = childInfo.mFullThreadDevice; info.mFullNetworkData = childInfo.mFullNetworkData; info.mIsStateRestoring = childInfo.mIsStateRestoring; childTable.push_back(info); childIndex++; } VerifyOrExit(DBusMessageEncodeToVariant(&aIter, childTable) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetNeighborTableHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; otNeighborInfoIterator iter = OT_NEIGHBOR_INFO_ITERATOR_INIT; otNeighborInfo neighborInfo; std::vector<NeighborInfo> neighborTable; while (otThreadGetNextNeighborInfo(threadHelper->GetInstance(), &iter, &neighborInfo) == OT_ERROR_NONE) { NeighborInfo info; info.mExtAddress = ConvertOpenThreadUint64(neighborInfo.mExtAddress.m8); info.mAge = neighborInfo.mAge; info.mRloc16 = neighborInfo.mRloc16; info.mLinkFrameCounter = neighborInfo.mLinkFrameCounter; info.mMleFrameCounter = neighborInfo.mMleFrameCounter; info.mLinkQualityIn = neighborInfo.mLinkQualityIn; info.mAverageRssi = neighborInfo.mAverageRssi; info.mLastRssi = neighborInfo.mLastRssi; info.mFrameErrorRate = neighborInfo.mFrameErrorRate; info.mMessageErrorRate = neighborInfo.mMessageErrorRate; info.mRxOnWhenIdle = neighborInfo.mRxOnWhenIdle; info.mSecureDataRequest = neighborInfo.mSecureDataRequest; info.mFullThreadDevice = neighborInfo.mFullThreadDevice; info.mFullNetworkData = neighborInfo.mFullNetworkData; info.mIsChild = neighborInfo.mIsChild; neighborTable.push_back(info); } VerifyOrExit(DBusMessageEncodeToVariant(&aIter, neighborTable) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetPartitionIDHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; uint32_t partitionId = otThreadGetPartitionId(threadHelper->GetInstance()); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, partitionId) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetInstantRssiHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; int8_t rssi = otPlatRadioGetRssi(threadHelper->GetInstance()); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, rssi) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetRadioTxPowerHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; int8_t txPower; SuccessOrExit(error = otPlatRadioGetTransmitPower(threadHelper->GetInstance(), &txPower)); VerifyOrExit(DBusMessageEncodeToVariant(&aIter, txPower) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } otError DBusThreadObject::GetExternalRoutesHandler(DBusMessageIter &aIter) { auto threadHelper = mNcp->GetThreadHelper(); otError error = OT_ERROR_NONE; otNetworkDataIterator iter = OT_NETWORK_DATA_ITERATOR_INIT; otExternalRouteConfig config; std::vector<ExternalRoute> externalRouteTable; while (otNetDataGetNextRoute(threadHelper->GetInstance(), &iter, &config) == OT_ERROR_NONE) { ExternalRoute route; route.mPrefix.mPrefix = std::vector<uint8_t>(&config.mPrefix.mPrefix.mFields.m8[0], &config.mPrefix.mPrefix.mFields.m8[OTBR_IP6_PREFIX_SIZE]); route.mPrefix.mLength = config.mPrefix.mLength; route.mRloc16 = config.mRloc16; route.mPreference = config.mPreference; route.mStable = config.mStable; route.mNextHopIsThisDevice = config.mNextHopIsThisDevice; externalRouteTable.push_back(route); } VerifyOrExit(DBusMessageEncodeToVariant(&aIter, externalRouteTable) == OTBR_ERROR_NONE, error = OT_ERROR_INVALID_ARGS); exit: return error; } } // namespace DBus } // namespace otbr
42.267016
120
0.69476
[ "vector" ]
4fe0c9301e1f4da138958a08b02972171001a006
6,866
cc
C++
LiteCore/RevTrees/RevID.cc
udkyo/couchbase-lite-core
18f3368186875461c49a559705f9a791e31c6fb9
[ "Apache-2.0" ]
null
null
null
LiteCore/RevTrees/RevID.cc
udkyo/couchbase-lite-core
18f3368186875461c49a559705f9a791e31c6fb9
[ "Apache-2.0" ]
null
null
null
LiteCore/RevTrees/RevID.cc
udkyo/couchbase-lite-core
18f3368186875461c49a559705f9a791e31c6fb9
[ "Apache-2.0" ]
null
null
null
// // RevID.cc // // Copyright (c) 2014 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "RevID.hh" #include "VersionVector.hh" #include "Error.hh" #include "varint.hh" #include "PlatformCompat.hh" #include "StringUtil.hh" #include "slice_stream.hh" #include <math.h> #include <limits.h> namespace litecore { using namespace fleece; static inline bool islowerxdigit(char c) { return isxdigit(c) && !isupper(c); } #pragma mark - API: pair<unsigned,slice> revid::generationAndDigest() const { if (isVersion()) error::_throw(error::InvalidParameter); slice_istream digest = *this; if (auto gen = digest.readUVarInt(); !gen || *gen == 0 || *gen > UINT_MAX) error::_throw(error::CorruptRevisionData); else return {unsigned(*gen), digest}; } unsigned revid::generation() const { if (isVersion()) return unsigned(asVersion().gen()); //FIX: Should Version.gen change to uint32? else return generationAndDigest().first; } Version revid::asVersion() const { if (isVersion()) return VersionVector::readCurrentVersionFromBinary(*this); else if (size == 0) error::_throw(error::CorruptRevisionData); // buffer too short! else error::_throw(error::InvalidParameter); // it's a digest, not a version } VersionVector revid::asVersionVector() const { if (isVersion()) return VersionVector::fromBinary(*this); else if (size == 0) error::_throw(error::CorruptRevisionData); // buffer too short! else error::_throw(error::InvalidParameter); // it's a digest, not a version } bool revid::operator< (const revid& other) const { if (isVersion()) { return asVersion() < other.asVersion(); } else { auto [myGen, myDigest] = generationAndDigest(); auto [otherGen, otherDigest] = other.generationAndDigest(); return (myGen != otherGen) ? myGen < otherGen : myDigest < otherDigest; } } bool revid::isEquivalentTo(const revid& other) const noexcept { if (*this == other) return true; else return isVersion() && other.isVersion() && asVersion() == other.asVersion(); } bool revid::expandInto(slice_ostream &result) const noexcept { slice_ostream out = result.capture(); if (isVersion()) { if (!asVersion().writeASCII(out)) return false; } else { auto [gen, digest] = generationAndDigest(); if (!out.writeDecimal(gen) || !out.writeByte('-') || !out.writeHex(digest)) return false; } result = out; return true; } alloc_slice revid::expanded() const { if (!buf) return alloc_slice(); if (isVersion()) { return asVersion().asASCII(); } else { auto [gen, digest] = generationAndDigest(); size_t expandedSize = 2 + size_t(::floor(::log10(gen))) + 2*digest.size; alloc_slice resultBuf(expandedSize); slice_ostream out(resultBuf); Assert(expandInto(out)); resultBuf.shorten(out.bytesWritten()); return resultBuf; } } std::string revid::str() const { alloc_slice exp = expanded(); return std::string((char*)exp.buf, exp.size); } #pragma mark - RevIDBuffer: revidBuffer::revidBuffer(unsigned generation, slice digest) :revid(&_buffer, 0) { uint8_t* dst = _buffer; dst += PutUVarInt(dst, generation); setSize(dst + digest.size - _buffer); if (size > sizeof(_buffer)) error::_throw(error::BadRevisionID); // digest too long! memcpy(dst, digest.buf, digest.size); } revidBuffer& revidBuffer::operator= (const revidBuffer& other) noexcept { memcpy(_buffer, other._buffer, sizeof(_buffer)); set(&_buffer, other.size); return *this; } revidBuffer& revidBuffer::operator= (const revid &other) { if (other.isVersion()) { // Just copy the first Version: *this = other.asVersion(); } else { if (other.size > sizeof(_buffer)) error::_throw(error::BadRevisionID); // digest too long! memcpy(_buffer, other.buf, other.size); set(&_buffer, other.size); } return *this; } revidBuffer& revidBuffer::operator= (const Version &vers) noexcept { slice_ostream out(_buffer, sizeof(_buffer)); out.writeByte(0); vers.writeBinary(out); *(slice*)this = out.output(); return *this; } void revidBuffer::parse(slice s) { if (!tryParse(s)) error::_throw(error::BadRevisionID); } bool revidBuffer::tryParse(slice asciiData) noexcept { slice_istream ascii(asciiData); if (ascii.findByte('-') != nullptr) { // Digest type: uint8_t* start = _buffer, *end = start + sizeof(_buffer), *dst = start; set(start, 0); uint64_t gen = ascii.readDecimal(); if (gen == 0 || gen > UINT_MAX) return false; dst += PutUVarInt(dst, gen); if (ascii.readByte() != '-') return false; // Copy hex digest into dst as binary: if (ascii.size == 0 || (ascii.size & 1) || dst + ascii.size / 2 > end) return false; // rev ID is too long to fit in my buffer for (unsigned i = 0; i < ascii.size; i += 2) { if (!islowerxdigit(ascii[i]) || !islowerxdigit(ascii[i+1])) return false; // digest is not hex *dst++ = (uint8_t)(16*digittoint(ascii[i]) + digittoint(ascii[i+1])); } setEnd(dst); return true; } else { // Vector type: auto comma = ascii.findByteOrEnd(','); auto vers = Version::readASCII(slice(ascii.buf, comma)); if (!vers) return false; *this = *vers; return true; } } }
31.209091
99
0.566269
[ "vector" ]
4fe127544be6f4439b184e1fcf4436eda4a53cc5
4,796
cc
C++
tensorflow/contrib/lite/toco/graph_transformations/propagate_array_data_types.cc
harunpehlivan/tensorflow
376e2cfdab31f4da251ea2e50992a9bf97fd171b
[ "Apache-2.0" ]
22
2018-01-13T14:52:47.000Z
2018-07-05T01:00:28.000Z
tensorflow/contrib/lite/toco/graph_transformations/propagate_array_data_types.cc
hamzabekkouri/tensorflow
d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f
[ "Apache-2.0" ]
null
null
null
tensorflow/contrib/lite/toco/graph_transformations/propagate_array_data_types.cc
hamzabekkouri/tensorflow
d87a9fbbc5f49ec5ae8eb52c62628f0b1a0bf67f
[ "Apache-2.0" ]
3
2018-01-20T06:47:34.000Z
2018-05-07T19:14:34.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/core/platform/logging.h" namespace toco { namespace { void SetDataTypeForAllOutputs(Model* model, Operator* op, ArrayDataType data_type) { for (const auto& output : op->outputs) { model->arrays[output]->data_type = data_type; } } } // namespace bool PropagateArrayDataTypes::Run(Model* model, std::size_t op_index) { auto it = model->operators.begin() + op_index; auto* op = it->get(); // If the data type of some input is unknown, we need to yield. for (const auto& input : op->inputs) { if (model->arrays[input]->data_type == ArrayDataType::kNone) { return false; } } // Record data types of output before processing, so we can see at the // end if we changed anything, and return the correct boolean value. std::unordered_map<string, ArrayDataType> old_output_data_types; for (const auto& output : op->outputs) { old_output_data_types[output] = model->arrays[output]->data_type; } // Do the actual output data types propagation. if (op->type == OperatorType::kDequantize || op->type == OperatorType::kResizeBilinear) { // These operators unconditionally produce float outputs SetDataTypeForAllOutputs(model, op, ArrayDataType::kFloat); } else if (op->type == OperatorType::kTensorFlowLess || op->type == OperatorType::kTensorFlowLessEqual || op->type == OperatorType::kTensorFlowGreater || op->type == OperatorType::kTensorFlowGreaterEqual) { // These operators unconditionally produce bool outputs SetDataTypeForAllOutputs(model, op, ArrayDataType::kBool); } else if (op->type == OperatorType::kRank || op->type == OperatorType::kTensorFlowShape) { // These operators are assumed to produce int32 outputs. SetDataTypeForAllOutputs(model, op, ArrayDataType::kInt32); } else if (op->type == OperatorType::kTensorFlowSplit || op->type == OperatorType::kTensorFlowConcat || op->type == OperatorType::kFill) { // These operators produce an output with the same type as their 2nd input CHECK_GE(op->inputs.size(), 2); const ArrayDataType data_type = model->arrays[op->inputs[1]]->data_type; SetDataTypeForAllOutputs(model, op, data_type); } else if (op->type == OperatorType::kCast) { // Data type of the Cast op is specified. CHECK_EQ(op->outputs.size(), 1); auto* cast_op = static_cast<CastOperator*>(op); model->arrays[op->outputs[0]]->data_type = cast_op->dst_data_type; } else if (op->type == OperatorType::kArgMax) { // Data type of the ArgMax op is specified. CHECK_EQ(op->outputs.size(), 1); auto* argmax_op = static_cast<ArgMaxOperator*>(op); model->arrays[op->outputs[0]]->data_type = argmax_op->output_data_type; } else if (op->type == OperatorType::kTensorFlowUnsupported) { auto* unsupported_op = static_cast<TensorFlowUnsupportedOperator*>(op); if (unsupported_op->output_data_types.size() != op->outputs.size()) { return false; } for (int i = 0; i < unsupported_op->output_data_types.size(); ++i) { auto output = op->outputs[i]; auto data_type = unsupported_op->output_data_types[i]; model->arrays[output]->data_type = data_type; } } else if (op->type == OperatorType::kExpandDims) { // Yield on ExpandDim until it is converted to Reshape return false; } else { // These operators produce outputs with the same type as their 1st input CHECK_GT(op->inputs.size(), 0); const ArrayDataType data_type = model->arrays[op->inputs[0]]->data_type; SetDataTypeForAllOutputs(model, op, data_type); } // Return true if any output data type changed, false if none changed. for (const auto& output : op->outputs) { if (old_output_data_types[output] != model->arrays[output]->data_type) { return true; } } return false; } } // namespace toco
42.821429
85
0.685363
[ "vector", "model" ]
4fe1d3aba7cfd9e4ac467487a45b26a421d5d4a9
13,921
cpp
C++
src/hmm_duo.cpp
jaredo/duohmm
95bd3958792aeaa43e9f301ead139e5691d7c165
[ "MIT" ]
null
null
null
src/hmm_duo.cpp
jaredo/duohmm
95bd3958792aeaa43e9f301ead139e5691d7c165
[ "MIT" ]
null
null
null
src/hmm_duo.cpp
jaredo/duohmm
95bd3958792aeaa43e9f301ead139e5691d7c165
[ "MIT" ]
null
null
null
//$Id$ #include "hmm.h" geneticMap::geneticMap(string fname){ pos.push_back(0); cM.push_back(0.0); if(fname.compare("")==0) { pos.push_back(4000e6); cM.push_back(4000. * 1.19); } else { ifstream inf2(fname.c_str()); if(!inf2) { cerr << "Problem reading genetic map: " << fname << "\nExiting..."<<endl; exit(1); } int tmp1; float tmp2,tmp3; inf2.ignore(1000,'\n'); while(inf2) { inf2 >> tmp1; inf2 >> tmp2; inf2 >> tmp3; // if(DEBUG>0) // cout << tmp1 <<"\t" <<tmp2<<"\t"<<tmp3<<endl; pos.push_back(tmp1); cM.push_back(tmp3); } float maxpos = pos[pos.size()-1] + 5e6; float last_cm = cM[cM.size()-1] + 5*1.19; pos.push_back(maxpos); cM.push_back(last_cm); // cout << maxpos << " " << last_cm<<endl; } nsnp = pos.size(); } #ifdef SHAPEIT geneticMap::geneticMap(genhap_set & GH) { pos.push_back(0); cM.push_back(0.0); for(size_t l=0;l<GH.mapG->vec_pos.size();l++) { pos.push_back(GH.mapG->vec_pos[l]->bp); cM.push_back(GH.mapG->vec_pos[l]->cm); } nsnp = pos.size(); } #endif geneticMap::geneticMap() { int maxpos = 1000000000; pos.push_back(0); pos.push_back(maxpos); cM.push_back(0.0); cM.push_back(maxpos/1000000. * 1.19); nsnp = 2; } float geneticMap::interpolate(int position) { int i=0; while(i<nsnp && pos[i]<=position) { i++; } assert(i>0); if(i>=nsnp) { i--; #ifndef SHAPEIT cerr << "WARNING: marker at position "<<position<< " was outside the range of provided genetic map"<<endl; cerr << "Is your map the appropriate chromosome and build?" << endl; #endif } return( cM[i-1] + (cM[i]-cM[i-1])*(float)(position-pos[i-1])/(float)(pos[i]-pos[i-1]) ); } int geneticMap::interpolate(vector<int> & positions,vector<float> & output){ output.resize(positions.size()); for(size_t i=0;i<positions.size();i++) { output[i] = interpolate(positions[i]); // #ifdef DEBUG // cerr<<positions[i]<<"\t"<<output[i]<<endl; // #endif } return(0); } void DuoHMM::setIterations(int n) { NITERATION = n; } DuoHMM::DuoHMM(vector<int> & positions, geneticMap & gm) { NITERATION=100; float r; male_multiplier = 0.7539868; female_multiplier = 1.2460132; K=4; nsnp=positions.size(); cM.resize(nsnp); gm.interpolate(positions,cM); male_length = (cM[nsnp-1]* male_multiplier)/100.; female_length = (cM[nsnp-1] * female_multiplier)/100.; male_rho.resize(nsnp); male_norho.resize(nsnp); female_rho.resize(nsnp); female_norho.resize(nsnp); for(int i=0;i<nsnp-1;i++) { r = (cM[i+1]-cM[i])/100.; if(r<=0.0) r = 1e-13;//hack to handle positions with same genetic location (which shouldnt be in the snps in the first place) male_norho[i] = exp(-r * male_multiplier); male_rho[i] = 1. - male_norho[i]; female_norho[i] = exp(-r * female_multiplier); female_rho[i] = 1. - female_norho[i]; } scale.resize(nsnp); alpha.assign(K,vector<float>(nsnp)); beta.assign(K,vector<float>(nsnp)); posterior.assign(K,vector<float>(nsnp)); // alpha.resize(K); // beta.resize(K); // posterior.resize(K); // for(int i=0;i<K;i++) { // alpha[i].resize(nsnp); // beta[i].resize(nsnp); // posterior[i].resize(nsnp); // } trans_posterior.resize(K); for(int i=0;i<K;i++) { trans_posterior[i].resize(K); for(int j=0;j<K;j++) trans_posterior[i][j].resize(nsnp,0.0); } error = 0.001; switch1 = 0.0005; switch2 = 0.0005; } int DuoHMM::forward() { int l = 0; float noerror = 1. - error; scale.assign(nsnp,0.0); for(int i=0;i<K;i++) alpha[i].assign(nsnp,0.0); //initial step for(int i=0;i<K/2;i++) { for(int j=0;j<K/2;j++) { int idx = i*2+j; if(child[j][l]==parent[i][l]) alpha[idx][l] = noerror; else alpha[idx][l] = error; alpha[idx][l] /= K; scale[l] += alpha[idx][l]; } } scale[l] = 1./scale[l]; for(int i=0;i<K;i++) alpha[i][l] *= scale[l]; //induction int idx1,idx2; float tmp; for(l=1;l<nsnp;l++) { for(int i2=0;i2<2;i2++) { for(int j2=0;j2<2;j2++) { idx2 = i2*2+j2; for(int i1=0;i1<2;i1++) {//transition probs for(int j1=0;j1<2;j1++) { idx1 = i1*2+j1; if(i1==i2) tmp = (1-rho[l-1])*(1-switch1) + rho[l-1]*switch1; else tmp = rho[l-1]*(1-switch1) + (1. - rho[l-1])*switch1 ; if(j1==j2) tmp *= (1. - switch2); else tmp *= switch2; tmp *= alpha[idx1][l-1]; alpha[idx2][l]+=tmp; } } //emission if(child[j2][l]==parent[i2][l]) alpha[idx2][l] *= noerror; else alpha[idx2][l] *= error; scale[l] += alpha[idx2][l]; } } scale[l] = 1./scale[l]; for(int i=0;i<K;i++) alpha[i][l] *= scale[l]; } return(0); } int DuoHMM::backward() { float noerror = 1. - error; int l = nsnp-1; for(int i=0;i<K;i++) beta[i].assign(nsnp,0.0); //initial step for(int i=0;i<K;i++) beta[i][l] = scale[l]; //induction float tmp; for(l=nsnp-2;l>=0;l--) { for(int i2=0;i2<2;i2++) { for(int j2=0;j2<2;j2++) { int idx2 = i2*2+j2; for(int i1=0;i1<2;i1++) {//transition probs for(int j1=0;j1<2;j1++) { int idx1 = i1*2+j1; if(i1==i2) tmp = (1-rho[l])*(1-switch1) + rho[l]*switch1; else tmp = rho[l]*(1. -switch1) + (1. - rho[l])*switch1 ; if(j1==j2) tmp *= (1. - switch2); else tmp *= switch2; tmp *= beta[idx1][l+1]; if(child[j1][l+1]==parent[i1][l+1]) tmp *= noerror; else tmp *= error; beta[idx2][l]+=tmp; } } beta[idx2][l] *= scale[l]; } } } return(0); } int DuoHMM::setHaps(vector<bool> *parental_haplotypes,vector<bool> *child_haplotypes,string sex) { assert(parental_haplotypes!=NULL && child_haplotypes!=NULL); // cout << sex << endl; assert(sex.compare("1")==0 || sex.compare("2")==0); parent = parental_haplotypes; child = child_haplotypes; if(sex.compare("1")==0) { rho = &male_rho[0]; genetic_length = male_length; multi = male_multiplier; } else { rho = &female_rho[0]; genetic_length = female_length; multi = female_multiplier; } error = 0.001; switch1 = 0.0005; switch2 = 0.0005; return(0); } int DuoHMM::EM(int niteration) { float switch1_old=switch1; float switch2_old=switch2; float error_old=error; float tol=0.00001; float dif=2*tol; int i=0; while(i<niteration && dif>tol) { if(DEBUG>1) { cout << "ITERATION " <<i<<endl; cout << "error = "<< error << endl; cout << "switch1 = "<< switch1 << endl; cout << "switch2 = "<< switch2 << endl; } estep(); mstep(); dif = abs(switch1_old-switch1)+abs( switch2_old-switch2)+abs(error_old-error); switch1_old=switch1; switch2_old=switch2; error_old=error; i++; } return(0); } int DuoHMM::mstep() { float ngenerror = 0.0; float nswitch1 = 0.0; float nswitch2 = 0.0; int nhet1=0; int nhet2=0; int nhet3=0; genError.assign(nsnp,0.0); for(int l=0;l<nsnp;l++) { if(parent[0][l]!=parent[1][l]) nhet1++; if(child[0][l]!=child[1][l]) nhet2++; if(child[0][l]!=child[1][l] || parent[0][l]!=parent[1][l]) nhet3++; //genotyping error counts for(int i=0;i<K/2;i++) { for(int j=0;j<K/2;j++) { int idx = i*2+j; if(child[j][l]!=parent[i][l]) { ngenerror += posterior[idx][l]; genError[l] += posterior[idx][l]; } } } } for(int l=0;l<nsnp-1;l++) { //switch error counts for(int i2=0;i2<2;i2++) { for(int j2=0;j2<2;j2++) { int idx2 = i2*2+j2; for(int i1=0;i1<2;i1++) {//transition probs for(int j1=0;j1<2;j1++) { int idx1 = i1*2+j1; if(i1!=i2) nswitch1 += trans_posterior[idx1][idx2][l]; if(j1!=j2) nswitch2 += trans_posterior[idx1][idx2][l]; } } } } } if(DEBUG>1) { cout << "nswitch1 = " << nswitch1<<endl; cout << "nswitch2 = " << nswitch2<<endl; cout << "ngenerror = " << ngenerror<<endl; } //since these events are only detectable at hetorzygote sites, mstep denominator should probably be nhets rather than nsnp //in practice makes little difference /* switch1 = (nswitch1 - genetic_length) / (nhet1 - 2*genetic_length); if(switch1<0.0) switch1 = 0.0; switch2 = nswitch2 / nhet2; error = ngenerror / nhet3; */ switch1 = (nswitch1 - genetic_length) / (nsnp - 2*genetic_length); if(switch1<0.0) switch1 = 0.0; switch2 = nswitch2 / nsnp; error = ngenerror / nsnp; return(0); } int DuoHMM::estep() { forward(); backward(); float noerror = 1. - error; float denominator; for(int l=0;l<nsnp;l++) { denominator = 0.0; for(int i=0;i<K;i++) { posterior[i][l] = alpha[i][l] * beta[i][l]; denominator+=posterior[i][l]; } for(int i=0;i<K;i++) posterior[i][l] /= denominator; } float aij; for(int l=0;l<(nsnp-1);l++) { assert(l<(nsnp-1)); if(!(rho[l]>=0.0 && rho[l]<1.)) { cerr << "ERROR BAD RECOMBINATION RATE AT MARKER " << l << " rho = "<<rho[l]<<endl; cerr << cM[l] << " " << cM[l+1]<<endl; exit(1); } denominator = 0.0; for(int i2=0;i2<2;i2++) { for(int j2=0;j2<2;j2++) { int idx2 = i2*2+j2; for(int i1=0;i1<2;i1++) {//transition probs for(int j1=0;j1<2;j1++) { int idx1 = i1*2+j1; trans_posterior[idx1][idx2][l] = alpha[idx1][l]*beta[idx2][l+1]; if(i1==i2) aij = (1-rho[l])*(1-switch1) + rho[l]*switch1 ; else aij = rho[l]*(1-switch1) + (1. - rho[l])*switch1 ; if(j1==j2) aij *= (1. - switch2); else aij *= switch2; trans_posterior[idx1][idx2][l] *= aij; //emission if(child[j2][l+1]==parent[i2][l+1]) trans_posterior[idx1][idx2][l] *= noerror; else trans_posterior[idx1][idx2][l] *= error; denominator += trans_posterior[idx1][idx2][l]; } } } } for(int i2=0;i2<2;i2++) { for(int j2=0;j2<2;j2++) { int idx2 = i2*2+j2; for(int i1=0;i1<2;i1++) {//transition probs for(int j1=0;j1<2;j1++) { int idx1 = i1*2+j1; // float tmp = trans_posterior[idx1][idx2][l]; trans_posterior[idx1][idx2][l] /= denominator; // if(trans_posterior[idx1][idx2][l] > 0.5 && i1!=i2) // cout << l << "\t" << idx1 << "\t" << idx2 << "\t" << tmp << "\t" << denominator << endl; } } } } } return(0); } int DuoHMM::viterbi() { int l = 0; float logerror = log(error); float lognoerror = log(1. - error); stateseq.resize(nsnp); backtrack.resize(K); for(int i=0;i<K;i++) backtrack[i].assign(nsnp,0); //initial step for(int i=0;i<K/2;i++) { for(int j=0;j<K/2;j++) { int idx = i*2+j; if(child[j][l]==parent[i][l]) alpha[idx][l] = lognoerror; else alpha[idx][l] = logerror; alpha[idx][l] -= log(K); } } //induction int idx1,idx2; vector<float> tmp(4,0.0); for(l=1;l<nsnp;l++) { for(int i2=0;i2<2;i2++) { for(int j2=0;j2<2;j2++) { idx2 = i2*2+j2; for(int i1=0;i1<2;i1++) {//transition probs for(int j1=0;j1<2;j1++) { idx1 = i1*2+j1; if(i1==i2) tmp[idx1] = log( (1-rho[l-1])*(1-switch1) + rho[l-1]*switch1 ); else tmp[idx1] = log(rho[l-1]*(1-switch1) + (1. - rho[l-1])*switch1); if(j1==j2) tmp[idx1] += log(1. - switch2); else tmp[idx1] += log(switch2); tmp[idx1] += alpha[idx1][l-1]; } } int maxind = argmax(tmp); backtrack[idx2][l]=maxind; //emission if(child[j2][l]==parent[i2][l]) alpha[idx2][l] = tmp[maxind]+lognoerror; else alpha[idx2][l] = tmp[maxind]+logerror; } } } //backtrack int maxind=0; for(int i=1;i<K;i++) if(alpha[i][nsnp-1]>alpha[maxind][nsnp-1]) maxind=i; stateseq[nsnp-1]=maxind; for(l=nsnp-2;l>=0;l--) stateseq[l] = backtrack[stateseq[l+1]][l+1]; if(DEBUG>1) { for(int l=0;l<nsnp;l++) cout << l << "\t" << (int)stateseq[l] << endl; } return(0); } int DuoHMM::estimateRecombination() { recombinationMap.assign(nsnp,0.0); EM(NITERATION); float noerror = 1. - error; float r,rho2; int prevhet=-1; int l=0; while(parent[0][l]==parent[1][l]) l++; prevhet=l; vector <float> p; while(l<nsnp) { float recp=0; float denominator=0,p1,p2; while(parent[0][l]==parent[1][l] && l<nsnp) l++; if(l<nsnp) { r = multi * (cM[l]-cM[prevhet])/100.; if(r<=0.0) r = 1e-13;//hack to handle positions with same genetic location (which shouldnt be in the snps in the first place) rho2 = 1 - exp(-r); for(int i2=0;i2<2;i2++) { for(int j2=0;j2<2;j2++) { int idx2 = i2*2+j2; for(int i1=0;i1<2;i1++) {//transition probs for(int j1=0;j1<2;j1++) { int idx1 = i1*2+j1; if(child[j2][l]==parent[i2][l]) p1 = noerror*alpha[idx1][prevhet]*beta[idx2][l]; else p1 = error*alpha[idx1][prevhet]*beta[idx2][l]; p2 = p1; if(i1==i2) { p1 *= rho2*switch1; p2 *= ( (1-rho2)*(1-switch1) + rho2*switch1 ); } else { p1 *= rho2*(1-switch1); p2 *= ( rho2*(1-switch1) + (1. - rho2)*switch1 ); } if(j1==j2) { p1 *= (1. - switch2); p2 *= (1. - switch2); } else { p1 *= switch2; p2 *= switch2; } recp += p1; denominator += p2; } } } } recp/=denominator; } else { recp = 0.0; } if(!(recp>=0.0 && recp<=1.0)){ cout << "ERROR:Invalid probability encountered"<<endl<<recp<<endl; cout << l << endl; cout << cM[l]<<" "<<cM[prevhet]<< endl; cout << r << endl; cout << rho2 << endl; cout << switch1 << endl; cout << switch2 << endl; exit(1); }; for(int i=prevhet;i<l;i++) recombinationMap[i] = recp; prevhet=l; l++; } return 0; }
22.821311
131
0.542131
[ "vector" ]
4fe4fdb45256ea6afa9443ab639371b3312825e5
10,933
cc
C++
content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/renderer_webmediaplayer_delegate_browsertest.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <tuple> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/location.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/simple_test_tick_clock.h" #include "base/threading/thread_task_runner_handle.h" #include "content/common/media/media_player_delegate_messages.h" #include "content/public/renderer/render_view.h" #include "content/public/test/render_view_test.h" #include "content/renderer/media/renderer_webmediaplayer_delegate.h" #include "content/renderer/render_process.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { ACTION_P(RunClosure, closure) { closure.Run(); } class MockWebMediaPlayerDelegateObserver : public WebMediaPlayerDelegate::Observer { public: MockWebMediaPlayerDelegateObserver() {} ~MockWebMediaPlayerDelegateObserver() {} // WebMediaPlayerDelegate::Observer implementation. MOCK_METHOD0(OnHidden, void()); MOCK_METHOD0(OnShown, void()); MOCK_METHOD1(OnSuspendRequested, void(bool)); MOCK_METHOD0(OnPlay, void()); MOCK_METHOD0(OnPause, void()); MOCK_METHOD1(OnVolumeMultiplierUpdate, void(double)); }; class RendererWebMediaPlayerDelegateTest : public content::RenderViewTest { public: RendererWebMediaPlayerDelegateTest() {} ~RendererWebMediaPlayerDelegateTest() override {} void SetUp() override { RenderViewTest::SetUp(); delegate_manager_.reset( new RendererWebMediaPlayerDelegate(view_->GetMainRenderFrame())); } void TearDown() override { // Destruct the controller prior to any other tear down to avoid out of // order destruction relative to the test render frame. delegate_manager_.reset(); RenderViewTest::TearDown(); } protected: IPC::TestSink& test_sink() { return render_thread_->sink(); } std::unique_ptr<RendererWebMediaPlayerDelegate> delegate_manager_; private: DISALLOW_COPY_AND_ASSIGN(RendererWebMediaPlayerDelegateTest); }; TEST_F(RendererWebMediaPlayerDelegateTest, SendsMessagesCorrectly) { testing::StrictMock<MockWebMediaPlayerDelegateObserver> observer; const int delegate_id = delegate_manager_->AddObserver(&observer); // Verify the playing message. { const bool kHasVideo = true, kHasAudio = false, kIsRemote = false; const base::TimeDelta kDuration = base::TimeDelta::FromSeconds(5); delegate_manager_->DidPlay(delegate_id, kHasVideo, kHasAudio, kIsRemote, kDuration); const IPC::Message* msg = test_sink().GetUniqueMessageMatching( MediaPlayerDelegateHostMsg_OnMediaPlaying::ID); ASSERT_TRUE(msg); std::tuple<int, bool, bool, bool, base::TimeDelta> result; ASSERT_TRUE(MediaPlayerDelegateHostMsg_OnMediaPlaying::Read(msg, &result)); EXPECT_EQ(delegate_id, std::get<0>(result)); EXPECT_EQ(kHasVideo, std::get<1>(result)); EXPECT_EQ(kHasAudio, std::get<2>(result)); EXPECT_EQ(kIsRemote, std::get<3>(result)); EXPECT_EQ(kDuration, std::get<4>(result)); } // Verify the paused message. { test_sink().ClearMessages(); const bool kReachedEndOfStream = true; delegate_manager_->DidPause(delegate_id, kReachedEndOfStream); const IPC::Message* msg = test_sink().GetUniqueMessageMatching( MediaPlayerDelegateHostMsg_OnMediaPaused::ID); ASSERT_TRUE(msg); std::tuple<int, bool> result; ASSERT_TRUE(MediaPlayerDelegateHostMsg_OnMediaPaused::Read(msg, &result)); EXPECT_EQ(delegate_id, std::get<0>(result)); EXPECT_EQ(kReachedEndOfStream, std::get<1>(result)); } // Verify the destruction message. { test_sink().ClearMessages(); delegate_manager_->PlayerGone(delegate_id); const IPC::Message* msg = test_sink().GetUniqueMessageMatching( MediaPlayerDelegateHostMsg_OnMediaDestroyed::ID); ASSERT_TRUE(msg); std::tuple<int> result; ASSERT_TRUE( MediaPlayerDelegateHostMsg_OnMediaDestroyed::Read(msg, &result)); EXPECT_EQ(delegate_id, std::get<0>(result)); } delegate_manager_->RemoveObserver(delegate_id); } TEST_F(RendererWebMediaPlayerDelegateTest, DeliversObserverNotifications) { testing::StrictMock<MockWebMediaPlayerDelegateObserver> observer; const int delegate_id = delegate_manager_->AddObserver(&observer); EXPECT_CALL(observer, OnHidden()); delegate_manager_->WasHidden(); EXPECT_CALL(observer, OnShown()); delegate_manager_->WasShown(); EXPECT_CALL(observer, OnPause()); MediaPlayerDelegateMsg_Pause pause_msg(0, delegate_id); delegate_manager_->OnMessageReceived(pause_msg); EXPECT_CALL(observer, OnPlay()); MediaPlayerDelegateMsg_Play play_msg(0, delegate_id); delegate_manager_->OnMessageReceived(play_msg); const double kTestMultiplier = 0.5; EXPECT_CALL(observer, OnVolumeMultiplierUpdate(kTestMultiplier)); MediaPlayerDelegateMsg_UpdateVolumeMultiplier volume_msg(0, delegate_id, kTestMultiplier); delegate_manager_->OnMessageReceived(volume_msg); EXPECT_CALL(observer, OnSuspendRequested(true)); MediaPlayerDelegateMsg_SuspendAllMediaPlayers suspend_msg(0); delegate_manager_->OnMessageReceived(suspend_msg); delegate_manager_->RemoveObserver(delegate_id); } TEST_F(RendererWebMediaPlayerDelegateTest, IdleDelegatesAreSuspended) { // Start the tick clock off at a non-null value. base::SimpleTestTickClock tick_clock; tick_clock.Advance(base::TimeDelta::FromSeconds(1234)); const base::TimeDelta kIdleTimeout = base::TimeDelta::FromSeconds(2); delegate_manager_->SetIdleCleanupParamsForTesting(kIdleTimeout, &tick_clock); EXPECT_FALSE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); // Just adding an observer should not start the idle timer. testing::StrictMock<MockWebMediaPlayerDelegateObserver> observer_1; const int delegate_id_1 = delegate_manager_->AddObserver(&observer_1); EXPECT_FALSE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); // Starting playback should not have an idle timer. delegate_manager_->DidPlay(delegate_id_1, true, true, false, base::TimeDelta()); EXPECT_FALSE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); // Never calling DidPlay() but calling DidPause() should count as idle. testing::StrictMock<MockWebMediaPlayerDelegateObserver> observer_2; const int delegate_id_2 = delegate_manager_->AddObserver(&observer_2); delegate_manager_->DidPause(delegate_id_2, false); EXPECT_TRUE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); // Adding the observer should instantly queue the timeout task, once run the // second delegate should be expired while the first is kept alive. { EXPECT_CALL(observer_2, OnSuspendRequested(false)) .WillOnce(RunClosure(base::Bind( &RendererWebMediaPlayerDelegate::PlayerGone, base::Unretained(delegate_manager_.get()), delegate_id_2))); base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); tick_clock.Advance(kIdleTimeout + base::TimeDelta::FromMicroseconds(1)); run_loop.Run(); } // Pausing should count as idle if playback didn't reach end of stream, but // in this case the player will not remove the MediaSession. delegate_manager_->DidPause(delegate_id_1, false /* reached_end_of_stream */); testing::StrictMock<MockWebMediaPlayerDelegateObserver> observer_3; const int delegate_id_3 = delegate_manager_->AddObserver(&observer_3); delegate_manager_->DidPlay(delegate_id_3, true, true, false, base::TimeDelta()); // Adding the observer should instantly queue the timeout task, once run no // delegates should have been expired. { EXPECT_CALL(observer_1, OnSuspendRequested(false)) .Times(testing::AtLeast(1)); base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); tick_clock.Advance(kIdleTimeout + base::TimeDelta::FromMicroseconds(1)); run_loop.Run(); } delegate_manager_->DidPlay(delegate_id_1, true, true, false, base::TimeDelta()); // Pausing after reaching end of stream should count as idle. delegate_manager_->DidPause(delegate_id_1, true /* reached_end_of_stream */); // Once the timeout task runs the first delegate should be expired while the // third is kept alive. { EXPECT_CALL(observer_1, OnSuspendRequested(false)) .WillOnce(RunClosure(base::Bind( &RendererWebMediaPlayerDelegate::PlayerGone, base::Unretained(delegate_manager_.get()), delegate_id_1))); base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); tick_clock.Advance(kIdleTimeout + base::TimeDelta::FromMicroseconds(1)); run_loop.Run(); } delegate_manager_->RemoveObserver(delegate_id_1); delegate_manager_->RemoveObserver(delegate_id_2); delegate_manager_->RemoveObserver(delegate_id_3); EXPECT_FALSE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); } TEST_F(RendererWebMediaPlayerDelegateTest, IdleDelegatesIgnoresSuspendRequest) { // Start the tick clock off at a non-null value. base::SimpleTestTickClock tick_clock; tick_clock.Advance(base::TimeDelta::FromSeconds(1234)); const base::TimeDelta kIdleTimeout = base::TimeDelta::FromSeconds(2); delegate_manager_->SetIdleCleanupParamsForTesting(kIdleTimeout, &tick_clock); EXPECT_FALSE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); testing::StrictMock<MockWebMediaPlayerDelegateObserver> observer_1; const int delegate_id_1 = delegate_manager_->AddObserver(&observer_1); EXPECT_FALSE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); // Calling DidPause() should instantly queue the timeout task. delegate_manager_->DidPause(delegate_id_1, false); EXPECT_TRUE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); // Wait for the suspend request, but don't call PlayerGone(). EXPECT_CALL(observer_1, OnSuspendRequested(false)); base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, run_loop.QuitClosure()); tick_clock.Advance(kIdleTimeout + base::TimeDelta::FromMicroseconds(1)); run_loop.Run(); // Even though the player did not call PlayerGone() it should be removed from // future idle cleanup polls. EXPECT_FALSE(delegate_manager_->IsIdleCleanupTimerRunningForTesting()); delegate_manager_->RemoveObserver(delegate_id_1); } } // namespace media
39.756364
80
0.743437
[ "render" ]
4fe5d90f9155071857b6953cff5045df7ece5039
51,395
cpp
C++
src/CLR/Core/Thread.cpp
skyflashde/nf-interpreter
664db50bce6990c39591fb736ecac7e6aa70a927
[ "Apache-2.0" ]
3
2019-11-14T09:25:24.000Z
2020-05-08T16:39:02.000Z
src/CLR/Core/Thread.cpp
skyflashde/nf-interpreter
664db50bce6990c39591fb736ecac7e6aa70a927
[ "Apache-2.0" ]
127
2019-06-20T22:18:44.000Z
2022-03-14T13:11:12.000Z
src/CLR/Core/Thread.cpp
skyflashde/nf-interpreter
664db50bce6990c39591fb736ecac7e6aa70a927
[ "Apache-2.0" ]
8
2020-02-21T13:33:46.000Z
2021-05-17T23:36:46.000Z
// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "Core.h" //////////////////////////////////////////////////////////////////////////////////////////////////// HRESULT CLR_RT_SubThread::CreateInstance( CLR_RT_Thread* th, CLR_RT_StackFrame* stack, int priority, CLR_RT_SubThread*& sthRef ) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_SubThread* sth = EVENTCACHE_EXTRACT_NODE(g_CLR_RT_EventCache,CLR_RT_SubThread,DATATYPE_SUBTHREAD); CHECK_ALLOCATION(sth); sth->m_owningThread = th; // CLR_RT_Thread* m_owningThread; sth->m_owningStackFrame = stack; // CLR_RT_StackFrame* m_owningStackFrame; sth->m_lockRequestsCount = 0; // CLR_UINT32 m_lockRequestsCount; // sth->m_priority = priority; // int m_priority; sth->m_timeConstraint = TIMEOUT_INFINITE; // CLR_INT64 m_timeConstraint; sth->m_status = 0; // CLR_UINT32 m_status; th->m_subThreads.LinkAtBack( sth ); NANOCLR_CLEANUP(); sthRef = sth; NANOCLR_CLEANUP_END(); } void CLR_RT_SubThread::DestroyInstance( CLR_RT_Thread* th, CLR_RT_SubThread* sthBase, int flags ) { NATIVE_PROFILE_CLR_CORE(); // // You cannot destroy a subthread without destroying all the children subthreads. // while(true) { CLR_RT_SubThread* sth = th->CurrentSubThread(); if(sth->Prev() == NULL) break; // // Release all the frames for this subthread. // while(true) { CLR_RT_StackFrame* stack = th->CurrentFrame(); if(stack->Prev() == NULL) break; if(stack == sth->m_owningStackFrame) break; stack->Pop(); } // // Release all the locks for this subthread. // NANOCLR_FOREACH_NODE(CLR_RT_HeapBlock_Lock,lock,th->m_locks) { lock->DestroyOwner( sth ); } NANOCLR_FOREACH_NODE_END(); // // Release all the lock requests. // g_CLR_RT_ExecutionEngine.DeleteLockRequests( NULL, sth ); if(sth == sthBase && (flags & CLR_RT_SubThread::MODE_IncludeSelf) == 0) break; g_CLR_RT_EventCache.Append_Node( sth ); if(sth == sthBase) break; } } bool CLR_RT_SubThread::ChangeLockRequestCount( int diff ) { NATIVE_PROFILE_CLR_CORE(); CLR_RT_Thread* th = m_owningThread; this->m_lockRequestsCount += diff; th ->m_lockRequestsCount += diff; if(th->m_lockRequestsCount == 0) { th->Restart( false ); return true; } else { th->m_status = CLR_RT_Thread::TH_S_Waiting; return false; } } void CLR_RT_Thread::BringExecCounterToDate( int iGlobalExecutionCounter, int iDebitForEachRun ) { (void)iDebitForEachRun; // Normally the condition is false. It becomes true if thread was out of execution for some time. // The value of (ThreadPriority::System_Highest + 1) is 33. // 33 for ThreadPriority::Highest gives up to 16 cycles to catch up. // 33 for ThreadPriority::Lowest we provide only 1 cycle to catch up. // If thread was sleeping for some time we forefeet the time it was sleeping and not updating execution counter. if ( m_executionCounter - iGlobalExecutionCounter > (int)((1 << ThreadPriority::System_Highest) + 1) ) { m_executionCounter = iGlobalExecutionCounter + (int)((1 << ThreadPriority::System_Highest) + 1); } } //////////////////////////////////////////////////////////////////////////////////////////////////// bool CLR_RT_Thread::IsFinalizerThread() { NATIVE_PROFILE_CLR_CORE(); return g_CLR_RT_ExecutionEngine.m_finalizerThread == this; } bool CLR_RT_Thread::CanThreadBeReused() { NATIVE_PROFILE_CLR_CORE(); return (m_flags & CLR_RT_Thread::TH_F_System) && (m_status == CLR_RT_Thread::TH_S_Terminated || m_status == CLR_RT_Thread::TH_S_Unstarted ); } HRESULT CLR_RT_Thread::PushThreadProcDelegate( CLR_RT_HeapBlock_Delegate* pDelegate ) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_MethodDef_Instance inst; #if defined(NANOCLR_APPDOMAINS) CLR_RT_AppDomain* appDomainSav = g_CLR_RT_ExecutionEngine.SetCurrentAppDomain( pDelegate->m_appDomain ); #endif if(pDelegate == NULL || pDelegate->DataType() != DATATYPE_DELEGATE_HEAD || inst.InitializeFromIndex( pDelegate->DelegateFtn() ) == false) { NANOCLR_SET_AND_LEAVE(CLR_E_WRONG_TYPE); } #if defined(NANOCLR_APPDOMAINS) if(!pDelegate->m_appDomain->IsLoaded()) { if(!IsFinalizerThread()) { NANOCLR_SET_AND_LEAVE(CLR_E_APPDOMAIN_EXITED); } m_flags |= CLR_RT_Thread::TH_F_ContainsDoomedAppDomain; } #endif this->m_dlg = pDelegate; this->m_status = TH_S_Ready; NANOCLR_CHECK_HRESULT(CLR_RT_StackFrame::Push( this, inst, inst.m_target->numArgs )); if((inst.m_target->flags & CLR_RECORD_METHODDEF::MD_Static) == 0) { CLR_RT_StackFrame* stackTop = this->CurrentFrame(); stackTop->m_arguments[ 0 ].Assign( pDelegate->m_object ); } g_CLR_RT_ExecutionEngine.PutInProperList( this ); NANOCLR_CLEANUP(); #if defined(NANOCLR_APPDOMAINS) g_CLR_RT_ExecutionEngine.SetCurrentAppDomain( appDomainSav ); #endif NANOCLR_CLEANUP_END(); } HRESULT CLR_RT_Thread::CreateInstance( int pid, int priority, CLR_RT_Thread*& th, CLR_UINT32 flags ) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_SubThread* sth; //--// th = EVENTCACHE_EXTRACT_NODE(g_CLR_RT_EventCache,CLR_RT_Thread,DATATYPE_THREAD); CHECK_ALLOCATION(th); { CLR_RT_ProtectFromGC gc( (void**)&th, CLR_RT_Thread::ProtectFromGCCallback ); th->Initialize(); th->m_pid = pid; // int m_pid; th->m_status = TH_S_Unstarted; // CLR_UINT32 m_status; th->m_flags = flags; // CLR_UINT32 m_flags; th->m_executionCounter = 0; // int m_executionCounter; th->m_timeQuantumExpired = false; // bool m_timeQuantumExpired; // th->m_dlg = NULL; // CLR_RT_HeapBlock_Delegate* m_dlg; th->m_currentException .SetObjectReference( NULL ); // CLR_RT_HeapBlock m_currentException; // UnwindStack m_nestedExceptions[c_MaxStackUnwindDepth]; th->m_nestedExceptionsPos = 0; // int m_nestedExceptionsPos; // // //--// // th->m_terminationCallback = NULL; // ThreadTerminationCallback m_terminationCallback; th->m_terminationParameter = NULL; // void* m_terminationParameter; // th->m_waitForEvents = 0; // CLR_UINT32 m_waitForEvents; th->m_waitForEvents_Timeout = TIMEOUT_INFINITE; // CLR_INT64 m_waitForEvents_Timeout; th->m_waitForEvents_IdleTimeWorkItem = TIMEOUT_ZERO; // CLR_INT64 m_waitForEvents_IdleTimeWorkItem; // th->m_locks .DblLinkedList_Initialize(); // CLR_RT_DblLinkedList m_locks; th->m_lockRequestsCount = 0; // CLR_UINT32 m_lockRequestsCount; th->m_waitForObject = NULL; // th->m_stackFrames .DblLinkedList_Initialize(); // CLR_RT_DblLinkedList m_stackFrames; // th->m_subThreads .DblLinkedList_Initialize(); // CLR_RT_DblLinkedList m_subThreads; // #if defined(ENABLE_NATIVE_PROFILER) th->m_fNativeProfiled = false; #endif #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) th->m_scratchPad = -1; // int m_scratchPad; th->m_fHasJMCStepper = false; // bool m_fHasJMCStepper // For normal threads created in CLR m_realThread points to the thread object. // If debugger creates managed thread for function evaluation, then m_realThread points to the thread that has focus in debugger th->m_realThread = th; // CLR_RT_Thread* m_realThread #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //--// NANOCLR_CHECK_HRESULT(CLR_RT_SubThread::CreateInstance( th, NULL, priority, sth )); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(g_CLR_RT_ExecutionEngine.m_breakpointsNum) { // // This needs to happen before the Push // g_CLR_RT_ExecutionEngine.Breakpoint_Thread_Created( th ); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) } NANOCLR_NOCLEANUP(); } HRESULT CLR_RT_Thread::CreateInstance( int pid, CLR_RT_HeapBlock_Delegate* pDelegate, int priority, CLR_RT_Thread*& th, CLR_UINT32 flags ) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); NANOCLR_CHECK_HRESULT(CreateInstance( pid, priority, th, flags )); if(pDelegate) { NANOCLR_CHECK_HRESULT(th->PushThreadProcDelegate( pDelegate )); } NANOCLR_NOCLEANUP(); } void CLR_RT_Thread::DestroyInstance() { NATIVE_PROFILE_CLR_CORE(); DetachAll(); Passivate(); //Prevent ReleaseWhenDeadEx from keeping the thread alive if(m_flags & CLR_RT_Thread::TH_F_System) { m_flags &= ~CLR_RT_Thread::TH_F_System; OnThreadTerminated(); } ReleaseWhenDeadEx(); } bool CLR_RT_Thread::ReleaseWhenDeadEx() { NATIVE_PROFILE_CLR_CORE(); //maybe separate for shutdown.... //These threads live forever?!!? if(m_flags & CLR_RT_Thread::TH_F_System) return false; if(!IsReadyForRelease()) return false; if(this == g_CLR_RT_ExecutionEngine.m_finalizerThread) g_CLR_RT_ExecutionEngine.m_finalizerThread = NULL; if(this == g_CLR_RT_ExecutionEngine.m_interruptThread) g_CLR_RT_ExecutionEngine.m_interruptThread = NULL; if(this == g_CLR_RT_ExecutionEngine.m_timerThread ) g_CLR_RT_ExecutionEngine.m_timerThread = NULL; if(this == g_CLR_RT_ExecutionEngine.m_cctorThread ) g_CLR_RT_ExecutionEngine.m_cctorThread = NULL; return ReleaseWhenDead(); } //--// void CLR_RT_Thread::ProtectFromGCCallback( void* state ) { NATIVE_PROFILE_CLR_CORE(); CLR_RT_Thread* th = (CLR_RT_Thread*)state; g_CLR_RT_GarbageCollector.Thread_Mark( th ); } //--// HRESULT CLR_RT_Thread::Suspend() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); if((m_flags & CLR_RT_Thread::TH_F_Suspended) == 0 && m_status != CLR_RT_Thread::TH_S_Terminated) { m_flags |= CLR_RT_Thread::TH_F_Suspended; g_CLR_RT_ExecutionEngine.PutInProperList( this ); } NANOCLR_NOCLEANUP_NOLABEL(); } HRESULT CLR_RT_Thread::Resume() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); if((m_flags & CLR_RT_Thread::TH_F_Suspended) != 0 && m_status != CLR_RT_Thread::TH_S_Terminated) { m_flags &= ~CLR_RT_Thread::TH_F_Suspended; g_CLR_RT_ExecutionEngine.PutInProperList( this ); } NANOCLR_NOCLEANUP_NOLABEL(); } HRESULT CLR_RT_Thread::Terminate() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); m_status = CLR_RT_Thread::TH_S_Terminated; //An exception is needed to ensure that StackFrame::Pop does not copy uninitialized data //to callers evaluation stacks. This would likely be harmless, as the entire thread is about to be killed //However, this is simply a safeguard to prevent possible problems if it ever happens that //between the start and end of killing the thread, a GC gets run. (void)Library_corlib_native_System_Exception::CreateInstance( m_currentException, g_CLR_RT_WellKnownTypes.m_ThreadAbortException, S_OK, CurrentFrame() ); g_CLR_RT_ExecutionEngine.PutInProperList( this ); NANOCLR_NOCLEANUP_NOLABEL(); } HRESULT CLR_RT_Thread::Abort() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); // // Only abort a non-terminated thread... // if(m_status != CLR_RT_Thread::TH_S_Terminated) { (void)Library_corlib_native_System_Exception::CreateInstance( m_currentException, g_CLR_RT_WellKnownTypes.m_ThreadAbortException, S_OK, CurrentFrame() ); m_flags |= CLR_RT_Thread::TH_F_Aborted; Restart( true ); } NANOCLR_NOCLEANUP_NOLABEL(); } void CLR_RT_Thread::Restart( bool fDeleteEvent ) { NATIVE_PROFILE_CLR_CORE(); // // Wake up and queue. // m_status = CLR_RT_Thread::TH_S_Ready; g_CLR_RT_ExecutionEngine.PutInProperList( this ); if(fDeleteEvent) { m_waitForEvents = 0; m_waitForEvents_Timeout = TIMEOUT_INFINITE; } } void CLR_RT_Thread::OnThreadTerminated() { NATIVE_PROFILE_CLR_CORE(); SignalAll(); // // Release all the subthreads. // CLR_RT_SubThread::DestroyInstance( this, NULL, 0 ); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(g_CLR_RT_ExecutionEngine.m_breakpointsNum) { g_CLR_RT_ExecutionEngine.Breakpoint_Thread_Terminated( this ); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) } void CLR_RT_Thread::Passivate() { NATIVE_PROFILE_CLR_CORE(); m_flags &= ~(CLR_RT_Thread::TH_F_Suspended | CLR_RT_Thread::TH_F_ContainsDoomedAppDomain | CLR_RT_Thread::TH_F_Aborted); g_CLR_RT_ExecutionEngine.m_threadsZombie.LinkAtFront( this ); m_waitForEvents = 0; m_waitForEvents_Timeout = TIMEOUT_INFINITE; //--// if(m_waitForObject != NULL) { g_CLR_RT_EventCache.Append_Node( m_waitForObject ); m_waitForObject = NULL; } //--// if((m_flags & CLR_RT_Thread::TH_F_System) == 0) { m_status = CLR_RT_Thread::TH_S_Terminated; OnThreadTerminated(); } else { m_status = CLR_RT_Thread::TH_S_Unstarted; } m_currentException.SetObjectReference( NULL ); // Reset exception flag. // // If the thread is associated with a timer, advance the state of the timer. // if(m_terminationCallback) { ThreadTerminationCallback terminationCallback = m_terminationCallback; m_terminationCallback = NULL; terminationCallback( m_terminationParameter ); } if(m_status == CLR_RT_Thread::TH_S_Terminated || m_status == CLR_RT_Thread::TH_S_Unstarted) { //This is used by Static constructor thread. m_dlg = NULL; } ReleaseWhenDeadEx(); } bool CLR_RT_Thread::CouldBeActivated() { NATIVE_PROFILE_CLR_CORE(); if(m_waitForEvents_Timeout != TIMEOUT_INFINITE) return true; if(m_waitForEvents ) return true; return false; } void CLR_RT_Thread::RecoverFromGC() { NATIVE_PROFILE_CLR_CORE(); CheckAll(); } void CLR_RT_Thread::Relocate() { NATIVE_PROFILE_CLR_CORE(); CLR_RT_GarbageCollector::Heap_Relocate( (void**)&m_dlg ); m_currentException.Relocate__HeapBlock(); for(int i=0; i<m_nestedExceptionsPos; i++) { UnwindStack& us = m_nestedExceptions[ i ]; CLR_RT_GarbageCollector::Heap_Relocate( (void**)&us.m_stack ); CLR_RT_GarbageCollector::Heap_Relocate( (void**)&us.m_handlerStack ); CLR_RT_GarbageCollector::Heap_Relocate( (void**)&us.m_exception ); CLR_RT_GarbageCollector::Heap_Relocate( (void**)&us.m_ip ); CLR_RT_GarbageCollector::Heap_Relocate( (void**)&us.m_currentBlockStart ); CLR_RT_GarbageCollector::Heap_Relocate( (void**)&us.m_currentBlockEnd ); CLR_RT_GarbageCollector::Heap_Relocate( (void**)&us.m_handlerBlockStart ); CLR_RT_GarbageCollector::Heap_Relocate( (void**)&us.m_handlerBlockEnd ); } } //--// #if defined(NANOCLR_TRACE_CALLS) void CLR_RT_Thread::DumpStack() { NATIVE_PROFILE_CLR_CORE(); const char* szStatus; switch(m_status) { case TH_S_Ready : szStatus = "Ready" ; break; case TH_S_Waiting : szStatus = "Waiting" ; break; case TH_S_Terminated: szStatus = "Terminated"; break; default : szStatus = "" ; break; } CLR_Debug::Printf( "Thread: %d %d %s %s\r\n", m_pid, GetThreadPriority(), szStatus, (m_flags & CLR_RT_Thread::TH_F_Suspended) ? "Suspended" : "" ); NANOCLR_FOREACH_NODE_BACKWARD(CLR_RT_StackFrame,stack,m_stackFrames) { CLR_Debug::Printf( " " ); CLR_RT_DUMP::METHOD( stack->m_call ); CLR_Debug::Printf( " [IP: %04x]\r\n", (stack->m_IP - stack->m_IPstart) ); } NANOCLR_FOREACH_NODE_BACKWARD_END(); } #endif //--// void CLR_RT_Thread::ProcessException_FilterPseudoFrameCopyVars(CLR_RT_StackFrame* to, CLR_RT_StackFrame* from) { NATIVE_PROFILE_CLR_CORE(); CLR_UINT8 numArgs = from->m_call.m_target->numArgs; if(numArgs) { memcpy( to->m_arguments, from->m_arguments, sizeof(CLR_RT_HeapBlock) * numArgs ); } if(from->m_call.m_target->numLocals) { memcpy( to->m_locals, from->m_locals, sizeof(CLR_RT_HeapBlock) * from->m_call.m_target->numLocals ); } } HRESULT CLR_RT_Thread::ProcessException_EndFilter() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_StackFrame* stack = CurrentFrame(); CLR_INT32 choice = stack->PopValue().NumericByRef().s4; UnwindStack& us = m_nestedExceptions[ m_nestedExceptionsPos - 1 ]; ProcessException_FilterPseudoFrameCopyVars(us.m_handlerStack, stack); //Clear the stack variable so Pop doesn't remove us from the UnwindStack. us.m_stack = NULL; #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //We don't want to send any breakpoints until after we set the IP appropriately bool fBreakpointsDisabledSav = CLR_EE_DBG_IS(BreakpointsDisabled); CLR_EE_DBG_SET(BreakpointsDisabled); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) stack->Pop(); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(!fBreakpointsDisabledSav) { CLR_EE_DBG_CLR(BreakpointsDisabled); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(choice == 1) { //The filter signaled that it will handle this exception. Update the phase state us.SetPhase(UnwindStack::p_2_RunningFinallys_0); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) g_CLR_RT_ExecutionEngine.Breakpoint_Exception(us.m_handlerStack, CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_HANDLER_FOUND, us.m_handlerBlockStart); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) } else { //Store the IP so Phase1/FindEhBlock knows to start looking from the point of the filter we were executing. us.m_ip = us.m_currentBlockStart; } //Signal that this is a continuation of processing for the handler on top of the unwind stack. us.m_flags |= UnwindStack::c_ContinueExceptionHandler; #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //We must stop if we sent out a Catch Handler found message. if(CLR_EE_DBG_IS( Stopped )) { //If the debugger stopped because of the messages we sent, then we should break out of Execute_IL, drop down, //and wait for the debugger to continue. m_currentException.SetObjectReference(us.m_exception); NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) (void)ProcessException(); // Swap results around. ProcessException must return a success code in Thread::Execute and set m_currentException to continue processing. // Execute_IL must get a FAILED hr in order to break outside of the execution loop. if(m_currentException.Dereference() == NULL) { //Return S_OK because exception handling is complete or handling is in-flight and needs to execute IL to continue. NANOCLR_SET_AND_LEAVE(S_OK); } else { //Return PROCESS_EXCEPTION to break out of the IL loop to rerun ProcessException and/or abort from an unhandled exception NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); } NANOCLR_NOCLEANUP(); } HRESULT CLR_RT_Thread::ProcessException_EndFinally() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_StackFrame* stack = CurrentFrame(); UnwindStack& us = m_nestedExceptions[ m_nestedExceptionsPos - 1 ]; if(us.m_ip) { CLR_PMETADATA ipLeave = us.m_ip; CLR_RT_ExceptionHandler eh; if(FindEhBlock( stack, stack->m_IP-1, ipLeave, eh, true )) { us.m_stack = stack; us.m_exception = NULL; us.m_ip = ipLeave; us.m_currentBlockStart = eh.m_handlerStart; us.m_currentBlockEnd = eh.m_handlerEnd; //Leave is not valid to leave a finally block, and is the only thing that leaves m_ip set when executing IL. //Therefore if we're here then we are not interfering with an unhandled exception and flags can be safely set. us.SetPhase( UnwindStack::p_4_NormalCleanup ); stack->m_IP = eh.m_handlerStart ; } else { //We're truely done with finally's for now. Pop off the handler m_nestedExceptionsPos--; stack->m_IP = ipLeave; } #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(stack->m_flags & CLR_RT_StackFrame::c_HasBreakpoint) { g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Step( stack, stack->m_IP ); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) NANOCLR_SET_AND_LEAVE(S_OK); } else if(us.m_exception) { //This finally block was executed because an exception was thrown inside its protected block. //Signal that this is a continuation of an already existing EH process. us.m_flags |= UnwindStack::c_ContinueExceptionHandler; (void)ProcessException(); //Similar to EndFilter, we need to swap the return codes around. Thread::Execute needs a success code or the thread will be aborted. //ExecuteIL needs a failure code or we'll continue to execute IL when we possibly shouldn't. if (m_currentException.Dereference() == NULL) { //Return S_OK because exception handling is complete or handling is in-flight and needs to execute IL to continue. NANOCLR_SET_AND_LEAVE(S_OK); } else { //Return PROCESS_EXCEPTION to break out of the IL loop to rerun ProcessException and/or abort from an unhandled exception NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); } } NANOCLR_NOCLEANUP(); } HRESULT CLR_RT_Thread::ProcessException_Phase1() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); // Load the UnwindStack entry to process, as created/loaded by ProcessException UnwindStack& us = m_nestedExceptions[ m_nestedExceptionsPos - 1 ]; CLR_RT_ExceptionHandler eh; // If we were executing a filter that returned false, there's not much point checking the stack frames above the point of the filter. // Try to resume from the frame of the last filter executed. CLR_RT_StackFrame* stack = us.m_handlerStack; #ifndef CLR_NO_IL_INLINE CLR_RT_InlineFrame tmpInline; tmpInline.m_IP = NULL; #endif // If this is the first pass through _Phase1 then start at the top. if(!stack) { stack = CurrentFrame(); } //Search for a willing catch handler. while(stack->Caller() != NULL) { #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(g_CLR_RT_ExecutionEngine.m_breakpointsNum && us.GetPhase() < UnwindStack::p_1_SearchingForHandler_2_SentUsersChance && stack->m_IP) { //We have a debugger attached and we need to send some messages before we start searching. //These messages should only get sent when the search reaches managed code. Stack::Push sets m_IP to NULL for native code, //so therefore we need IP to be non-NULL us.m_handlerStack = stack; if(us.GetPhase() < UnwindStack::p_1_SearchingForHandler_1_SentFirstChance) { g_CLR_RT_ExecutionEngine.Breakpoint_Exception( stack, CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_FIRST_CHANCE, NULL ); us.SetPhase(UnwindStack::p_1_SearchingForHandler_1_SentFirstChance); //Break out here, because of synchronization issues (false positives) with JMC checking. if(CLR_EE_DBG_IS( Stopped )) { goto ContinueAndExit; } } //In order to send the User's first chance message, we have to know that we're in JMC //Do we have thread synchronization issues here? The debugger is sending out 3 Not My Code messages for a function, //presumably the one on the top of the stack, but when we execute this, we're reading true. if(stack->m_call.DebuggingInfo().IsJMC()) { g_CLR_RT_ExecutionEngine.Breakpoint_Exception( stack, CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_USERS_CHANCE, NULL ); us.SetPhase( UnwindStack::p_1_SearchingForHandler_2_SentUsersChance ); if(CLR_EE_DBG_IS(Stopped)) { goto ContinueAndExit; } } } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(stack->m_call.m_target->flags & CLR_RECORD_METHODDEF::MD_HasExceptionHandlers) { CLR_PMETADATA ip; if (us.m_ip) { ip = us.m_ip; //Use the IP set by endfilter us.m_ip = NULL; //Reset to prevent catch block & PopEH issues via 'leave' or 'endfinally' } else { ip = stack->m_IP; //Normal case: use the IP where the exception was thrown. } if(ip) // No IP? Either out of memory during allocation of stack frame or native method. { if(FindEhBlock( stack, ip, NULL, eh, false )) { //There are two cases here: //1. We found a catch block... in this case, we want to break out and go to phase 2. //2. We found a filter... in this case, we want to duplicate the stack and execute the filter. //Store the handler block address and stack frame. //It's needed in Phase2 for when finally's are finished and we execute the catch handler us.m_handlerBlockStart = eh.m_handlerStart; us.m_handlerBlockEnd = eh.m_handlerEnd; us.m_handlerStack = stack; #ifndef CLR_NO_IL_INLINE if(tmpInline.m_IP) { us.m_flags |= UnwindStack::c_MagicCatchForInline; } #endif if (eh.IsFilter()) { CLR_RT_StackFrame* newStack = NULL; //Store the IP range that we're currently executing so leave/PopEH doesn't accidentally pop the filter off. us.m_currentBlockStart = eh.m_userFilterStart; us.m_currentBlockEnd = eh.m_handlerStart; //Create a pseudo-frame at the top of the stack so the filter can call other functions. CLR_UINT8 numArgs = stack->m_call.m_target->numArgs; #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //We don't want to send any breakpoints until after we set the IP appropriately bool fBreakpointsDisabledSav = CLR_EE_DBG_IS(BreakpointsDisabled); CLR_EE_DBG_SET(BreakpointsDisabled); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) hr = CLR_RT_StackFrame::Push( stack->m_owningThread, stack->m_call, numArgs ); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(!fBreakpointsDisabledSav) { CLR_EE_DBG_CLR(BreakpointsDisabled); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(FAILED(hr)) { //We probably ran out of memory. In either case, don't run this handler. //Set the IP so we'll try the next catch block. us.m_ip = us.m_currentBlockStart; continue; } //stack is the original filter stack frame; newStack is the new pseudoframe newStack = CurrentFrame(); newStack->m_flags |= CLR_RT_StackFrame::c_PseudoStackFrameForFilter; us.m_stack = newStack; //Copy local variables and arguments so the filter has access to them. if(numArgs) { memcpy( newStack->m_arguments, stack->m_arguments, sizeof(CLR_RT_HeapBlock) * numArgs ); } if (stack->m_call.m_target->numLocals) { memcpy( newStack->m_locals, stack->m_locals, sizeof(CLR_RT_HeapBlock) * stack->m_call.m_target->numLocals ); } newStack->PushValueAndAssign( m_currentException ); //Set the ip to the handler newStack->m_IP = eh.m_userFilterStart; //We are willing to execute IL again so clear the m_currentException flag. m_currentException.SetObjectReference( NULL ); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Push( newStack, CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_STEP_INTERCEPT ); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //Return a success value to break out of ProcessException and to signal that execution of IL can continue. NANOCLR_SET_AND_LEAVE(S_OK); } else { //We found a normal Catch or CatchAll block. We are all set to proceed onto the Unwinding phase. //Note that we found a catch handler so we don't look for it again for this exception. us.SetPhase( UnwindStack::p_2_RunningFinallys_0 ); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(g_CLR_RT_ExecutionEngine.m_breakpointsNum) { g_CLR_RT_ExecutionEngine.Breakpoint_Exception( stack, CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_HANDLER_FOUND, eh.m_handlerStart ); if(CLR_EE_DBG_IS(Stopped)) { goto ContinueAndExit; } } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //We want to continue running EH "goo" code so leave m_currentException set and return PROCESS_EXCEPTION NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); } } } } //We didn't find a catch block at this level... //Check to see if we trickled up to a pseudoStack frame that we created to execute a handler //Both of these shouldn't be set at once because of the two-pass handling mechanism. if (stack->m_flags & CLR_RT_StackFrame::c_AppDomainTransition) { us.m_handlerStack = NULL; us.SetPhase(UnwindStack::p_2_RunningFinallys_0); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(g_CLR_RT_ExecutionEngine.m_breakpointsNum) { //Send the IP offset -1 for a catch handler in the case of an appdomain transition to mimic the desktop. g_CLR_RT_ExecutionEngine.Breakpoint_Exception( stack, CLR_DBG_Commands::Debugging_Execution_BreakpointDef::c_DEPTH_EXCEPTION_HANDLER_FOUND, stack->m_IPstart - 1 ); if(CLR_EE_DBG_IS(Stopped)) { goto ContinueAndExit; } } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); } if (stack->m_flags & CLR_RT_StackFrame::c_PseudoStackFrameForFilter) { us.m_handlerStack = NULL; us.SetPhase( UnwindStack::p_2_RunningFinallys_0 ); NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); } #ifndef CLR_NO_IL_INLINE if(stack->m_inlineFrame != NULL && tmpInline.m_IP == NULL) { stack->SaveStack(tmpInline); stack->RestoreFromInlineStack(); } else { if(tmpInline.m_IP) { stack->RestoreStack(tmpInline); tmpInline.m_IP = NULL; } #else { #endif stack = stack->Caller(); } } us.m_handlerStack = NULL; us.SetPhase(UnwindStack::p_2_RunningFinallys_0); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(g_CLR_RT_ExecutionEngine.m_breakpointsNum) { g_CLR_RT_ExecutionEngine.Breakpoint_Exception_Uncaught( this ); if(CLR_EE_DBG_IS(Stopped)) { goto ContinueAndExit; } } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //We want to continue running EH "goo" code so leave m_currentException set and return PROCESS_EXCEPTION NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) ContinueAndExit: #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //There are multiple cases where we want to break out of this function, send debug messages, and then resume exactly where we were. //All of those cases jump to here. //However, there are cases where we may be stopped but we don't want to set this flag (i.e. pushing on a filter and completing a stepper) //where we do not want to set this flag, so it cannot be in nanoCLR_Cleanup. us.m_flags |= UnwindStack::c_ContinueExceptionHandler; NANOCLR_SET_AND_LEAVE(S_OK); NANOCLR_CLEANUP(); #ifndef CLR_NO_IL_INLINE if(tmpInline.m_IP) { stack->RestoreStack(tmpInline); } #endif NANOCLR_CLEANUP_END(); } HRESULT CLR_RT_Thread::ProcessException_Phase2() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); /* * Start running through the stack frames, running all finally handlers and popping them off until * we hit our target catch handler, if any. */ UnwindStack& us = m_nestedExceptions[ m_nestedExceptionsPos - 1 ]; CLR_RT_StackFrame* iterStack = CurrentFrame(); CLR_RT_ExceptionHandler eh; //Unwind the stack, running finally's as we go while (iterStack->Caller() != NULL) { #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if (g_CLR_RT_ExecutionEngine.m_breakpointsNum && iterStack == us.m_handlerStack && (us.m_flags & UnwindStack::c_MagicCatchForInteceptedException) != 0) { //We've reached the frame we want to "handle" this exception. However, since the handler doesn't really exist, we want to remove the UnwindStack entry. m_nestedExceptionsPos--; iterStack->ResetStack(); //We are willing to execute IL again so clear the m_currentException flag. m_currentException.SetObjectReference( NULL ); //CPDE better reset the IP, or there are going to be issues. iterStack->m_flags |= CLR_RT_StackFrame::c_InvalidIP; //Send the message to the debugger. g_CLR_RT_ExecutionEngine.Breakpoint_Exception_Intercepted( iterStack ); //Return a success value to break out of ProcessException and to signal that execution of IL can continue. NANOCLR_SET_AND_LEAVE(S_OK); } else #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(iterStack->m_call.m_target->flags & CLR_RECORD_METHODDEF::MD_HasExceptionHandlers) { if(iterStack->m_IP) // No IP? Either out of memory during allocation of iterStack frame or native method. { //handlerBlockStart is used to not execute finally's who's protected blocks contain the handler itself. //NULL is used when we're not in the handler stack frame to make it work in the case of recursive functions with filtered handlers. if(FindEhBlock( iterStack, iterStack->m_IP, (us.m_handlerStack == iterStack)? us.m_handlerBlockStart : NULL, eh, true )) { //We have a finally block to process us.m_stack = iterStack; us.m_ip = NULL; us.m_currentBlockStart = eh.m_handlerStart; us.m_currentBlockEnd = eh.m_handlerEnd; us.SetPhase(UnwindStack::p_2_RunningFinallys_0); m_currentException.SetObjectReference( NULL ); // Reset exception flag. iterStack->ResetStack(); iterStack->m_IP = eh.m_handlerStart; iterStack->m_flags &= ~CLR_RT_StackFrame::c_InvalidIP; #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) #ifndef CLR_NO_IL_INLINE if(iterStack->m_inlineFrame == NULL) #endif { g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Pop( iterStack, true ); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) NANOCLR_SET_AND_LEAVE(S_OK); } if (iterStack == us.m_handlerStack) { #ifndef CLR_NO_IL_INLINE if(iterStack->m_inlineFrame == NULL || 0 == (us.m_flags & UnwindStack::c_MagicCatchForInline)) #endif { //We've popped off all stack frames above the target. //Now we should run the exception handler. //Store the range of the block and the stack frame we're executing for PopEH us.m_currentBlockStart = us.m_handlerBlockStart; us.m_currentBlockEnd = us.m_handlerBlockEnd; us.m_stack = us.m_handlerStack; us.SetPhase( UnwindStack::p_3_RunningHandler ); //Set the IP and push the exception object on the stack. iterStack->m_IP = us.m_handlerBlockStart; iterStack->m_flags &= ~CLR_RT_StackFrame::c_InvalidIP; iterStack->ResetStack(); iterStack->PushValue().SetObjectReference( us.m_exception ); //We are willing to execute IL again so clear the m_currentException flag. m_currentException.SetObjectReference( NULL ); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) #ifndef CLR_NO_IL_INLINE if(iterStack->m_inlineFrame == NULL) #endif { g_CLR_RT_ExecutionEngine.Breakpoint_StackFrame_Pop( iterStack, true ); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //Return a success value to break out of ProcessException and to signal that execution of IL can continue. NANOCLR_SET_AND_LEAVE(S_OK); } } } } //We didn't find a finally block at this level... //Check to see if we trickled up to a pseudoiterStack frame that we created to execute a filter handler: if (iterStack->m_flags & CLR_RT_StackFrame::c_PseudoStackFrameForFilter) { //An exception was thrown while executing a filter block. //The CLR should swallow the current exception, perform some filter-cleanup, act as if the filter returned false and //continue looking for a handler for the old exception m_nestedExceptionsPos--; UnwindStack& us = m_nestedExceptions[ m_nestedExceptionsPos - 1 ]; //Since there are no applicable handlers for this IP inside this filter block, and all finally's nested below the //filter have executed, we should pop off our pseudoframe and try to find another catch block. //Copy the arguments and locals back to the original stack frame. ProcessException_FilterPseudoFrameCopyVars( us.m_handlerStack, iterStack ); //Set IP so we can resume looking for the next filter. us.m_ip = us.m_currentBlockStart; us.m_stack = NULL; //Prevent Pop from taking this handler off the stack. #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //We don't want to send any breakpoints until after we set the IP appropriately bool fBreakpointsDisabledSav = CLR_EE_DBG_IS(BreakpointsDisabled); CLR_EE_DBG_SET(BreakpointsDisabled); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) iterStack->Pop(); //No finally's for the current ip in this method, pop to the next. #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(!fBreakpointsDisabledSav) { CLR_EE_DBG_CLR(BreakpointsDisabled); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) m_currentException.SetObjectReference( us.m_exception ); //Drop current exception, use old one. //Set the continue flag, and leave with S_OK to loop around and get Phase1 called again via ProcessException us.m_flags |= UnwindStack::c_ContinueExceptionHandler; //We are not ready to execute IL yet so do NOT clear m_currentException flag. //There still remains hope for this thread so return S_OK so ProcessException can get called again via Thread::Execute NANOCLR_SET_AND_LEAVE(S_OK); } #if defined(NANOCLR_APPDOMAINS) if(iterStack->m_flags & CLR_RT_StackFrame::c_AppDomainTransition) { //If we hit an AppDomain transition and haven't handled the exception, then a special case occurs. //Exception handling stops at this point and the whole process needs to start over in the caller's AppDomain. //We need to pop the handler off the unwind stack, pop the current stack frame, and then proceed to Phase1. m_nestedExceptionsPos--; //Take off the pseudo-handler #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) bool fBreakpointsDisabledSav = CLR_EE_DBG_IS(BreakpointsDisabled); CLR_EE_DBG_SET(BreakpointsDisabled); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) #ifndef CLR_NO_IL_INLINE if(iterStack->m_inlineFrame) { iterStack->PopInline(); } else #endif { iterStack->Pop(); //No finally's for the current ip in this method, pop to the next. } #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(!fBreakpointsDisabledSav) { CLR_EE_DBG_CLR(BreakpointsDisabled); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //We are not ready to execute IL yet so do NOT clear m_currentException flag. //There still remains hope for this thread so return S_OK so ProcessException can get called again via Thread::Execute NANOCLR_SET_AND_LEAVE(S_OK); } #endif us.m_stack = NULL; //Don't pop off the handler when we pop this stack frame #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) //We don't want to send any breakpoints until after we set the IP appropriately bool fBreakpointsDisabledSav = CLR_EE_DBG_IS(BreakpointsDisabled); CLR_EE_DBG_SET(BreakpointsDisabled); #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) #ifndef CLR_NO_IL_INLINE if(iterStack->m_inlineFrame) { iterStack->PopInline(); } else #endif { iterStack->Pop(); //No finally's for the current ip in this method, pop to the next. } iterStack = CurrentFrame(); #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) if(!fBreakpointsDisabledSav) { CLR_EE_DBG_CLR(BreakpointsDisabled); } #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) } //If we reached this point, we've unwound the entire thread and have an unhandled exception. m_nestedExceptionsPos = 0; //We have an unhandled exception, we might as well clean the unwind stack. //At this point, no hope remains. //m_currentException is still set, but we return PROCESS_EXCEPTION signalling that there is no hope for the thread, //which causes Thread::Execute to terminate it. #if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) #if !defined(BUILD_RTM) //special case thread abort exception if((this->m_flags & CLR_RT_Thread::TH_F_Aborted) == 0) { CLR_Debug::Printf(" Uncaught exception \r\n" ); //Perhaps some stronger notification is needed. Consider CLR 2.0's fail-fast work //We could kill the application, and perhaps even store relevant data to dump to the user //when they connect to the PC. Save the state so the debug API for the uncaught exception could be //retrieved? } #endif //!BUILD_RTM #endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING) NANOCLR_SET_AND_LEAVE(CLR_E_PROCESS_EXCEPTION); NANOCLR_NOCLEANUP(); } HRESULT CLR_RT_Thread::ProcessException() { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_StackFrame* stack = CurrentFrame(); UnwindStack* us = NULL; // If the exception was thrown in the middle of an IL instruction, // back up the pointer to point to the executing instruction, not the next one. // Not an assert because the exception can be thrown by a native method. if(stack->m_flags & CLR_RT_StackFrame::c_ExecutingIL) { stack->m_IP--; stack->m_flags &= ~CLR_RT_StackFrame::c_ExecutingIL; stack->m_flags |= CLR_RT_StackFrame::c_InvalidIP; } // If we are supposed to continue with the old exception handler, then pull the state from it rather than create a new exception. if (m_nestedExceptionsPos) { us = &m_nestedExceptions[ m_nestedExceptionsPos - 1 ]; if (us->m_flags & UnwindStack::c_ContinueExceptionHandler) { //Reset the flag so we don't get false positives from new exceptions us->m_flags &= ~UnwindStack::c_ContinueExceptionHandler; m_currentException.SetObjectReference( us->m_exception ); } else { //Signal that we need a new handler pushed on the stack. us = NULL; } } if (us == NULL) { //Push a new handler on the unwind stack that will last until its handler gets executed or //something out-of-band forces the stack frame to get popped. us = PushEH(); //decent failure case is currently not implemented //a. Clearing the unwind stack and throwing a new exception is just asking for undefined behavior if this exception is caught //and the IP in stack frames somewhere below are in a finally due to an exception that hasn't yet ran a catch block and //endfinally gets executed. Execution would continue, thinking that nothing was wrong... a guranteed way to create hard-to-find bugs. //b. We could treat it as an unhandled exception, which would terminate the thread. It would be annoying, but it wouldn't lead to //unexpected code execution leading to potentially more exceptions. //c. We could forcibly pop stack frames until there is room on the unwind stack and then throw a stack overflow exception. //It gives a program a chance to recover, especially for 'always-on' type devices that are inconvenient for the user to perform a cold-boot. //At any restartable point in the program, there could be a try { } catch-all { } block inside a loop, causing the app to immediately restart //after an error that would normally terminate the thread. //A similar setup would be needed for leave, involving goto Execute_Restart to compensate for possible stack frame changes. Perhaps it could be //implemented directly in PushEh to reduce common code. us->m_exception = m_currentException.Dereference(); us->m_stack = stack; us->m_flags = UnwindStack::p_1_SearchingForHandler_0; } if (us->GetPhase() <= UnwindStack::p_1_SearchingForHandler_2_SentUsersChance) { NANOCLR_EXIT_ON_SUCCESS(ProcessException_Phase1()); // Leave if we're executing a filter. } NANOCLR_SET_AND_LEAVE(ProcessException_Phase2()); //Leave if we're executing a finally or the catch block, or have an unhandled exception NANOCLR_NOCLEANUP(); }
40.278213
188
0.624847
[ "object" ]
4fe5df238910e1740bba565536fb3d0d39d03c04
13,550
cpp
C++
perf_test/sparse/KokkosSparse_spmv_struct.cpp
kuberry/kokkos-kernels
30be76be52f1d62f9b5798984674ad46a59e5070
[ "BSD-3-Clause" ]
null
null
null
perf_test/sparse/KokkosSparse_spmv_struct.cpp
kuberry/kokkos-kernels
30be76be52f1d62f9b5798984674ad46a59e5070
[ "BSD-3-Clause" ]
null
null
null
perf_test/sparse/KokkosSparse_spmv_struct.cpp
kuberry/kokkos-kernels
30be76be52f1d62f9b5798984674ad46a59e5070
[ "BSD-3-Clause" ]
null
null
null
/* //@HEADER // ************************************************************************ // // KokkosKernels 0.9: Linear Algebra and Graph Kernels // Copyright 2017 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Siva Rajamanickam (srajama@sandia.gov) // // ************************************************************************ //@HEADER */ #include <cstdio> #include <ctime> #include <cstring> #include <cstdlib> #include <limits> #include <limits.h> #include <cmath> #include <unordered_map> #include <Kokkos_Core.hpp> #include <KokkosSparse_spmv.hpp> #include <KokkosKernels_Test_Structured_Matrix.hpp> #include <KokkosSparse_spmv_struct_impl.hpp> #include <KokkosSparse_spmv_impl.hpp> enum {STRUCT, UNSTR}; enum {AUTO, DYNAMIC, STATIC}; #if defined(KOKKOSKERNELS_INST_ORDINAL_INT) typedef int default_lno_t; #elif defined(KOKKOSKERNELS_INST_ORDINAL_INT64_T) typedef int64_t default_lno_t; #else #error "Expect int and/or int64_t to be enabled as ORDINAL (lno_t) types" #endif //Prefer int as the default offset type, because cuSPARSE doesn't support size_t for rowptrs. #if defined(KOKKOSKERNELS_INST_OFFSET_INT) typedef int default_size_type; #elif defined(KOKKOSKERNELS_INST_OFFSET_SIZE_T) typedef size_t default_size_type; #else #error "Expect size_t and/or int to be enabled as OFFSET (size_type) types" #endif void print_help() { printf("SPMV_struct benchmark code written by Luc Berger-Vergiat.\n"); printf("Options:\n"); printf(" --check-errors : Determine if the result of spmv_struct is compared to serial unstructured spmv.\n"); printf(" --compare : Compare results efficiency of spmv_struct and spmv.\n"); printf(" -l [LOOP] : How many spmv to run to aggregate average time. \n"); printf(" -nx : How many nodes in x direction. \n"); printf(" -ny : How many nodes in y direction. \n"); printf(" -nz : How many nodes in z direction. \n"); printf(" -st : The stencil type used for discretization: 1 -> FD, 2 -> FE.\n"); printf(" -dim : Number of spacial dimensions used in the problem: 1, 2 or 3\n"); printf(" -ws : Worksets. \n"); printf(" -ts : Team Size. \n"); printf(" -vl : Vector length. \n"); } int main(int argc, char **argv) { typedef double Scalar; int nx = 100; int ny = 100; int nz = 100; int stencil_type = 1; int numDimensions = 2; int numVecs = 1; bool check_errors = false; bool compare = false; int loop = 100; int vl = -1; int ts = -1; int ws = -1; if(argc == 1) { print_help(); return 0; } for(int i=0;i<argc;i++) { if((strcmp(argv[i],"-nx" )==0)) {nx=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-ny" )==0)) {ny=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-nz" )==0)) {nz=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-st" )==0)) {stencil_type=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-dim")==0)) {numDimensions=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-mv" )==0)) {numVecs=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-l" )==0)) {loop=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-vl" )==0)) {vl=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-ts" )==0)) {ts=atoi(argv[++i]); continue;} if((strcmp(argv[i],"-ws" )==0)) {ws=atoi(argv[++i]); continue;} if((strcmp(argv[i],"--check-errors")==0)) {check_errors=true; continue;} if((strcmp(argv[i],"--compare")==0)) {compare=true; continue;} if((strcmp(argv[i],"--help")==0) || (strcmp(argv[i],"-h")==0)) { print_help(); return 0; } } if(vl < 0) { vl = 2; } else if(ts < 0) { ts = 256 / vl; if(ws < 0) { if(numDimensions == 1) { ws = (nx - 2 + ts - 1) / ts; } else if(numDimensions == 2) { ws = ((nx - 2)*(ny - 2) + ts - 1) / ts; } else if(numDimensions == 3) { ws = ((nx - 2)*(ny - 2)*(nz - 2) + ts - 1) / ts; } } } Kokkos::initialize(argc,argv); { typedef default_lno_t lno_t; typedef default_size_type size_type; typedef KokkosSparse::CrsMatrix<Scalar,lno_t,Kokkos::DefaultExecutionSpace,void,size_type> matrix_type; typedef typename Kokkos::View<Scalar**,Kokkos::LayoutLeft> mv_type; // typedef typename Kokkos::View<Scalar*,Kokkos::LayoutLeft,Kokkos::MemoryRandomAccess > mv_random_read_type; typedef typename mv_type::HostMirror h_mv_type; int leftBC = 1, rightBC = 1, frontBC = 1, backBC = 1, bottomBC = 1, topBC = 1; Kokkos::View<lno_t*, Kokkos::HostSpace> structure("Spmv Structure", numDimensions); Kokkos::View<lno_t*[3], Kokkos::HostSpace> mat_structure("Matrix Structure", numDimensions); if(numDimensions == 1) { structure(0) = nx; mat_structure(0, 0) = nx; } else if(numDimensions == 2) { structure(0) = nx; structure(1) = ny; mat_structure(0, 0) = nx; mat_structure(1, 0) = ny; if(leftBC == 1) { mat_structure(0, 1) = 1; } if(rightBC == 1) { mat_structure(0, 2) = 1; } if(bottomBC == 1) { mat_structure(1, 1) = 1; } if(topBC == 1) { mat_structure(1, 2) = 1; } } else if(numDimensions == 3) { structure(0) = nx; structure(1) = ny; structure(2) = nz; mat_structure(0, 0) = nx; mat_structure(1, 0) = ny; mat_structure(2, 0) = nz; if(leftBC == 1) { mat_structure(0, 1) = 1; } if(rightBC == 1) { mat_structure(0, 2) = 1; } if(frontBC == 1) { mat_structure(1, 1) = 1; } if(backBC == 1) { mat_structure(1, 2) = 1; } if(bottomBC == 1) { mat_structure(2, 1) = 1; } if(topBC == 1) { mat_structure(2, 2) = 1; } } std::string discrectization_stencil; if(stencil_type == 1) { discrectization_stencil = "FD"; } else if(stencil_type == 2) { discrectization_stencil = "FE"; } matrix_type A; if(numDimensions == 1) { A = Test::generate_structured_matrix1D<matrix_type>(mat_structure); } else if(numDimensions == 2) { A = Test::generate_structured_matrix2D<matrix_type>(discrectization_stencil, mat_structure); } else if(numDimensions == 3) { A = Test::generate_structured_matrix3D<matrix_type>(discrectization_stencil, mat_structure); } mv_type x("X", A.numCols(), numVecs); // mv_random_read_type t_x(x); mv_type y("Y", A.numRows(), numVecs); h_mv_type h_x = Kokkos::create_mirror_view(x); h_mv_type h_y = Kokkos::create_mirror_view(y); h_mv_type h_y_compare; for(int rowIdx = 0; rowIdx < A.numCols(); ++rowIdx) { for(int vecIdx = 0; vecIdx < numVecs; ++vecIdx) { h_x(rowIdx, vecIdx) = static_cast<Scalar>(1.0*(rand()%40)-20.0); h_y(rowIdx, vecIdx) = static_cast<Scalar>(1.0*(rand()%40)-20.0); } } if(check_errors) { h_y_compare = Kokkos::create_mirror(y); typename matrix_type::StaticCrsGraphType::HostMirror h_graph = Kokkos::create_mirror(A.graph); typename matrix_type::values_type::HostMirror h_values = Kokkos::create_mirror_view(A.values); // Error Check Gold Values for(int rowIdx = 0; rowIdx < A.numRows(); ++rowIdx) { int start = h_graph.row_map(rowIdx); int end = h_graph.row_map(rowIdx + 1); for(int vecIdx = 0; vecIdx < numVecs; ++vecIdx) { h_y_compare(rowIdx, vecIdx) = 0; } for(int entryIdx = start; entryIdx < end; ++entryIdx) { // Scalar tmp_val = h_graph.entries(entryIdx) + i; int idx = h_graph.entries(entryIdx); for(int vecIdx = 0; vecIdx < numVecs; ++vecIdx) { h_y_compare(rowIdx, vecIdx) += h_values(entryIdx)*h_x(idx, vecIdx); } } } } Kokkos::deep_copy(x, h_x); Kokkos::deep_copy(y, h_y); Kokkos::View<Scalar**, Kokkos::LayoutLeft, Kokkos::DefaultExecutionSpace> x1("X1", A.numCols(), numVecs); Kokkos::View<Scalar**, Kokkos::LayoutLeft, Kokkos::DefaultExecutionSpace> y1("Y1", A.numRows(), numVecs); Kokkos::deep_copy(x1, h_x); // typename KokkosSparse::CrsMatrix<Scalar,int,Kokkos::DefaultExecutionSpace,void,int>::values_type y1("Y1", A.numRows(), numVecs); { Kokkos::Profiling::pushRegion("Structured spmv test"); // Benchmark double min_time = 1.0e32; double max_time = 0.0; double ave_time = 0.0; for(int i=0;i<loop;i++) { Kokkos::Timer timer; KokkosSparse::Experimental::spmv_struct("N", stencil_type, structure, 1.0, A, x1, 1.0, y1); Kokkos::fence(); double time = timer.seconds(); ave_time += time; if(time>max_time) max_time = time; if(time<min_time) min_time = time; } // Performance Output double matrix_size = 1.0*((A.nnz()*(sizeof(Scalar) + sizeof(int)) + A.numRows()*sizeof(int)))/1024/1024; double vector_size = 2.0*A.numRows()*sizeof(Scalar)/1024/1024; double vector_readwrite = (A.nnz() + A.numCols())*sizeof(Scalar)/1024/1024; double problem_size = matrix_size+vector_size; printf("Type NNZ NumRows NumCols ProblemSize(MB) AveBandwidth(GB/s) MinBandwidth(GB/s) MaxBandwidth(GB/s) AveGFlop MinGFlop MaxGFlop aveTime(ms) maxTime(ms) minTime(ms)\n"); printf("Struct %zu %zu %zu %6.2lf ( %6.2lf %6.2lf %6.2lf ) ( %6.3lf %6.3lf %6.3lf ) ( %6.3lf %6.3lf %6.3lf )\n", (size_t) A.nnz(), (size_t) A.numRows(), (size_t) A.numCols(), problem_size, (matrix_size+vector_readwrite)/ave_time*loop/1024, (matrix_size+vector_readwrite)/max_time/1024, (matrix_size+vector_readwrite)/min_time/1024, 2.0*A.nnz()*loop/ave_time/1e9, 2.0*A.nnz()/max_time/1e9, 2.0*A.nnz()/min_time/1e9, ave_time/loop*1000, max_time*1000, min_time*1000); Kokkos::Profiling::popRegion(); } if(compare) { Kokkos::Profiling::pushRegion("Unstructured spmv test"); // Benchmark double min_time = 1.0e32; double max_time = 0.0; double ave_time = 0.0; for(int i=0;i<loop;i++) { Kokkos::Timer timer; KokkosSparse::spmv("N", 1.0, A, x1, 1.0, y1); Kokkos::fence(); double time = timer.seconds(); ave_time += time; if(time>max_time) max_time = time; if(time<min_time) min_time = time; } // Performance Output double matrix_size = 1.0*((A.nnz()*(sizeof(Scalar)+sizeof(int)) + A.numRows()*sizeof(int)))/1024/1024; double vector_size = 2.0*A.numRows()*sizeof(Scalar)/1024/1024; double vector_readwrite = (A.nnz() + A.numCols())*sizeof(Scalar)/1024/1024; double problem_size = matrix_size+vector_size; printf("Unstr %zu %zu %zu %6.2lf ( %6.2lf %6.2lf %6.2lf ) ( %6.3lf %6.3lf %6.3lf ) ( %6.3lf %6.3lf %6.3lf )\n", (size_t) A.nnz(), (size_t) A.numRows(), (size_t) A.numCols(), problem_size, (matrix_size+vector_readwrite)/ave_time*loop/1024, (matrix_size+vector_readwrite)/max_time/1024,(matrix_size+vector_readwrite)/min_time/1024, 2.0*A.nnz()*loop/ave_time/1e9, 2.0*A.nnz()/max_time/1e9, 2.0*A.nnz()/min_time/1e9, ave_time/loop*1000, max_time*1000, min_time*1000); Kokkos::Profiling::popRegion(); } if(check_errors) { // Error Check Kokkos::deep_copy(h_y, y1); Scalar error = 0; Scalar sum = 0; for(int rowIdx = 0; rowIdx < A.numRows(); ++rowIdx) { for(int vecIdx = 0; vecIdx < numVecs; ++vecIdx) { error += (h_y_compare(rowIdx, vecIdx) - h_y(rowIdx, vecIdx))*(h_y_compare(rowIdx, vecIdx) - h_y(rowIdx, vecIdx)); sum += h_y_compare(rowIdx, vecIdx)*h_y_compare(rowIdx, vecIdx); } } int num_errors = 0; double total_error = 0; double total_sum = 0; num_errors += (error/(sum==0?1:sum))>1e-5?1:0; total_error += error; total_sum += sum; if(total_error == 0) { printf("Kokkos::MultiVector Test: Passed\n"); } else { printf("Kokkos::MultiVector Test: Failed\n"); } } } Kokkos::finalize(); }
39.389535
179
0.627306
[ "vector" ]
4fe7cccbcb1ee0158f9f0875f732bae1f327c423
77,111
cpp
C++
src/actions/SoToVRML2Action.cpp
eddieh/Coin3D
1a1cd97b4dac262838a1a802bdf1803bee2920c2
[ "BSD-3-Clause" ]
null
null
null
src/actions/SoToVRML2Action.cpp
eddieh/Coin3D
1a1cd97b4dac262838a1a802bdf1803bee2920c2
[ "BSD-3-Clause" ]
null
null
null
src/actions/SoToVRML2Action.cpp
eddieh/Coin3D
1a1cd97b4dac262838a1a802bdf1803bee2920c2
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************\ * Copyright (c) Kongsberg Oil & Gas Technologies AS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \**************************************************************************/ /*! \class SoToVRML2Action SoToVRML2Action.h Inventor/actions/SoToVRML2Action.h \brief The SoToVRML2Action class builds a new scene graph, using only VRML97/VRML2 nodes. \ingroup actions This action is used for converting a scene graph of VRML1/Coin nodes to a new scene graph using only VRML97/VRML2 nodes. Due to the basic differences between VRML1/Coin and VRML2 (the latter does not really have a traversal state) the new scene graph will typically be somewhat larger. To minimize this effect the action tries to re-use nodes when possible. VRML1 nodes will be converted to its direct equivalent VRML2 node, while Coin nodes with no VRML2 equivalent are converted to IndexedFaceSet. If the DrawStyle is POINTS, all geometry will be built using PointSet; if it is LINES IndexedLineSet is used. Here's a basic usage example of this action, in the form of a complete, stand-alone program: \code #include <Inventor/SoDB.h> #include <Inventor/SoInteraction.h> #include <Inventor/SoInput.h> #include <Inventor/SoOutput.h> #include <Inventor/actions/SoWriteAction.h> #include <Inventor/actions/SoToVRML2Action.h> #include <Inventor/nodes/SoSeparator.h> #include <Inventor/VRMLnodes/SoVRMLGroup.h> int main(int argc, char *argv[]) { SoDB::init(); SoInteraction::init(); SoInput in; in.openFile(argv[1]); printf("Reading...\n"); SoSeparator *root = SoDB::readAll(&in); if (root) { root->ref(); SbString hdr = in.getHeader(); in.closeFile(); printf("Converting...\n"); SoToVRML2Action tovrml2; tovrml2.apply(root); SoVRMLGroup *newroot = tovrml2.getVRML2SceneGraph(); newroot->ref(); root->unref(); printf("Writing...\n"); SoOutput out; out.openFile("out.wrl"); out.setHeaderString("#VRML V2.0 utf8"); SoWriteAction wra(&out); wra.apply(newroot); out.closeFile(); newroot->unref(); } return 0; } \endcode Note: if VRML97 support is not present in the Coin library, this action does nothing and getVRML2SceneGraph always returns \c NULL. \sa SoToVRMLAction \since Coin 2.0 \since TGS Inventor 2.5 */ // ************************************************************************* // FIXME: SoComplexity::BOUNDING_BOX are not supported. For // DrawStyle::LINES quads are not handled correctly (will always draw // triangles). SoArray and SoMultipleCopy are not supported. // Reusing of appearance and geometry nodes is not implemented. // 20020813 kristian. // ************************************************************************* #include <Inventor/actions/SoToVRML2Action.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <cfloat> #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include <Inventor/SbBSPTree.h> #include <Inventor/SbName.h> #include <Inventor/SbViewportRegion.h> #include <Inventor/SoInput.h> #include <Inventor/SoOutput.h> #include <Inventor/SoPrimitiveVertex.h> #include <Inventor/actions/SoCallbackAction.h> #include <Inventor/actions/SoGetPrimitiveCountAction.h> #include <Inventor/actions/SoGetBoundingBoxAction.h> #include <Inventor/actions/SoSearchAction.h> #include <Inventor/actions/SoWriteAction.h> #include <Inventor/actions/SoGetMatrixAction.h> #include <Inventor/elements/SoCoordinateElement.h> #include <Inventor/elements/SoNormalElement.h> #include <Inventor/elements/SoSwitchElement.h> #include <Inventor/elements/SoMultiTextureCoordinateElement.h> #include <Inventor/errors/SoDebugError.h> #include <Inventor/lists/SbList.h> #include <Inventor/lists/SoNodeList.h> #include <Inventor/lists/SoPathList.h> #include <Inventor/nodes/SoNodes.h> #include <Inventor/nodes/SoTransform.h> #ifdef HAVE_NODEKITS #include <Inventor/nodekits/SoBaseKit.h> #endif // HAVE_NODEKITS #include "SbBasicP.h" #include "actions/SoSubActionP.h" #include "misc/SbHash.h" // default values for cases where a viewport is needed #define DEFAULT_VIEWPORT_WIDTH 1024 #define DEFAULT_VIEWPORT_HEIGHT 768 // ************************************************************************* SO_ACTION_SOURCE(SoToVRML2Action); // ************************************************************************* // helper function needed to copy the name of a node static SoNode * tovrml2_new_node(SoNode * newnode, const SoNode * oldnode) { const SbName name = oldnode->getName(); if (name != SbName::empty()) newnode->setName(name); return newnode; } // We use SoType::createInstance() instead of simply new'ing to make // an instance, as this makes SoType::overrideType() influence the // conversion process. #define NEW_NODE(_type_, _oldnode_) \ coin_assert_cast<_type_*>(tovrml2_new_node(static_cast<SoNode *>(_type_::getClassTypeId().createInstance()), \ _oldnode_)) // ************************************************************************* // Overridden from parent class. void SoToVRML2Action::initClass(void) { SO_ACTION_INTERNAL_INIT_CLASS(SoToVRML2Action, SoToVRMLAction); } /*! \fn SoToVRML2Action::SoToVRML2Action(void) Constructor. */ /*! \fn SoToVRML2Action::~SoToVRML2Action(void) The destructor. */ /*! \fn SoVRMLGroup * SoToVRML2Action::getVRML2SceneGraph(void) const Return a pointer to the root node of the generated scenegraph of only VRML2 / VRML97 nodes. Will return \c NULL if VRML97 support was not compiled into the library. */ /*! \fn void SoToVRML2Action::reuseAppearanceNodes(SbBool appearance) Set the flag deciding if appearance nodes should be reused if possible. The default is FALSE. Please note that support for reusing Appearance nodes is not implemented yet. */ /*! \fn SbBool SoToVRML2Action::doReuseAppearanceNodes(void) const Get the flag deciding if appearance nodes should be reused if possible. The default is FALSE. Please note that support for reusing Appearance nodes is not implemented yet, so this method will always return FALSE. */ /*! \fn void SoToVRML2Action::reusePropertyNodes(SbBool property) Set the flag deciding if property nodes should be reused if possible. The default is FALSE. */ /*! \fn SbBool SoToVRML2Action::doReusePropertyNodes(void) const Get the flag deciding if property nodes should be reused if possible. The default is FALSE. */ /*! \fn void SoToVRML2Action::reuseGeometryNodes(SbBool geometry) Set the flag deciding if geometry nodes should be reused if possible. The default is FALSE. Please note that support for reusing Geometry nodes is not implemented yet. */ /*! \fn SbBool SoToVRML2Action::doReuseGeometryNodes(void) const Get the flag deciding if geometry nodes should be reused if possible. The default is FALSE. Please note that support for reusing Geometry nodes is not implemented yet, so this function will always return FALSE. */ // ************************************************************************* #ifndef HAVE_VRML97 class SoToVRML2ActionP { public: }; SoToVRML2Action::SoToVRML2Action(void) { SO_ACTION_CONSTRUCTOR(SoToVRML2Action); } SoToVRML2Action::~SoToVRML2Action() { } void SoToVRML2Action::apply(SoNode * node) { } void SoToVRML2Action::apply(SoPath * path) { } void SoToVRML2Action::apply(const SoPathList & pathlist, SbBool obeysrules) { } SoVRMLGroup * SoToVRML2Action::getVRML2SceneGraph(void) const { return NULL; } void SoToVRML2Action::beginTraversal(SoNode * node) { } void SoToVRML2Action::reuseAppearanceNodes(SbBool appearance) { } SbBool SoToVRML2Action::doReuseAppearanceNodes(void) const { return FALSE; } void SoToVRML2Action::reusePropertyNodes(SbBool property) { } SbBool SoToVRML2Action::doReusePropertyNodes(void) const { return FALSE; } void SoToVRML2Action::reuseGeometryNodes(SbBool geometry) { } SbBool SoToVRML2Action::doReuseGeometryNodes(void) const { return FALSE; } #else // HAVE_VRML97 #include <Inventor/VRMLnodes/SoVRMLNodes.h> #include <Inventor/VRMLnodes/SoVRML.h> class SoToVRML2ActionP { public: SoToVRML2ActionP(void) : master(NULL),nodefuse(FALSE),reuseAppearanceNodes(FALSE),reuseGeometryNodes(FALSE), bboxaction(NULL),vrml2path(NULL),vrml2root(NULL),vrmlcoords(NULL),vrmlnormals(NULL),vrmlcolors(NULL),vrmltexcoords(NULL) {} ~SoToVRML2ActionP(void) { delete this->vrmlcoords; delete this->vrmlnormals; delete this->vrmlcolors; delete this->vrmltexcoords; } void init(void) { this->bsptree = NULL; this->bsptreetex = NULL; this->bsptreenormal = NULL; this->coordidx = NULL; this->normalidx = NULL; this->texidx = NULL; this->coloridx = NULL; recentTex2 = NULL; do_post_primitives = FALSE; didpush = FALSE; delete this->vrmlcoords; delete this->vrmlnormals; delete this->vrmlcolors; delete this->vrmltexcoords; this->vrmlcoords = new SbList <SoVRMLCoordinate *>; this->vrmlnormals = new SbList <SoVRMLNormal *>; this->vrmlcolors = new SbList <SoVRMLColor *>; this->vrmltexcoords = new SbList <SoVRMLTextureCoordinate *>; if (this->vrml2path) { this->vrml2path->unref(); } this->vrml2path = reclassify_cast<SoFullPath *>(new SoPath); this->vrml2path->ref(); if (this->vrml2root) { this->vrml2root->unref(); } this->vrml2root = new SoVRMLGroup; this->vrml2root->ref(); this->vrml2path->setHead(this->vrml2root); } SoGetBoundingBoxAction * getBBoxAction(void) { if (this->bboxaction == NULL) { SbViewportRegion vp(DEFAULT_VIEWPORT_WIDTH, DEFAULT_VIEWPORT_HEIGHT); this->bboxaction = new SoGetBoundingBoxAction(vp); } return this->bboxaction; } float getBBoxDistance(const SbViewVolume & vv, const float screenarea, const float h) { const float h2 = h * 0.5f; // use half the height for simplicity float screenheight = float(sqrt(screenarea)) * 0.5f; // wanted height in pixels float vvheight = vv.getHeight() * 0.5f; // total height of view volume float neardist = vv.getNearDist(); float projheight = (screenheight / 768.0f) * vvheight; // wanted projected height // now, find the distance the bbox must be at the achieve this projheight if (projheight > 0.0f) { return (neardist / projheight) * h2; } return FLT_MAX; // never switch } SoToVRML2Action * master; SbBool nodefuse; SbBool reuseAppearanceNodes; SbBool reusePropertyNodes; SbBool reuseGeometryNodes; SbHash<const SoNode *, SoGroup *> dict; SoCallbackAction cbaction; SoSearchAction searchaction; SbList <SoVRMLGroup*> separatorstack; SbBSPTree * bsptree; SbBSPTree * bsptreetex; SbBSPTree * bsptreenormal; SbList <int32_t> * coordidx; SbList <int32_t> * normalidx; SbList <int32_t> * texidx; SbList <int32_t> * coloridx; SoGetBoundingBoxAction * bboxaction; SoTexture2 * recentTex2; SbBool do_post_primitives; SbBool didpush; static SoCallbackAction::Response unsupported_cb(void *, SoCallbackAction *, const SoNode *); SoFullPath * vrml2path; SoVRMLGroup * vrml2root; SbList <SoVRMLCoordinate *> * vrmlcoords; SbList <SoVRMLNormal *> * vrmlnormals; SbList <SoVRMLColor *> * vrmlcolors; SbList <SoVRMLTextureCoordinate *> * vrmltexcoords; SoNode * search_for_recent_node(SoAction * action, const SoType & type); SoGroup * get_current_tail(void); SoVRMLCoordinate * get_or_create_coordinate(const SbVec4f *, int32_t num); SoVRMLCoordinate * get_or_create_coordinate(const SbVec3f *, int32_t num); SoVRMLNormal * get_or_create_normal(const SbVec3f *, int32_t num); SoVRMLColor * get_or_create_color(const uint32_t * packedColor, int32_t num); SoVRMLColor * get_or_create_color(const SbColor *, int32_t num); SoVRMLTextureCoordinate * get_or_create_texcoordinate(const SbVec2f *, int32_t num); void insert_shape(SoCallbackAction * action, SoVRMLGeometry * geom); // Shape nodes static SoCallbackAction::Response soasciitext_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response socone_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response socube_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response socylinder_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response soifs_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response soils_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response solineset_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sopointset_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sosphere_cb(void *, SoCallbackAction *, const SoNode *); // Property nodes static SoCallbackAction::Response soinfo_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response solabel_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response somattrans_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sorotation_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sorotationxyz_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response soscale_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sotransform_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sotranslation_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sounits_cb(void *, SoCallbackAction *, const SoNode *); // Group nodes static SoCallbackAction::Response push_sep_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response pop_sep_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response push_transformsep_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response pop_transformsep_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response push_switch_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response pop_switch_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response push_lod_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response push_levelofdetail_cb(void *, SoCallbackAction *, const SoNode *); // Other nodes static SoCallbackAction::Response sopercam_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sodirlight_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sospotlight_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sopointlight_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response sowwwinl_cb(void *, SoCallbackAction *, const SoNode *); // Convert nodes to SoVRMLIndexedFaceSet via triangle cb static SoCallbackAction::Response sotoifs_cb(void *, SoCallbackAction *, const SoNode *); static SoCallbackAction::Response post_primitives_cb(void *, SoCallbackAction *, const SoNode *); static void triangle_cb(void * userdata, SoCallbackAction * action, const SoPrimitiveVertex * v1, const SoPrimitiveVertex * v2, const SoPrimitiveVertex * v3); }; #define PRIVATE(p) (p->pimpl) #define PUBLIC(p) (p->master) #define THISP(p) (static_cast<SoToVRML2ActionP *>(p)) // ************************************************************************* // add type and all shapes inheriting type to the list of shapes // already handled by the action static void add_shape_handled(const SoType & type, SoTypeList & addlist) { SoTypeList shapes; (void) SoType::getAllDerivedFrom(type, shapes); int i; for (i = 0; i < shapes.getLength(); i++) { SoType s = shapes[i]; if (s.canCreateInstance() && (addlist.find(s) < 0)) { addlist.append(s); } } } // ************************************************************************* SoToVRML2Action::SoToVRML2Action(void) { SO_ACTION_CONSTRUCTOR(SoToVRML2Action); PRIVATE(this)->master = this; #define ADD_PRE_CB(_node_, _cb_) \ PRIVATE(this)->cbaction.addPreCallback(_node_::getClassTypeId(), SoToVRML2ActionP::_cb_, &PRIVATE(this).get()) #define ADD_POST_CB(_node_, _cb_) \ PRIVATE(this)->cbaction.addPostCallback(_node_::getClassTypeId(), SoToVRML2ActionP::_cb_, &PRIVATE(this).get()) #define ADD_UNSUPPORTED(_node_) \ PRIVATE(this)->cbaction.addPreCallback(_node_::getClassTypeId(), SoToVRML2ActionP::unsupported_cb, &PRIVATE(this).get()) #define ADD_TRIANGLE_CB(_node_) \ PRIVATE(this)->cbaction.addTriangleCallback(_node_::getClassTypeId(), SoToVRML2ActionP::triangle_cb, &PRIVATE(this).get()) #define ADD_SHAPE_CB(_node_, _cb_) \ ADD_PRE_CB(_node_, _cb_); ADD_TRIANGLE_CB(_node_); ADD_POST_CB(_node_, post_primitives_cb); \ add_shape_handled(_node_::getClassTypeId(), shapehandledlist); #define ADD_SO_TO_IFS(_node_) \ ADD_PRE_CB(_node_, sotoifs_cb); ADD_TRIANGLE_CB(_node_); ADD_POST_CB(_node_, post_primitives_cb); \ add_shape_handled(_node_::getClassTypeId(), shapehandledlist); SoTypeList shapehandledlist; ADD_SHAPE_CB(SoAsciiText, soasciitext_cb); ADD_SHAPE_CB(SoCone, socone_cb); ADD_SHAPE_CB(SoCube, socube_cb); ADD_SHAPE_CB(SoCylinder, socylinder_cb); ADD_SHAPE_CB(SoIndexedFaceSet, soifs_cb); ADD_SHAPE_CB(SoIndexedLineSet, soils_cb); ADD_SHAPE_CB(SoPointSet, sopointset_cb); ADD_SHAPE_CB(SoSphere, sosphere_cb); // Property nodes ADD_PRE_CB(SoInfo, soinfo_cb); ADD_PRE_CB(SoLabel, solabel_cb); ADD_PRE_CB(SoMatrixTransform, somattrans_cb); ADD_PRE_CB(SoRotation, sorotation_cb); ADD_PRE_CB(SoRotationXYZ, sorotationxyz_cb); ADD_PRE_CB(SoScale, soscale_cb); ADD_PRE_CB(SoTransform, sotransform_cb); ADD_PRE_CB(SoTranslation, sotranslation_cb); ADD_PRE_CB(SoUnits, sounits_cb); // Group nodes ADD_PRE_CB(SoVRMLGroup, push_sep_cb); // support for VRML97 Transform and Group ADD_POST_CB(SoVRMLGroup, pop_sep_cb); ADD_PRE_CB(SoSeparator, push_sep_cb); ADD_POST_CB(SoSeparator, pop_sep_cb); ADD_PRE_CB(SoTransformSeparator, push_transformsep_cb); ADD_POST_CB(SoTransformSeparator, pop_transformsep_cb); ADD_PRE_CB(SoSwitch, push_switch_cb); ADD_POST_CB(SoSwitch, pop_switch_cb); ADD_PRE_CB(SoLOD, push_lod_cb); ADD_PRE_CB(SoLevelOfDetail, push_levelofdetail_cb); ADD_UNSUPPORTED(SoWWWAnchor); // Convert to SoVRMLAnchor // Other nodes ADD_UNSUPPORTED(SoOrthographicCamera); ADD_PRE_CB(SoPerspectiveCamera, sopercam_cb); ADD_PRE_CB(SoDirectionalLight, sodirlight_cb); ADD_PRE_CB(SoPointLight, sopointlight_cb); ADD_PRE_CB(SoSpotLight, sospotlight_cb); ADD_PRE_CB(SoWWWInline, sowwwinl_cb); // Coin nodes ADD_SHAPE_CB(SoLineSet, solineset_cb); ADD_SO_TO_IFS(SoIndexedTriangleStripSet); ADD_SO_TO_IFS(SoFaceSet); ADD_SO_TO_IFS(SoQuadMesh); ADD_SO_TO_IFS(SoTriangleStripSet); ADD_SO_TO_IFS(SoNurbsCurve); ADD_SO_TO_IFS(SoNurbsSurface); ADD_SO_TO_IFS(SoIndexedNurbsCurve); ADD_SO_TO_IFS(SoIndexedNurbsSurface); // find all shapes not handled earlier, and add generic triangle // handling for them // // FIXME: also add line segment callback and point callback. pederb, // 2005-06-10 SoTypeList shapes; (void) SoType::getAllDerivedFrom(SoShape::getClassTypeId(), shapes); int i; for (i = 0; i < shapes.getLength(); i++) { SoType type = shapes[i]; if (type.canCreateInstance() && (shapehandledlist.find(type) < 0)) { PRIVATE(this)->cbaction.addPreCallback(type, SoToVRML2ActionP::sotoifs_cb, &PRIVATE(this).get()); PRIVATE(this)->cbaction.addTriangleCallback(type, SoToVRML2ActionP::triangle_cb, &PRIVATE(this).get()); PRIVATE(this)->cbaction.addPostCallback(type, SoToVRML2ActionP::post_primitives_cb, &PRIVATE(this).get()); } } #undef ADD_PRE_CB #undef ADD_POST_CB #undef ADD_UNSUPPORTED #undef ADD_TRIANGLE_CB #undef ADD_SHAPE_CB #undef ADD_SO_TO_IFS } SoToVRML2Action::~SoToVRML2Action(void) { if (PRIVATE(this)->bboxaction) { delete PRIVATE(this)->bboxaction; } if (PRIVATE(this)->vrml2path) { PRIVATE(this)->vrml2path->unref(); } if (PRIVATE(this)->vrml2root) { PRIVATE(this)->vrml2root->unref(); } } // Documented in superclass. void SoToVRML2Action::apply(SoNode * root) { PRIVATE(this)->init(); PRIVATE(this)->cbaction.apply(root); } // Documented in superclass. void SoToVRML2Action::apply(SoPath * path) { PRIVATE(this)->init(); PRIVATE(this)->cbaction.apply(path); } // Documented in superclass. void SoToVRML2Action::apply(const SoPathList & pathlist, SbBool obeysrules) { PRIVATE(this)->init(); PRIVATE(this)->cbaction.apply(pathlist, obeysrules); } // Documented in superclass. void SoToVRML2Action::beginTraversal(SoNode * COIN_UNUSED_ARG(node)) { assert(0 && "should never get here"); } SoVRMLGroup * SoToVRML2Action::getVRML2SceneGraph(void) const { return PRIVATE(this)->vrml2root; } void SoToVRML2Action::reuseAppearanceNodes(SbBool COIN_UNUSED_ARG(appearance)) { // FIXME: not implemented yet. 20020808 mortene. COIN_STUB(); } SbBool SoToVRML2Action::doReuseAppearanceNodes(void) const { // FIXME: not implemented yet. 20020808 mortene. COIN_STUB(); return FALSE; } void SoToVRML2Action::reusePropertyNodes(SbBool property) { PRIVATE(this)->reusePropertyNodes = property; } SbBool SoToVRML2Action::doReusePropertyNodes(void) const { return PRIVATE(this)->reusePropertyNodes; } void SoToVRML2Action::reuseGeometryNodes(SbBool COIN_UNUSED_ARG(geometry)) { // FIXME: not implemented yet. 20020808 mortene. COIN_STUB(); } SbBool SoToVRML2Action::doReuseGeometryNodes(void) const { // FIXME: not implemented yet. 20020808 mortene. return FALSE; } SoNode * SoToVRML2ActionP::search_for_recent_node(SoAction * action, const SoType & type) { this->searchaction.setSearchingAll(FALSE); this->searchaction.setType(type); this->searchaction.setInterest(SoSearchAction::LAST); #ifdef HAVE_NODEKITS SbBool old = SoBaseKit::isSearchingChildren(); SoBaseKit::setSearchingChildren(TRUE); #endif // HAVE_NODEKITS this->searchaction.apply(const_cast<SoPath *>(action->getCurPath())); SoNode * tail = NULL; SoFullPath * path = reclassify_cast<SoFullPath *>(this->searchaction.getPath()); if (path) { tail = path->getTail(); } this->searchaction.reset(); #ifdef HAVE_NODEKITS SoBaseKit::setSearchingChildren(old); #endif // HAVE_NODEKITS return tail; } SoGroup * SoToVRML2ActionP::get_current_tail(void) { SoNode * node = this->vrml2path->getTail(); assert(node->isOfType(SoVRMLGroup::getClassTypeId()) || node->isOfType(SoVRMLSwitch::getClassTypeId()) || node->isOfType(SoVRMLLOD::getClassTypeId())); return coin_assert_cast<SoGroup *>(node); } SoVRMLCoordinate * SoToVRML2ActionP::get_or_create_coordinate(const SbVec4f * coord4, int32_t num) { SbList <SbVec3f> vec3f; for (int i = 0; i < num; i++) { SbVec3f tmp; coord4[i].getReal(tmp); vec3f.append(tmp); } return this->get_or_create_coordinate(vec3f.getArrayPtr(), num); } SoVRMLCoordinate * SoToVRML2ActionP::get_or_create_coordinate(const SbVec3f * coord3, int32_t num) { if (this->reusePropertyNodes) { // Search for a matching VRMLCoordinate int n = this->vrmlcoords->getLength(); while (--n >= 0) { SoVRMLCoordinate * c = (*this->vrmlcoords)[n]; if (c->point.getNum() == num && memcmp(coord3, c->point.getValues(0), num*sizeof(SbVec3f)) == 0) { return c; } } } // Create new SoVRMLCoordinate * c = new SoVRMLCoordinate; c->point.setValues(0, num, coord3); if (this->reusePropertyNodes) this->vrmlcoords->append(c); return c; } SoVRMLNormal * SoToVRML2ActionP::get_or_create_normal(const SbVec3f * normal, int32_t num) { if (this->reusePropertyNodes) { // Search for a matching VRMLNormal int n = this->vrmlnormals->getLength(); while (--n >= 0) { SoVRMLNormal * nor = (*this->vrmlnormals)[n]; if (nor->vector.getNum() == num && memcmp(normal, nor->vector.getValues(0), num*sizeof(SbVec3f)) == 0) { return nor; } } } // Create new SoVRMLNormal * nor = new SoVRMLNormal; nor->vector.setValues(0, num, normal); if (this->reusePropertyNodes) this->vrmlnormals->append(nor); return nor; } SoVRMLColor * SoToVRML2ActionP::get_or_create_color(const uint32_t * packedColor, int32_t num) { // Convert to SbColors SbList <SbColor> color; float f; for (int i = 0; i < num; i++) { SbColor tmp; tmp.setPackedValue(packedColor[i], f); color.append(tmp); } return this->get_or_create_color(color.getArrayPtr(), num); } SoVRMLColor * SoToVRML2ActionP::get_or_create_color(const SbColor * color, int32_t num) { if (this->reusePropertyNodes) { // Search for a matching VRMLColor int n = this->vrmlcolors->getLength(); while (--n >= 0) { SoVRMLColor * c = (*this->vrmlcolors)[n]; if (c->color.getNum() == num && memcmp(color, c->color.getValues(0), num*sizeof(SbColor)) == 0) { return c; } } } // Create new SoVRMLColor * c = new SoVRMLColor; c->color.setValues(0, num, color); if (this->reusePropertyNodes) this->vrmlcolors->append(c); return c; } SoVRMLTextureCoordinate * SoToVRML2ActionP::get_or_create_texcoordinate(const SbVec2f * texcoord2, int32_t num) { if (this->reusePropertyNodes) { // Search for a matching VRMLTextureCoordinate int n = this->vrmltexcoords->getLength(); while (--n >= 0) { SoVRMLTextureCoordinate * tc = (*this->vrmltexcoords)[n]; if (tc->point.getNum() == num && memcmp(texcoord2, tc->point.getValues(0), num*sizeof(SbVec2f)) == 0) { return tc; } } } // Create new SoVRMLTextureCoordinate * tc = new SoVRMLTextureCoordinate; tc->point.setValues(0, num, texcoord2); if (this->reusePropertyNodes) this->vrmltexcoords->append(tc); return tc; } void SoToVRML2ActionP::insert_shape(SoCallbackAction * action, SoVRMLGeometry * geom) { SoVRMLShape * shape = new SoVRMLShape; shape->geometry = geom; // Create appearance SoVRMLAppearance * appearance = new SoVRMLAppearance; shape->appearance = appearance; SoVRMLMaterial * mat = new SoVRMLMaterial; appearance->material = mat; // Get values from current state SbColor ambient, diffuse, specular, emissions; float shin, transp; action->getMaterial(ambient, diffuse, specular, emissions, shin, transp); if (!geom->isOfType(SoVRMLPointSet::getClassTypeId())) { if (mat->diffuseColor.getValue() != diffuse) mat->diffuseColor = diffuse; // Convert to grayscale for calculating the ambient intensity float ambientGray = ambient[0] * 77 + ambient[1] * 150 + ambient[2] * 29; if (ambientGray > 0) { float ambientIntensity = SbMin(1.0f, ambientGray / 256.0f); if (mat->ambientIntensity.getValue() != ambientIntensity) mat->ambientIntensity = ambientIntensity; } if (mat->specularColor.getValue() != specular) mat->specularColor = specular; if (mat->emissiveColor.getValue() != emissions) mat->emissiveColor = emissions; if (mat->shininess.getValue() != shin) mat->shininess = shin; if (mat->transparency.getValue() != transp) mat->transparency = transp; // Texture if (this->recentTex2 == NULL) { this->recentTex2 = coin_safe_cast<SoTexture2 *>(search_for_recent_node(action, SoTexture2::getClassTypeId())); } if (this->recentTex2 != NULL) { SbVec2s size; int numComponents; const unsigned char * image = this->recentTex2->image.getValue(size, numComponents); if (!this->recentTex2->filename.isDefault() || (size[0] > 0 && size[1] > 0)) { SoVRMLTexture * tex; if (!this->recentTex2->filename.isDefault()) { tex = new SoVRMLImageTexture; SbString url = this->master->getUrlName(); url += this->recentTex2->filename.getValue(); coin_assert_cast<SoVRMLImageTexture *>(tex)->url.setValue(url); } else { tex = new SoVRMLPixelTexture; coin_assert_cast<SoVRMLPixelTexture *>(tex)->image.setValue(size, numComponents, image); } tex->repeatS = this->recentTex2->wrapS.getValue() == SoTexture2::REPEAT; tex->repeatT = this->recentTex2->wrapT.getValue() == SoTexture2::REPEAT; appearance->texture = tex; // Texture transform const SbMatrix * matrix = &action->getTextureMatrix(); if (!matrix->equals(SbMatrix::identity(), 0.0f)) { SbVec3f translation, scaleFactor; SbRotation rotation, scaleOrientation; matrix->getTransform(translation, rotation, scaleFactor, scaleOrientation); SoVRMLTextureTransform * textrans = new SoVRMLTextureTransform; textrans->translation = SbVec2f(translation[0], translation[1]); SbVec3f axis; float radians; rotation.getValue(axis, radians); if (axis[2] < 0) radians = static_cast<float>(2*M_PI) - radians; textrans->rotation = radians; textrans->scale = SbVec2f(scaleFactor[0], scaleFactor[1]); appearance->textureTransform = textrans; } } this->recentTex2 = NULL; } } else { if (mat->emissiveColor.getValue() != diffuse) mat->emissiveColor = diffuse; } get_current_tail()->addChild(shape); } SoCallbackAction::Response SoToVRML2ActionP::push_sep_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoToVRML2ActionP * thisp = THISP(closure); SoGroup * prevgroup = thisp->get_current_tail(); SoGroup * vp; if (THISP(closure)->dict.get(node, vp)) { // Re-use previous subgraph prevgroup->addChild(vp); return SoCallbackAction::PRUNE; } // Push a new SoVRMLGroup on the tail of the path SoVRMLGroup * newgroup = NULL; if (node->isOfType(SoVRMLTransform::getClassTypeId())) { const SoVRMLTransform * oldtrans = coin_assert_cast<const SoVRMLTransform*>(node); SoVRMLTransform * newtrans = NEW_NODE(SoVRMLTransform, node); newgroup = newtrans; newtrans->translation = oldtrans->translation; newtrans->rotation = oldtrans->rotation; newtrans->scale = oldtrans->scale; newtrans->scaleOrientation = oldtrans->scaleOrientation; newtrans->center = oldtrans->center; } else { newgroup = NEW_NODE(SoVRMLGroup, node); } // Push a new SoVRMLGroup on the tail of the path prevgroup->addChild(newgroup); thisp->vrml2path->append(newgroup); thisp->separatorstack.append(newgroup); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::pop_sep_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoGroup * vp; if (THISP(closure)->dict.get(node, vp)) { return SoCallbackAction::CONTINUE; } SoGroup * pushedgroup = THISP(closure)->separatorstack.pop(); // Pop node from the tail of the path until an SoVRMLGroup has been popped SoGroup * grp; do { grp = THISP(closure)->get_current_tail(); THISP(closure)->vrml2path->pop(); } while (grp != pushedgroup); THISP(closure)->dict.put(node, grp); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::push_transformsep_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SbString str = "SoTransformSeparator nodes do not have a VRML counterpart, and may not function correctly"; SoDebugError::postWarning("SoToVRML2Action::push_transformsep_cb", "%s", str.getString()); return push_sep_cb(closure, action, node); } SoCallbackAction::Response SoToVRML2ActionP::pop_transformsep_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { return pop_sep_cb(closure, action, node); } SoCallbackAction::Response SoToVRML2ActionP::push_switch_cb(void * closure, SoCallbackAction * action, const SoNode * node) { SoToVRML2ActionP * thisp = THISP(closure); SoGroup * prevgroup = thisp->get_current_tail(); SoGroup * vp; if (THISP(closure)->dict.get(node, vp)) { // Re-use previous subgraph prevgroup->addChild(vp); return SoCallbackAction::PRUNE; } const SoSwitch * oldswitch = coin_assert_cast<const SoSwitch *>(node); SoVRMLSwitch * newswitch = NEW_NODE(SoVRMLSwitch, node); // SO_SWITCH_INHERIT is not supported in VRML97, so just translate // it here. We could perhaps consider creating a ROUTE from the // inherited whichChoice field to this field... int wc = oldswitch->whichChild.getValue() == SO_SWITCH_INHERIT ? action->getSwitch() : oldswitch->whichChild.getValue(); newswitch->whichChoice = wc; prevgroup->addChild(newswitch); thisp->vrml2path->append(newswitch); /* Traverse all children separately, that is, save and restore state * between each. If there is a selected child, traverse it normally * This is needed so that traversing the not selected * children won't influence the selected child. */ if (wc != SO_SWITCH_ALL) { SoState * state = action->getState(); // update SwitchElement before traversing children (this is // usually done in SoSwitch::doAction) (don't push before setting // this element as it's supposed to be set when traversing the // next sibling). action->pushCurPath(); SoSwitchElement::set(state, wc); int n = oldswitch->getNumChildren(); for (int i = 0; i < n; i++) { SoNode * child = oldswitch->getChild(i); if (i != wc) { state->push(); action->popPushCurPath(i, child); action->traverse(child); state->pop(); } else { action->popPushCurPath(i, child); action->traverse(child); } } action->popCurPath(); // so that the children will not be traversed return SoCallbackAction::PRUNE; } // traverse Switch node as a normal group node return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::pop_switch_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoGroup * vp; if (THISP(closure)->dict.get(node, vp)) { return SoCallbackAction::CONTINUE; } SoGroup * grp; do { grp = THISP(closure)->get_current_tail(); THISP(closure)->vrml2path->pop(); } while (grp->getTypeId() != SoVRMLSwitch::getClassTypeId()); SoVRMLSwitch * sw = coin_assert_cast<SoVRMLSwitch *>(grp); int wc = sw->whichChoice.getValue(); if (wc == SO_SWITCH_ALL) { // workaround since VRML97 does not support SO_SWITCH_ALL. SoVRMLGroup * allfix = new SoVRMLGroup; allfix->ref(); for (int i = 0; i < sw->getNumChoices(); i++) { allfix->addChild(sw->getChoice(i)); } sw->removeAllChoices(); sw->addChoice(allfix); allfix->unrefNoDelete(); // set whichChoice to point to the new group node sw->whichChoice = 0; } THISP(closure)->dict.put(node, grp); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::push_levelofdetail_cb(void * closure, SoCallbackAction * action, const SoNode * node) { SoToVRML2ActionP * thisp = THISP(closure); SoGroup * prevgroup = thisp->get_current_tail(); SoGroup * vp; if (THISP(closure)->dict.get(node, vp)) { // Re-use previous subgraph prevgroup->addChild(vp); return SoCallbackAction::PRUNE; } const SoLevelOfDetail * oldlod = coin_assert_cast<const SoLevelOfDetail *>(node); SoVRMLLOD * newlod = NEW_NODE(SoVRMLLOD, node); // calculate bbox of children to find a reasonable conversion to range SoGetBoundingBoxAction * bboxAction = thisp->getBBoxAction(); SbViewportRegion viewport(DEFAULT_VIEWPORT_WIDTH, DEFAULT_VIEWPORT_HEIGHT); bboxAction->setViewportRegion(viewport); // need to apply on the current path, not on the node, since we // might need coordinates from the state. Also, we need to set the // reset path so that we get the local bounding box for the nodes // below this node. bboxAction->setResetPath(action->getCurPath()); bboxAction->apply(const_cast<SoPath*>(action->getCurPath())); // find bbox of all children SbBox3f bbox = bboxAction->getBoundingBox(); float dx, dy, dz; bbox.getSize(dx,dy,dz); const float h = SbMax(SbMax(dx,dy), dz); // create a typical view volume SbViewVolume vv; vv.perspective(float(M_PI)/4.0f, DEFAULT_VIEWPORT_WIDTH/DEFAULT_VIEWPORT_HEIGHT, 1.0f, 10.0f); newlod->range.setNum(oldlod->screenArea.getNum()); float * rangeptr = newlod->range.startEditing(); int i; for (i = 0; i < oldlod->screenArea.getNum(); i++) { rangeptr[i] = thisp->getBBoxDistance(vv, oldlod->screenArea[i], h); } newlod->range.finishEditing(); prevgroup->addChild(newlod); thisp->vrml2path->append(newlod); // Traverse all children separately, with normal SoGroup traversal int n = oldlod->getNumChildren(); action->pushCurPath(); for (i=0; i < n; i++) { SoNode * child = oldlod->getChild(i); action->popPushCurPath(i, child); action->traverse(child); } action->popCurPath(); thisp->vrml2path->pop(); THISP(closure)->dict.put(node, newlod); return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::push_lod_cb(void * closure, SoCallbackAction * action, const SoNode * node) { SoToVRML2ActionP * thisp = THISP(closure); SoGroup * prevgroup = thisp->get_current_tail(); SoGroup * vp; if (THISP(closure)->dict.get(node, vp)) { // Re-use previous subgraph prevgroup->addChild(vp); return SoCallbackAction::PRUNE; } const SoLOD * oldlod = coin_assert_cast<const SoLOD *>(node); SoVRMLLOD * newlod = NEW_NODE(SoVRMLLOD, node); newlod->range.setValues(0, oldlod->range.getNum(), oldlod->range.getValues(0)); newlod->center = oldlod->center.getValue(); prevgroup->addChild(newlod); thisp->vrml2path->append(newlod); // Traverse all children separately, with a normal SoGroup traversal int n = oldlod->getNumChildren(); action->pushCurPath(); for (int i=0; i < n; i++) { SoNode * child = oldlod->getChild(i); action->popPushCurPath(i, child); action->traverse(child); } action->popCurPath(); thisp->vrml2path->pop(); THISP(closure)->dict.put(node, newlod); return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::unsupported_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoVRMLWorldInfo * info = NEW_NODE(SoVRMLWorldInfo, node); SbString str; str.sprintf("Unsupported node: %s", node->getTypeId().getName().getString()); info->title = str; THISP(closure)->get_current_tail()->addChild(info); if (THISP(closure)->master->isVerbose()) { SoDebugError::postWarning("SoToVRML2Action::unsupported_cb", "%s", str.getString()); } return SoCallbackAction::CONTINUE; } // Shape nodes SoCallbackAction::Response SoToVRML2ActionP::soasciitext_cb(void * closure, SoCallbackAction * action, const SoNode * node) { if (action->getDrawStyle() != SoDrawStyle::FILLED) { return SoToVRML2ActionP::sotoifs_cb(closure, action, node); } SoVRMLText * text = NEW_NODE(SoVRMLText, node); const SoAsciiText * oldtext = coin_assert_cast<const SoAsciiText *>(node); text->string = oldtext->string; text->length = oldtext->width; SoVRMLFontStyle *style = new SoVRMLFontStyle; style->size.setValue(action->getFontSize()); text->fontStyle.setValue(style); // FIXME: Better FontStyle handling (20030414 kintel) THISP(closure)->insert_shape(action, text); return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::socube_cb(void * closure, SoCallbackAction * action, const SoNode * node) { if (action->getDrawStyle() != SoDrawStyle::FILLED) { return SoToVRML2ActionP::sotoifs_cb(closure, action, node); } SoVRMLBox * box = NEW_NODE(SoVRMLBox, node); const SoCube * cube = coin_assert_cast<const SoCube *>(node); if (box->size.getValue()[0] != cube->width.getValue() || box->size.getValue()[1] != cube->height.getValue() || box->size.getValue()[2] != cube->depth.getValue()) { box->size.setValue(cube->width.getValue(), cube->height.getValue(), cube->depth.getValue()); } THISP(closure)->insert_shape(action, box); return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::socone_cb(void * closure, SoCallbackAction * action, const SoNode * node) { if (action->getDrawStyle() != SoDrawStyle::FILLED) { return SoToVRML2ActionP::sotoifs_cb(closure, action, node); } SoVRMLCone * cone = NEW_NODE(SoVRMLCone, node); const SoCone * oldcone = coin_assert_cast<const SoCone *>(node); if (oldcone->bottomRadius != cone->bottomRadius) cone->bottomRadius = oldcone->bottomRadius.getValue(); if (oldcone->height != cone->height) cone->height = oldcone->height.getValue(); SbBool bottom = (oldcone->parts.getValue() & SoCone::BOTTOM) ? TRUE : FALSE; if (bottom != cone->bottom.getValue()) cone->bottom = bottom; SbBool side = (oldcone->parts.getValue() & SoCone::SIDES) ? TRUE : FALSE; if (side != cone->side.getValue()) cone->side = side; THISP(closure)->insert_shape(action, cone); return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::socylinder_cb(void * closure, SoCallbackAction * action, const SoNode * node) { if (action->getDrawStyle() != SoDrawStyle::FILLED) { return SoToVRML2ActionP::sotoifs_cb(closure, action, node); } SoVRMLCylinder * cyl = NEW_NODE(SoVRMLCylinder, node); const SoCylinder * oldcyl = coin_assert_cast<const SoCylinder *>(node); if (oldcyl->radius != cyl->radius) cyl->radius = oldcyl->radius.getValue(); if (oldcyl->height != cyl->height) cyl->height = oldcyl->height.getValue(); SbBool side = (oldcyl->parts.getValue() & SoCylinder::SIDES) ? TRUE : FALSE; if (side != cyl->side.getValue()) cyl->side = side; SbBool top = (oldcyl->parts.getValue() & SoCylinder::TOP) ? TRUE : FALSE; if (top != cyl->top.getValue()) cyl->top = top; SbBool bottom = (oldcyl->parts.getValue() & SoCylinder::BOTTOM) ? TRUE : FALSE; if (bottom != cyl->bottom.getValue()) cyl->bottom = bottom; THISP(closure)->insert_shape(action, cyl); return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::soifs_cb(void * closure, SoCallbackAction * action, const SoNode * node) { if (action->getDrawStyle() != SoDrawStyle::FILLED) { return SoToVRML2ActionP::sotoifs_cb(closure, action, node); } const SoIndexedFaceSet * oldifs = coin_assert_cast<const SoIndexedFaceSet*>(node); if (oldifs->coordIndex.getNum() == 0 || oldifs->coordIndex[0] < 0) return SoCallbackAction::CONTINUE; SoToVRML2ActionP * thisp = THISP(closure); SoVRMLIndexedFaceSet * ifs = NEW_NODE(SoVRMLIndexedFaceSet, node); // Set the values from the current ShapeHints ifs->creaseAngle = action->getCreaseAngle(); ifs->ccw = action->getVertexOrdering() != SoShapeHints::CLOCKWISE; ifs->solid = SoShapeHintsElement::getShapeType(action->getState()) == SoShapeHintsElement::SOLID; ifs->convex = action->getFaceType() == SoShapeHints::CONVEX; // If there is a VertexProperty node set we need to put it on the state stack SoNode *vpnode = oldifs->vertexProperty.getValue(); SoVertexProperty * vp = coin_safe_cast<SoVertexProperty *>(vpnode); if (vp) { action->getState()->push(); vp->callback(action); } const SoCoordinateElement * coordElem = SoCoordinateElement::getInstance(action->getState()); if (coordElem->getNum() > 0) { if (coordElem->getArrayPtr3() != NULL) { ifs->coord = thisp->get_or_create_coordinate(coordElem->getArrayPtr3(), coordElem->getNum()); } else { ifs->coord = thisp->get_or_create_coordinate(coordElem->getArrayPtr4(), coordElem->getNum()); } } if (action->getNormalBinding() != SoNormalBinding::OVERALL) { const SoNormalElement * normalElem = SoNormalElement::getInstance(action->getState()); if (coordElem->getNum() > 0) { ifs->normal = thisp->get_or_create_normal(normalElem->getArrayPtr(), normalElem->getNum()); if (action->getNormalBinding() != SoNormalBinding::PER_VERTEX_INDEXED && action->getNormalBinding() != SoNormalBinding::PER_VERTEX) { ifs->normalPerVertex = FALSE; } } } if (action->getMaterialBinding() != SoMaterialBinding::OVERALL) { SoLazyElement * lazy = SoLazyElement::getInstance(action->getState()); if (lazy->getNumDiffuse() > 1) { if (lazy->isPacked()) { ifs->color = thisp->get_or_create_color(lazy->getPackedPointer(), lazy->getNumDiffuse()); } else { ifs->color = thisp->get_or_create_color(lazy->getDiffusePointer(), lazy->getNumDiffuse()); } if (action->getMaterialBinding() != SoMaterialBinding::PER_VERTEX_INDEXED && action->getMaterialBinding() != SoMaterialBinding::PER_VERTEX) { ifs->colorPerVertex = FALSE; } } } const SoMultiTextureCoordinateElement * texcoordElem = SoMultiTextureCoordinateElement::getInstance(action->getState()); if (texcoordElem->getNum(0) > 0) { ifs->texCoord = thisp->get_or_create_texcoordinate(texcoordElem->getArrayPtr2(), texcoordElem->getNum()); } ifs->coordIndex.setValues(0, oldifs->coordIndex.getNum(), oldifs->coordIndex.getValues(0)); if (!oldifs->textureCoordIndex.isDefault() && oldifs->textureCoordIndex.getNum()) { ifs->texCoordIndex.setValues(0, oldifs->textureCoordIndex.getNum(), oldifs->textureCoordIndex.getValues(0)); } if (!oldifs->materialIndex.isDefault() && oldifs->materialIndex.getNum()) { ifs->colorIndex.setValues(0, oldifs->materialIndex.getNum(), oldifs->materialIndex.getValues(0)); } if (!oldifs->normalIndex.isDefault() && oldifs->normalIndex.getNum()) { ifs->normalIndex.setValues(0, oldifs->normalIndex.getNum(), oldifs->normalIndex.getValues(0)); } THISP(closure)->insert_shape(action, ifs); // it's important to pop state _after_ inserting the shape to get // the correct material from SoVertexProperty nodes. if (vp) { action->getState()->pop(); } return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::soils_cb(void * closure, SoCallbackAction * action, const SoNode * node) { // FIXME: test for drawstyle == POINTS and convert to a point set // instead. pederb, 20060327 SoToVRML2ActionP * thisp = THISP(closure); const SoIndexedLineSet * oldils = coin_assert_cast<const SoIndexedLineSet *>(node); if (oldils->coordIndex.getNum() == 0 || oldils->coordIndex[0] < 0) return SoCallbackAction::CONTINUE; SoVRMLIndexedLineSet * ils = NEW_NODE(SoVRMLIndexedLineSet, node); // If there is a VertexProperty node set we need to put it on the state stack SoNode *vpnode = oldils->vertexProperty.getValue(); SoVertexProperty *vp = coin_safe_cast<SoVertexProperty *>(vpnode); if (vp) { action->getState()->push(); vp->callback(action); } SoVRMLCoordinate * newcoord = NULL; const SoCoordinateElement * coordElem = SoCoordinateElement::getInstance(action->getState()); if (coordElem->getNum() > 0) { if (thisp->nodefuse) { newcoord = new SoVRMLCoordinate; } else { if (coordElem->getArrayPtr3() != NULL) { newcoord = thisp->get_or_create_coordinate(coordElem->getArrayPtr3(), coordElem->getNum()); } else { newcoord = thisp->get_or_create_coordinate(coordElem->getArrayPtr4(), coordElem->getNum()); } } ils->coord = newcoord; } if (action->getMaterialBinding() != SoMaterialBinding::OVERALL) { const SoLazyElement * colorElem = SoLazyElement::getInstance(action->getState()); if (colorElem->getNumDiffuse() > 0) { if (colorElem->isPacked()) { ils->color = thisp->get_or_create_color(colorElem->getPackedPointer(), colorElem->getNumDiffuse()); } else { ils->color = thisp->get_or_create_color(colorElem->getDiffusePointer(), colorElem->getNumDiffuse()); } if (action->getMaterialBinding() != SoMaterialBinding::PER_VERTEX_INDEXED && action->getMaterialBinding() != SoMaterialBinding::PER_VERTEX) { ils->colorPerVertex = FALSE; } } } if (thisp->nodefuse && coordElem->getNum() > 0) { SbBSPTree bsp; int n = oldils->coordIndex.getNum(); const int32_t * src = oldils->coordIndex.getValues(0); SbVec3f * c = const_cast<SbVec3f*>(coordElem->getArrayPtr3()); if (c == NULL) { SbVec3f * vec3f = new SbVec3f[coordElem->getNum()]; const SbVec4f * coord4 = coordElem->getArrayPtr4(); for (int i=coordElem->getNum()-1; i >= 0; i--) { coord4[i].getReal(vec3f[i]); } c = vec3f; } ils->coordIndex.setNum(n); int32_t * dst = ils->coordIndex.startEditing(); for (int i = 0; i < n; i++) { int32_t idx = src[i]; if (idx >= 0) { dst[i] = bsp.addPoint(c[idx]); } else dst[i] = -1; } ils->coordIndex.finishEditing(); newcoord->point.setValues(0, bsp.numPoints(), bsp.getPointsArrayPtr()); if (coordElem->getArrayPtr3() == NULL) delete[] c; } else { ils->coordIndex.setValues(0, oldils->coordIndex.getNum(), oldils->coordIndex.getValues(0)); } if (action->getMaterialBinding() == SoMaterialBinding::PER_VERTEX_INDEXED || action->getMaterialBinding() == SoMaterialBinding::PER_FACE_INDEXED) { ils->colorIndex.setValues(0, oldils->materialIndex.getNum(), oldils->materialIndex.getValues(0)); } else if (action->getMaterialBinding() == SoMaterialBinding::PER_PART_INDEXED || action->getMaterialBinding() == SoMaterialBinding::PER_PART) { // Color per segment, convert to per vertex SbList <int32_t> coordIdx; SbBSPTree bsp; int32_t colidx = 0; SoVRMLColor * color = coin_assert_cast<SoVRMLColor *>(ils->color.getValue()); int n = ils->coordIndex.getNum()-1; for (int i = 0; i < n; i++) { SbVec3f curcol, nextcol(0.0f, 0.0f, 0.0f); if (action->getMaterialBinding() == SoMaterialBinding::PER_PART_INDEXED) { curcol = color->color[oldils->materialIndex[colidx]]; if (i != n-1) nextcol = color->color[oldils->materialIndex[colidx+1]]; } else { curcol = color->color[colidx]; if (i != n-1) nextcol = color->color[colidx+1]; } colidx++; coordIdx.append(bsp.addPoint(curcol)); if (i == n-1 || ils->coordIndex[i+2] == -1) { // Current polyline is done coordIdx.append(coordIdx[coordIdx.getLength()-1]); coordIdx.append(-1); i += 2; } else if (curcol != nextcol) { // Create a new vertex to avoid color interpolation ils->coordIndex.insertSpace(i+1, 1); ils->coordIndex.set1Value(i+1, ils->coordIndex[i+2]); coordIdx.append(bsp.addPoint(curcol)); i++; n++; } } ils->color = thisp->get_or_create_color(static_cast<const SbColor *>(bsp.getPointsArrayPtr()), bsp.numPoints()); ils->colorIndex.setValues(0, coordIdx.getLength(), coordIdx.getArrayPtr()); ils->colorPerVertex = TRUE; } THISP(closure)->insert_shape(action, ils); // it's important to pop state _after_ inserting the shape to get // the correct material from SoVertexProperty nodes. if (vp) { action->getState()->pop(); } return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::solineset_cb(void * closure, SoCallbackAction * action, const SoNode * node) { // FIXME: test for drawstyle == POINTS and convert to a point set // instead. pederb, 20060327 SoToVRML2ActionP * thisp = THISP(closure); const SoLineSet * oldls = coin_assert_cast<const SoLineSet *>(node); if (oldls->numVertices.getNum() == 0) return SoCallbackAction::CONTINUE; SoVRMLIndexedLineSet * ils = NEW_NODE(SoVRMLIndexedLineSet, node); // If there is a VertexProperty node set we need to put it on the state stack SoNode *vpnode = oldls->vertexProperty.getValue(); SoVertexProperty *vp = coin_safe_cast<SoVertexProperty *>(vpnode); if (vp) { action->getState()->push(); vp->callback(action); } const SoCoordinateElement * coordElem = SoCoordinateElement::getInstance(action->getState()); if (coordElem->getNum() > 0) { if (coordElem->getArrayPtr3() != NULL) { ils->coord = thisp->get_or_create_coordinate(coordElem->getArrayPtr3(), coordElem->getNum()); } else { ils->coord = thisp->get_or_create_coordinate(coordElem->getArrayPtr4(), coordElem->getNum()); } } if (action->getMaterialBinding() != SoMaterialBinding::OVERALL) { const SoLazyElement * colorElem = SoLazyElement::getInstance(action->getState()); if (colorElem->getNumDiffuse() > 0) { if (colorElem->isPacked()) { ils->color = thisp->get_or_create_color(colorElem->getPackedPointer(), colorElem->getNumDiffuse()); } else { ils->color = thisp->get_or_create_color(colorElem->getDiffusePointer(), colorElem->getNumDiffuse()); } if (action->getMaterialBinding() != SoMaterialBinding::PER_VERTEX) { ils->colorPerVertex = FALSE; } } } SbList <int32_t> l; int n = oldls->numVertices.getNum(); int32_t curidx = 0; // check for special case where lineset should render all vertices // on the state if ((n == 1) && (oldls->numVertices[0] == -1)) { const int numv = coordElem->getNum(); for (int i = 0; i < numv; i++) { l.append(curidx++); } l.append(-1); } else { for (int i = 0; i < n; i++) { for (int j = oldls->numVertices[i]-1; j >= 0; j--) { l.append(curidx++); } l.append(-1); } } ils->coordIndex.setValues(0, l.getLength(), l.getArrayPtr()); if (action->getMaterialBinding() == SoMaterialBinding::PER_PART) { // Color per segment, convert to per vertex SbList <int32_t> coordIdx; SbBSPTree bsp; int32_t colidx = 0; SoVRMLColor * color = coin_assert_cast<SoVRMLColor *>(ils->color.getValue()); int n = ils->coordIndex.getNum()-1; for (int i = 0; i < n; i++) { SbVec3f curcol, nextcol(0.0f, 0.0f, 0.0f); curcol = color->color[colidx]; if (i != n-1) nextcol = color->color[colidx+1]; colidx++; coordIdx.append(bsp.addPoint(curcol)); if (i == n-1 || ils->coordIndex[i+2] == -1) { // Current polyline is done coordIdx.append(coordIdx[coordIdx.getLength()-1]); coordIdx.append(-1); i += 2; } else if (curcol != nextcol) { // Create a new vertex to avoid color interpolation ils->coordIndex.insertSpace(i+1, 1); ils->coordIndex.set1Value(i+1, ils->coordIndex[i+2]); coordIdx.append(bsp.addPoint(curcol)); i++; n++; } } ils->color = thisp->get_or_create_color(static_cast<const SbColor *>(bsp.getPointsArrayPtr()), bsp.numPoints()); ils->colorIndex.setValues(0, coordIdx.getLength(), coordIdx.getArrayPtr()); ils->colorPerVertex = TRUE; } THISP(closure)->insert_shape(action, ils); // it's important to pop state _after_ inserting the shape to get // the correct material from SoVertexProperty nodes. if (vp) { action->getState()->pop(); } return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::sopointset_cb(void * closure, SoCallbackAction * action, const SoNode * node) { SoToVRML2ActionP * thisp = THISP(closure); const SoPointSet * oldps = coin_assert_cast<const SoPointSet *>(node); SoVRMLPointSet * ps = NEW_NODE(SoVRMLPointSet, node); // If there is a VertexProperty node set we need to put it on the state stack SoNode *vpnode = oldps->vertexProperty.getValue(); SoVertexProperty *vp = coin_safe_cast<SoVertexProperty *>(vpnode); if (vp) { action->getState()->push(); vp->callback(action); } const SoCoordinateElement * coordElem = SoCoordinateElement::getInstance(action->getState()); int numpts = oldps->numPoints.getValue(); // if numPts == -1, use all coordinates on the stack if (numpts < 0 || numpts > coordElem->getNum()) numpts = coordElem->getNum(); if (numpts) { if (coordElem->getArrayPtr3() != NULL) { ps->coord = thisp->get_or_create_coordinate(coordElem->getArrayPtr3(), numpts); } else { ps->coord = thisp->get_or_create_coordinate(coordElem->getArrayPtr4(), numpts); } } if (action->getMaterialBinding() != SoMaterialBinding::OVERALL) { const SoLazyElement * colorElem = SoLazyElement::getInstance(action->getState()); if (colorElem->getNumDiffuse() >= numpts) { if (colorElem->isPacked()) { ps->color = thisp->get_or_create_color(colorElem->getPackedPointer(), numpts); } else { ps->color = thisp->get_or_create_color(colorElem->getDiffusePointer(), numpts); } } } THISP(closure)->insert_shape(action, ps); // it's important to pop state _after_ inserting the shape to get // the correct material from SoVertexProperty nodes. if (vp) { action->getState()->pop(); } return SoCallbackAction::PRUNE; } SoCallbackAction::Response SoToVRML2ActionP::sosphere_cb(void * closure, SoCallbackAction * action, const SoNode * node) { if (action->getDrawStyle() != SoDrawStyle::FILLED) { return SoToVRML2ActionP::sotoifs_cb(closure, action, node); } SoVRMLSphere * sphere = NEW_NODE(SoVRMLSphere, node); const SoSphere * oldsphere = coin_assert_cast<const SoSphere *>(node); if (oldsphere->radius != sphere->radius) sphere->radius = oldsphere->radius.getValue(); THISP(closure)->insert_shape(action, sphere); return SoCallbackAction::PRUNE; } // Property nodes SoCallbackAction::Response SoToVRML2ActionP::soinfo_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { const SoInfo * oldinfo = coin_assert_cast<const SoInfo *>(node); SoVRMLWorldInfo * info = NEW_NODE(SoVRMLWorldInfo, node); info->title = oldinfo->string; THISP(closure)->get_current_tail()->addChild(info); return SoCallbackAction::CONTINUE; } // Property nodes SoCallbackAction::Response SoToVRML2ActionP::solabel_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { const SoLabel * oldlabel = coin_assert_cast<const SoLabel *>(node); SoVRMLWorldInfo * info = NEW_NODE(SoVRMLWorldInfo, node); info->title = oldlabel->label.getValue().getString(); THISP(closure)->get_current_tail()->addChild(info); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::somattrans_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { const SoMatrixTransform * oldt = coin_assert_cast<const SoMatrixTransform *>(node); SoVRMLTransform * newt = NEW_NODE(SoVRMLTransform, node); SbVec3f translation, scaleFactor; SbRotation rotation, scaleOrientation; oldt->matrix.getValue().getTransform(translation, rotation, scaleFactor, scaleOrientation); newt->translation = translation.getValue(); newt->rotation = rotation.getValue(); newt->scale = scaleFactor.getValue(); newt->scaleOrientation = scaleOrientation.getValue(); THISP(closure)->get_current_tail()->addChild(newt); THISP(closure)->vrml2path->append(newt); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::sorotation_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { const SoRotation * oldt = coin_assert_cast<const SoRotation *>(node); SoVRMLTransform * newt = NEW_NODE(SoVRMLTransform, node); newt->rotation = oldt->rotation.getValue(); THISP(closure)->get_current_tail()->addChild(newt); THISP(closure)->vrml2path->append(newt); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::sorotationxyz_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { const SoRotationXYZ * oldt = coin_assert_cast<const SoRotationXYZ *>(node); SoVRMLTransform * newt = NEW_NODE(SoVRMLTransform, node); newt->rotation = oldt->getRotation(); THISP(closure)->get_current_tail()->addChild(newt); THISP(closure)->vrml2path->append(newt); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::soscale_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { const SoScale * oldt = coin_assert_cast<const SoScale *>(node); SoVRMLTransform * newt = NEW_NODE(SoVRMLTransform, node); newt->scale = oldt->scaleFactor.getValue(); THISP(closure)->get_current_tail()->addChild(newt); THISP(closure)->vrml2path->append(newt); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::sotransform_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { const SoTransform * oldt = coin_assert_cast<const SoTransform *>(node); SoVRMLTransform * newt = NEW_NODE(SoVRMLTransform, node); newt->translation = oldt->translation.getValue(); newt->rotation = oldt->rotation.getValue(); newt->scale = oldt->scaleFactor.getValue(); newt->scaleOrientation = oldt->scaleOrientation.getValue(); newt->center = oldt->center.getValue(); THISP(closure)->get_current_tail()->addChild(newt); THISP(closure)->vrml2path->append(newt); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::sotranslation_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { const SoTranslation * oldt = coin_assert_cast<const SoTranslation *>(node); SoVRMLTransform * newt = NEW_NODE(SoVRMLTransform, node); newt->translation = oldt->translation.getValue(); THISP(closure)->get_current_tail()->addChild(newt); THISP(closure)->vrml2path->append(newt); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::sounits_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoVRMLTransform * newt = NEW_NODE(SoVRMLTransform, node); // apply an SoGetMatrixAction to the node to find the scale factor SbViewportRegion dummy(100,100); SoGetMatrixAction gma(dummy); gma.apply(const_cast<SoNode *>(node)); const SbMatrix & m = gma.getMatrix(); // we know that the SoUnits node applies an uniform scale, so just // read the value in the first matrix column/row to find the scale // factor. newt->scale = SbVec3f(m[0][0], m[0][0], m[0][0]); THISP(closure)->get_current_tail()->addChild(newt); THISP(closure)->vrml2path->append(newt); return SoCallbackAction::CONTINUE; } // Other nodes SoCallbackAction::Response SoToVRML2ActionP::sopercam_cb(void * closure, SoCallbackAction * action, const SoNode * node) { return unsupported_cb(closure, action, node); } SoCallbackAction::Response SoToVRML2ActionP::sodirlight_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoVRMLDirectionalLight * dl = NEW_NODE(SoVRMLDirectionalLight, node); const SoDirectionalLight * olddl = coin_assert_cast<const SoDirectionalLight *>(node); dl->direction = olddl->direction.getValue(); dl->on = olddl->on.getValue(); dl->intensity = olddl->intensity.getValue(); dl->color = olddl->color.getValue(); // FIXME: SoDirectionalLight seems to not support this? 20020805 kristian. //dl->ambientIntensity = ambient.getValue()[0] / diffuse.getValue()[0]; THISP(closure)->get_current_tail()->addChild(dl); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::sopointlight_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoVRMLPointLight * dl = NEW_NODE(SoVRMLPointLight, node); const SoPointLight * olddl = coin_assert_cast<const SoPointLight *>(node); dl->location = olddl->location.getValue(); dl->on = olddl->on.getValue(); dl->intensity = olddl->intensity.getValue(); dl->color = olddl->color.getValue(); THISP(closure)->get_current_tail()->addChild(dl); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::sospotlight_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoVRMLSpotLight * dl = NEW_NODE(SoVRMLSpotLight, node); const SoSpotLight * olddl = coin_assert_cast<const SoSpotLight *>(node); dl->location = olddl->location.getValue(); dl->direction = olddl->direction.getValue(); dl->on = olddl->on.getValue(); dl->intensity = olddl->intensity.getValue(); dl->color = olddl->color.getValue(); dl->cutOffAngle = olddl->cutOffAngle.getValue(); THISP(closure)->get_current_tail()->addChild(dl); return SoCallbackAction::CONTINUE; } SoCallbackAction::Response SoToVRML2ActionP::sowwwinl_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoNode * node) { SoVRMLInline * inl = NEW_NODE(SoVRMLInline, node); const SoWWWInline * oldinl = coin_assert_cast<const SoWWWInline *>(node); inl->url = oldinl->name.getValue(); inl->bboxCenter = oldinl->bboxCenter.getValue(); inl->bboxSize = oldinl->bboxSize.getValue(); THISP(closure)->get_current_tail()->addChild(inl); return SoCallbackAction::CONTINUE; } // Convert nodes to ifs SoCallbackAction::Response SoToVRML2ActionP::sotoifs_cb(void * closure, SoCallbackAction * action, const SoNode * node) { SoToVRML2ActionP * thisp = THISP(closure); thisp->didpush = FALSE; // push state to handle SoVertexProperty node if (node->isOfType(SoVertexShape::getClassTypeId())) { SoNode * vpnode = coin_assert_cast<const SoVertexShape *>(node)->vertexProperty.getValue(); SoVertexProperty * vp = coin_safe_cast<SoVertexProperty *>(vpnode); if (vp) { action->getState()->push(); vp->callback(action); thisp->didpush = TRUE; } } thisp->bsptree = new SbBSPTree; thisp->bsptreenormal = new SbBSPTree; thisp->coordidx = new SbList <int32_t>; thisp->normalidx = new SbList <int32_t>; if (action->getMaterialBinding() != SoMaterialBinding::OVERALL) { const SoLazyElement * colorElem = SoLazyElement::getInstance(action->getState()); if (colorElem->getNumDiffuse() > 1) { thisp->coloridx = new SbList <int32_t>; } } thisp->recentTex2 = coin_safe_cast<SoTexture2 *>(thisp->search_for_recent_node(action, SoTexture2::getClassTypeId())); if (thisp->recentTex2) { thisp->bsptreetex = new SbBSPTree; thisp->texidx = new SbList <int32_t>; } thisp->do_post_primitives = TRUE; return SoCallbackAction::CONTINUE; } void SoToVRML2ActionP::triangle_cb(void * closure, SoCallbackAction * COIN_UNUSED_ARG(action), const SoPrimitiveVertex * v1, const SoPrimitiveVertex * v2, const SoPrimitiveVertex * v3) { SoToVRML2ActionP * thisp = THISP(closure); assert(thisp->bsptree); assert(thisp->bsptreenormal); SoPrimitiveVertex const * const arr[3] = {v1, v2, v3}; for (int i = 0; i < 3; i++) { const SoPrimitiveVertex * v = arr[i]; thisp->coordidx->append(thisp->bsptree->addPoint(v->getPoint())); thisp->normalidx->append(thisp->bsptreenormal->addPoint(v->getNormal())); if (thisp->texidx) { assert(thisp->bsptreetex); const SbVec4f & tc = v->getTextureCoords(); thisp->texidx->append(thisp->bsptreetex->addPoint(SbVec3f(tc[0], tc[1], 0.0f))); } if (thisp->coloridx) thisp->coloridx->append(v->getMaterialIndex()); } thisp->coordidx->append(-1); thisp->normalidx->append(-1); if (thisp->texidx) thisp->texidx->append(-1); if (thisp->coloridx) thisp->coloridx->append(-1); } SoCallbackAction::Response SoToVRML2ActionP::post_primitives_cb(void * closure, SoCallbackAction * action, const SoNode * node) { SoToVRML2ActionP * thisp = THISP(closure); if (!thisp->do_post_primitives) return SoCallbackAction::CONTINUE; thisp->do_post_primitives = FALSE; SoVRMLGeometry * is; if (action->getDrawStyle() == SoDrawStyle::POINTS) { SoVRMLPointSet * ps = NEW_NODE(SoVRMLPointSet, node); is = ps; ps->coord = thisp->get_or_create_coordinate(thisp->bsptree->getPointsArrayPtr(), thisp->bsptree->numPoints()); if (thisp->coloridx) { // Copy the colors from the state SoLazyElement * colorElem = SoLazyElement::getInstance(action->getState()); if (colorElem->getNumDiffuse() == thisp->bsptree->numPoints()) { if (colorElem->isPacked()) { ps->color = thisp->get_or_create_color(colorElem->getPackedPointer(), colorElem->getNumDiffuse()); } else { ps->color = thisp->get_or_create_color(colorElem->getDiffusePointer(), colorElem->getNumDiffuse()); } } } } else if (action->getDrawStyle() == SoDrawStyle::LINES) { SoVRMLIndexedLineSet * ils = NEW_NODE(SoVRMLIndexedLineSet, node); is = ils; ils->coord = thisp->get_or_create_coordinate(thisp->bsptree->getPointsArrayPtr(), thisp->bsptree->numPoints()); if (thisp->coloridx) { // Copy the colors from the state const SoLazyElement * colorElem = SoLazyElement::getInstance(action->getState()); if (colorElem->isPacked()) { ils->color = thisp->get_or_create_color(colorElem->getPackedPointer(), colorElem->getNumDiffuse()); } else { ils->color = thisp->get_or_create_color(colorElem->getDiffusePointer(), colorElem->getNumDiffuse()); } // Index ils->colorIndex.setValues(0, thisp->coloridx->getLength(), thisp->coloridx->getArrayPtr()); } int n = thisp->coordidx->getLength(); const int32_t * a = thisp->coordidx->getArrayPtr(); SbList <int32_t> l; int32_t p = a[0]; for (int i = 0; i < n; i++) { if (a[i] == -1) { l.append(p); if (i < n-1) p = a[i+1]; } l.append(a[i]); } ils->coordIndex.setValues(0, l.getLength(), l.getArrayPtr()); } else { SoVRMLIndexedFaceSet * ifs = NEW_NODE(SoVRMLIndexedFaceSet, node); is = ifs; // we need some specific handling for VRML nodes, since these // nodes store the state inside the node in fields const SoSFBool * ccw_field = NULL; const SoSFBool * solid_field = NULL; const SoSFBool * convex_field = NULL; const SoSFFloat * creaseangle_field = NULL; if (node->isOfType(SoVRMLGeometry::getClassTypeId())) { ccw_field = static_cast<const SoSFBool*>(node->getField("ccw")); solid_field = static_cast<const SoSFBool*>(node->getField("solid")); convex_field = static_cast<const SoSFBool*>(node->getField("convex")); creaseangle_field = static_cast<const SoSFFloat*>(node->getField("creaseAngle")); } // Set the values from the current ShapeHints ifs->creaseAngle = creaseangle_field ? creaseangle_field->getValue() : action->getCreaseAngle(); if (node->isOfType(SoVertexShape::getClassTypeId())) { ifs->ccw = action->getVertexOrdering() != SoShapeHints::CLOCKWISE; } else { ifs->ccw = ccw_field ? ccw_field->getValue() : TRUE; } ifs->solid = solid_field ? solid_field->getValue() : (SoShapeHintsElement::getShapeType(action->getState()) == SoShapeHintsElement::SOLID); ifs->convex = convex_field ? convex_field->getValue() : (action->getFaceType() == SoShapeHints::CONVEX); ifs->coord = thisp->get_or_create_coordinate(thisp->bsptree->getPointsArrayPtr(), thisp->bsptree->numPoints()); ifs->normal = thisp->get_or_create_normal(thisp->bsptreenormal->getPointsArrayPtr(), thisp->bsptreenormal->numPoints()); if (thisp->coloridx) { // Copy the colors from the state const SoLazyElement * colorElem = SoLazyElement::getInstance(action->getState()); if (colorElem->isPacked()) { ifs->color = thisp->get_or_create_color(colorElem->getPackedPointer(), colorElem->getNumDiffuse()); } else { ifs->color = thisp->get_or_create_color(colorElem->getDiffusePointer(), colorElem->getNumDiffuse()); } // Index ifs->colorIndex.setValues(0, thisp->coloridx->getLength(), thisp->coloridx->getArrayPtr()); } if (thisp->texidx) { // Copy texture coordinates SoVRMLTextureCoordinate * tex = new SoVRMLTextureCoordinate; int n = thisp->bsptreetex->numPoints(); tex->point.setNum(n); SbVec2f * ptr = tex->point.startEditing(); for (int i = 0; i < n; i++) { SbVec3f p = thisp->bsptreetex->getPoint(i); ptr[i] = SbVec2f(p[0], p[1]); } tex->point.finishEditing(); ifs->texCoord = tex; // Index ifs->texCoordIndex.setValues(0, thisp->texidx->getLength(), thisp->texidx->getArrayPtr()); } ifs->coordIndex.setValues(0, thisp->coordidx->getLength(), thisp->coordidx->getArrayPtr()); ifs->normalIndex.setValues(0, thisp->normalidx->getLength(), thisp->normalidx->getArrayPtr()); } delete thisp->bsptree; thisp->bsptree = NULL; delete thisp->bsptreetex; thisp->bsptreetex = NULL; delete thisp->bsptreenormal; thisp->bsptreenormal = NULL; delete thisp->coordidx; thisp->coordidx = NULL; delete thisp->normalidx; thisp->normalidx = NULL; delete thisp->texidx; thisp->texidx = NULL; delete thisp->coloridx; thisp->coloridx = NULL; thisp->insert_shape(action, is); if (thisp->didpush) { action->getState()->pop(); } return SoCallbackAction::CONTINUE; } #undef NEW_NODE #undef DEFAULT_VIEWPORT_WIDTH #undef DEFAULT_VIEWPORT_HEIGHT #undef PRIVATE #undef PUBLIC #undef THISP #endif // HAVE_VRML97
34.907651
143
0.67989
[ "geometry", "render", "shape", "vector", "transform", "solid" ]
4fe88668e7ae4c8aba957ed4217b9ec094b82b37
6,401
cpp
C++
Engine/Source/Runtime/Engine/Private/LODActor.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Engine/Private/LODActor.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Engine/Private/LODActor.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= LODActorBase.cpp: Static mesh actor base class implementation. =============================================================================*/ #include "EnginePrivate.h" #include "Engine/LODActor.h" #include "MapErrors.h" #include "MessageLog.h" #include "UObjectToken.h" #if WITH_EDITOR #include "Components/DrawSphereComponent.h" #endif // WITH_EDITOR #define LOCTEXT_NAMESPACE "LODActor" ALODActor::ALODActor(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) , LODDrawDistance(5000) { bCanBeDamaged = false; bIsPreviewActor = false; StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent0")); StaticMeshComponent->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); StaticMeshComponent->Mobility = EComponentMobility::Static; StaticMeshComponent->bGenerateOverlapEvents = false; StaticMeshComponent->bCastDynamicShadow = false; StaticMeshComponent->bCastStaticShadow = false; StaticMeshComponent->CastShadow = false; RootComponent = StaticMeshComponent; #if WITH_EDITORONLY_DATA DrawSphereComponent = CreateEditorOnlyDefaultSubobject<UDrawSphereComponent>(TEXT("VisualizeComponent0")); if (DrawSphereComponent) { DrawSphereComponent->SetSphereRadius(0.0f); } #endif // WITH_EDITORONLY_DATA } FString ALODActor::GetDetailedInfoInternal() const { return StaticMeshComponent ? StaticMeshComponent->GetDetailedInfoInternal() : TEXT("No_StaticMeshComponent"); } void ALODActor::PostRegisterAllComponents() { Super::PostRegisterAllComponents(); #if WITH_EDITOR if (!bIsPreviewActor && StaticMeshComponent->SceneProxy) { ensure (LODLevel >= 1); (StaticMeshComponent->SceneProxy)->SetHierarchicalLOD_GameThread(LODLevel); } #endif } void ALODActor::SetStaticMesh(class UStaticMesh* InStaticMesh) { if (StaticMeshComponent) { StaticMeshComponent->StaticMesh = InStaticMesh; } // If given NULL for static mesh then this is a preview actor (only rendering the bounds) bIsPreviewActor = (InStaticMesh == nullptr); } #if WITH_EDITOR void ALODActor::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { UProperty* PropertyThatChanged = PropertyChangedEvent.Property; FName PropertyName = PropertyThatChanged != NULL ? PropertyThatChanged->GetFName() : NAME_None; if (PropertyName == GET_MEMBER_NAME_CHECKED(ALODActor, LODDrawDistance)) { for (auto& Actor: SubActors) { if (Actor) { TArray<UPrimitiveComponent*> InnerComponents; Actor->GetComponents<UPrimitiveComponent>(InnerComponents); for(auto& Component: InnerComponents) { UPrimitiveComponent* ParentComp = Component->GetLODParentPrimitive(); if (ParentComp) { ParentComp->MinDrawDistance = LODDrawDistance; ParentComp->MarkRenderStateDirty(); } } } } } Super::PostEditChangeProperty(PropertyChangedEvent); } bool ALODActor::GetReferencedContentObjects( TArray<UObject*>& Objects ) const { Super::GetReferencedContentObjects(Objects); return true; } void ALODActor::CheckForErrors() { FMessageLog MapCheck("MapCheck"); // Only check when this is not a preview actor and actually has a static mesh if (!bIsPreviewActor) { Super::CheckForErrors(); if (!StaticMeshComponent) { MapCheck.Warning() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(LOCTEXT("MapCheck_Message_StaticMeshComponent", "Static mesh actor has NULL StaticMeshComponent property - please delete"))) ->AddToken(FMapErrorToken::Create(FMapErrors::StaticMeshComponent)); } if (StaticMeshComponent && StaticMeshComponent->StaticMesh == NULL) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Error() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT("MapCheck_Message_InvalidLODActorMissingMesh", "{ActorName} : Static mesh is missing for the built LODActor. Did you remove the asset? Please delete it and build LOD again. "), Arguments))) ->AddToken(FMapErrorToken::Create(FMapErrors::LODActorMissingStaticMesh)); } } if (SubActors.Num() == 0) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Error() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT("MapCheck_Message_InvalidLODActorEmptyActor", "{ActorName} : NoActor is assigned. We recommend you to delete this actor. "), Arguments))) ->AddToken(FMapErrorToken::Create(FMapErrors::LODActorNoActorFound)); } else { for(auto& Actor : SubActors) { // see if it's null, if so it is not good if(Actor == nullptr) { FFormatNamedArguments Arguments; Arguments.Add(TEXT("ActorName"), FText::FromString(GetName())); FMessageLog("MapCheck").Error() ->AddToken(FUObjectToken::Create(this)) ->AddToken(FTextToken::Create(FText::Format(LOCTEXT("MapCheck_Message_InvalidLODActorNullActor", "{ActorName} : Actor is missing. The actor might have been removed. We recommend you to build LOD again. "), Arguments))) ->AddToken(FMapErrorToken::Create(FMapErrors::LODActorMissingActor)); } } } } void ALODActor::EditorApplyTranslation(const FVector& DeltaTranslation, bool bAltDown, bool bShiftDown, bool bCtrlDown) { } void ALODActor::EditorApplyRotation(const FRotator& DeltaRotation, bool bAltDown, bool bShiftDown, bool bCtrlDown) { } void ALODActor::EditorApplyScale(const FVector& DeltaScale, const FVector* PivotLocation, bool bAltDown, bool bShiftDown, bool bCtrlDown) { } void ALODActor::EditorApplyMirror(const FVector& MirrorScale, const FVector& PivotLocation) { } #endif // WITH_EDITOR FBox ALODActor::GetComponentsBoundingBox(bool bNonColliding) const { FBox BoundBox = Super::GetComponentsBoundingBox(bNonColliding); if (bNonColliding) { if (StaticMeshComponent && StaticMeshComponent->StaticMesh) { FBoxSphereBounds StaticBound = StaticMeshComponent->StaticMesh->GetBounds(); FBox StaticBoundBox(BoundBox.GetCenter()-StaticBound.BoxExtent, BoundBox.GetCenter()+StaticBound.BoxExtent); BoundBox += StaticBoundBox; } } return BoundBox; } #undef LOCTEXT_NAMESPACE
31.53202
246
0.745665
[ "mesh" ]
4feba20889a13fe28191d6290f2f805bfc5b1561
3,484
cpp
C++
src/2ls/graphml_witness_ext.cpp
FrNecas/2ls
9a77f9af2bf711e44c683683dfbc184a0a74bfa4
[ "BSD-4-Clause" ]
27
2016-12-01T03:17:10.000Z
2022-01-26T02:42:46.000Z
src/2ls/graphml_witness_ext.cpp
FrNecas/2ls
9a77f9af2bf711e44c683683dfbc184a0a74bfa4
[ "BSD-4-Clause" ]
109
2016-07-05T13:42:35.000Z
2022-01-14T15:01:59.000Z
src/2ls/graphml_witness_ext.cpp
FrNecas/2ls
9a77f9af2bf711e44c683683dfbc184a0a74bfa4
[ "BSD-4-Clause" ]
25
2016-04-20T23:25:05.000Z
2022-03-02T16:35:29.000Z
/*******************************************************************\ Module: SSA CFA extension for GraphML output Author: Peter Schrammel \*******************************************************************/ /// \file /// SSA CFA extension for GraphML output #include "graphml_witness_ext.h" /// proof witness TODO: works only for inlined programs void graphml_witness_extt::operator()( const summary_checker_baset &summary_checker) { irep_idt function_name=goto_functionst::entry_point(); const unwindable_local_SSAt &ssa= static_cast<const unwindable_local_SSAt &>( summary_checker.ssa_db.get(function_name)); const ssa_local_unwindert &ssa_unwinder= summary_checker.ssa_unwinder.get(function_name); graphml.key_values["sourcecodelang"]="C"; dynamic_cfgt cfg; if(summary_checker.summary_db.exists(function_name)) { const summaryt &summary=summary_checker.summary_db.get(function_name); cfg(ssa_unwinder, ssa, summary); } else { cfg(ssa_unwinder, ssa, summaryt()); } // CFG to CFA const graphmlt::node_indext sink=graphml.add_node(); graphml[sink].node_name="sink"; graphml[sink].is_violation=false; graphml[sink].has_invariant=false; std::vector<graphmlt::node_indext> index_map; index_map.resize(cfg.size()); for(std::size_t i=0; i<cfg.size(); ++i) { const source_locationt &source_location=cfg[i].id.pc->source_location; if(source_location.is_nil() || source_location.get_file().empty() || source_location.get_file()=="<built-in-additions>" || source_location.get_line().empty()) { index_map[i]=sink; continue; } const graphmlt::node_indext node=add_node(cfg[i], function_name); index_map[i]=node; } for(std::size_t i=0; i<cfg.size(); ++i) { for(const auto &e : cfg[i].out) { if(index_map[i]!=sink && index_map[e.first]!=sink) add_edge(index_map[i], cfg[i], index_map[e.first], cfg[e.first]); } } } graphmlt::node_indext graphml_witness_extt::add_node( const dynamic_cfg_nodet &cfg_node, const irep_idt &function_identifier) { const graphmlt::node_indext node=graphml.add_node(); graphml[node].node_name=cfg_node.id.to_string(); graphml[node].has_invariant=cfg_node.assumption.is_not_nil(); if(cfg_node.assumption.is_not_nil()) { std::ostringstream invs; invs << from_expr(ns, "", cfg_node.assumption); graphml[node].invariant=invs.str(); graphml[node].invariant_scope=id2string(function_identifier); } return node; } void graphml_witness_extt::add_edge( const graphmlt::node_indext &from, const dynamic_cfg_nodet &from_cfg_node, const graphmlt::node_indext &to, const dynamic_cfg_nodet &to_cfg_node) { const source_locationt &source_location=from_cfg_node.id.pc->source_location; xmlt edge("edge"); edge.set_attribute("source", graphml[from].node_name); edge.set_attribute("target", graphml[to].node_name); { xmlt &data_f=edge.new_element("data"); data_f.set_attribute("key", "originfile"); data_f.data=id2string(source_location.get_file()); xmlt &data_l=edge.new_element("data"); data_l.set_attribute("key", "startline"); data_l.data=id2string(source_location.get_line()); if(to_cfg_node.is_loop_head) { xmlt &data_l=edge.new_element("data"); data_l.set_attribute("key", "enterLoopHead"); data_l.data="true"; } } graphml[to].in[from].xml_node=edge; graphml[from].out[to].xml_node=edge; }
28.557377
79
0.681688
[ "vector" ]
4feea62d6afa9a144de0f3f5e93dcfad23965aea
19,993
cpp
C++
src/wallet/asyncrpcoperation_shieldcoinbase.cpp
reclaim-privacy/btq
7463d7411d05ea487eec3f2c457bdd82187697d9
[ "Unlicense" ]
5
2020-10-09T05:47:25.000Z
2022-03-22T08:38:48.000Z
src/wallet/asyncrpcoperation_shieldcoinbase.cpp
reclaim-privacy/btq
7463d7411d05ea487eec3f2c457bdd82187697d9
[ "Unlicense" ]
null
null
null
src/wallet/asyncrpcoperation_shieldcoinbase.cpp
reclaim-privacy/btq
7463d7411d05ea487eec3f2c457bdd82187697d9
[ "Unlicense" ]
1
2018-05-18T01:16:53.000Z
2018-05-18T01:16:53.000Z
// Copyright (c) 2017 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "asyncrpcqueue.h" #include "amount.h" #include "consensus/upgrades.h" #include "core_io.h" #include "init.h" #include "key_io.h" #include "main.h" #include "net.h" #include "netbase.h" #include "rpc/protocol.h" #include "rpc/server.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include "wallet.h" #include "walletdb.h" #include "script/interpreter.h" #include "utiltime.h" #include "zcash/IncrementalMerkleTree.hpp" #include "sodium.h" #include "miner.h" #include <array> #include <iostream> #include <chrono> #include <thread> #include <string> #include "asyncrpcoperation_shieldcoinbase.h" #include "paymentdisclosure.h" #include "paymentdisclosuredb.h" using namespace libzcash; extern uint64_t ASSETCHAINS_TIMELOCKGTE; static int find_output(UniValue obj, int n) { UniValue outputMapValue = find_value(obj, "outputmap"); if (!outputMapValue.isArray()) { throw JSONRPCError(RPC_WALLET_ERROR, "Missing outputmap for JoinSplit operation"); } UniValue outputMap = outputMapValue.get_array(); assert(outputMap.size() == ZC_NUM_JS_OUTPUTS); for (size_t i = 0; i < outputMap.size(); i++) { if (outputMap[i].get_int() == n) { return i; } } throw std::logic_error("n is not present in outputmap"); } AsyncRPCOperation_shieldcoinbase::AsyncRPCOperation_shieldcoinbase( TransactionBuilder builder, CMutableTransaction contextualTx, std::vector<ShieldCoinbaseUTXO> inputs, std::string toAddress, CAmount fee, UniValue contextInfo) : builder_(builder), tx_(contextualTx), inputs_(inputs), fee_(fee), contextinfo_(contextInfo) { assert(contextualTx.nVersion >= 2); // transaction format version must support vjoinsplit if (fee < 0 || fee > MAX_MONEY) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee is out of range"); } if (inputs.size() == 0) { throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Empty inputs"); } // Check the destination address is valid for this network i.e. not testnet being used on mainnet auto address = DecodePaymentAddress(toAddress); if (IsValidPaymentAddress(address)) { tozaddr_ = address; } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid to address"); } // Log the context info if (LogAcceptCategory("zrpcunsafe")) { LogPrint("zrpcunsafe", "%s: z_shieldcoinbase initialized (context=%s)\n", getId(), contextInfo.write()); } else { LogPrint("zrpc", "%s: z_shieldcoinbase initialized\n", getId()); } // Lock UTXOs lock_utxos(); // Enable payment disclosure if requested paymentDisclosureMode = fExperimentalMode && GetBoolArg("-paymentdisclosure", false); } AsyncRPCOperation_shieldcoinbase::~AsyncRPCOperation_shieldcoinbase() { } void AsyncRPCOperation_shieldcoinbase::main() { if (isCancelled()) { unlock_utxos(); // clean up return; } set_state(OperationStatus::EXECUTING); start_execution_clock(); bool success = false; #ifdef ENABLE_MINING #ifdef ENABLE_WALLET GenerateBitcoins(false, NULL, 0); #else GenerateBitcoins(false, 0); #endif #endif try { success = main_impl(); } catch (const UniValue& objError) { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); set_error_code(code); set_error_message(message); } catch (const runtime_error& e) { set_error_code(-1); set_error_message("runtime error: " + string(e.what())); } catch (const logic_error& e) { set_error_code(-1); set_error_message("logic error: " + string(e.what())); } catch (const exception& e) { set_error_code(-1); set_error_message("general exception: " + string(e.what())); } catch (...) { set_error_code(-2); set_error_message("unknown error"); } #ifdef ENABLE_MINING #ifdef ENABLE_WALLET GenerateBitcoins(GetBoolArg("-gen",false), pwalletMain, GetArg("-genproclimit", 0)); #else GenerateBitcoins(GetBoolArg("-gen",false), GetArg("-genproclimit", 0)); #endif #endif stop_execution_clock(); if (success) { set_state(OperationStatus::SUCCESS); } else { set_state(OperationStatus::FAILED); } std::string s = strprintf("%s: z_shieldcoinbase finished (status=%s", getId(), getStateAsString()); if (success) { s += strprintf(", txid=%s)\n", tx_.GetHash().ToString()); } else { s += strprintf(", error=%s)\n", getErrorMessage()); } LogPrintf("%s",s); unlock_utxos(); // clean up // !!! Payment disclosure START if (success && paymentDisclosureMode && paymentDisclosureData_.size()>0) { uint256 txidhash = tx_.GetHash(); std::shared_ptr<PaymentDisclosureDB> db = PaymentDisclosureDB::sharedInstance(); for (PaymentDisclosureKeyInfo p : paymentDisclosureData_) { p.first.hash = txidhash; if (!db->Put(p.first, p.second)) { LogPrint("paymentdisclosure", "%s: Payment Disclosure: Error writing entry to database for key %s\n", getId(), p.first.ToString()); } else { LogPrint("paymentdisclosure", "%s: Payment Disclosure: Successfully added entry to database for key %s\n", getId(), p.first.ToString()); } } } // !!! Payment disclosure END } bool AsyncRPCOperation_shieldcoinbase::main_impl() { CAmount minersFee = fee_; size_t numInputs = inputs_.size(); // Check mempooltxinputlimit to avoid creating a transaction which the local mempool rejects size_t limit = (size_t)GetArg("-mempooltxinputlimit", 0); { LOCK(cs_main); if (NetworkUpgradeActive(chainActive.Height() + 1, Params().GetConsensus(), Consensus::UPGRADE_OVERWINTER)) { limit = 0; } } if (limit>0 && numInputs > limit) { throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Number of inputs %d is greater than mempooltxinputlimit of %d", numInputs, limit)); } CAmount targetAmount = 0; for (ShieldCoinbaseUTXO & utxo : inputs_) { targetAmount += utxo.amount; } if (targetAmount <= minersFee) { throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strprintf("Insufficient coinbase funds, have %s and miners fee is %s", FormatMoney(targetAmount), FormatMoney(minersFee))); } CAmount sendAmount = targetAmount - minersFee; LogPrint("zrpc", "%s: spending %s to shield %s with fee %s\n", getId(), FormatMoney(targetAmount), FormatMoney(sendAmount), FormatMoney(minersFee)); return boost::apply_visitor(ShieldToAddress(this, sendAmount), tozaddr_); } bool ShieldToAddress::operator()(const libzcash::SproutPaymentAddress &zaddr) const { // update the transaction with these inputs CMutableTransaction rawTx(m_op->tx_); for (ShieldCoinbaseUTXO & t : m_op->inputs_) { CTxIn in(COutPoint(t.txid, t.vout)); if ((uint64_t)t.amount >= ASSETCHAINS_TIMELOCKGTE) in.nSequence = 0xfffffffe; rawTx.vin.push_back(in); } m_op->tx_ = CTransaction(rawTx); // Prepare raw transaction to handle JoinSplits CMutableTransaction mtx(m_op->tx_); crypto_sign_keypair(m_op->joinSplitPubKey_.begin(), m_op->joinSplitPrivKey_); mtx.joinSplitPubKey = m_op->joinSplitPubKey_; m_op->tx_ = CTransaction(mtx); // Create joinsplit UniValue obj(UniValue::VOBJ); ShieldCoinbaseJSInfo info; info.vpub_old = sendAmount; info.vpub_new = 0; JSOutput jso = JSOutput(zaddr, sendAmount); info.vjsout.push_back(jso); obj = m_op->perform_joinsplit(info); m_op->sign_send_raw_transaction(obj); return true; } extern UniValue signrawtransaction(const UniValue& params, bool fHelp); extern UniValue sendrawtransaction(const UniValue& params, bool fHelp); bool ShieldToAddress::operator()(const libzcash::SaplingPaymentAddress &zaddr) const { m_op->builder_.SetFee(m_op->fee_); // Sending from a t-address, which we don't have an ovk for. Instead, // generate a common one from the HD seed. This ensures the data is // recoverable, while keeping it logically separate from the ZIP 32 // Sapling key hierarchy, which the user might not be using. HDSeed seed; if (!pwalletMain->GetHDSeed(seed)) { throw JSONRPCError( RPC_WALLET_ERROR, "CWallet::GenerateNewSaplingZKey(): HD seed not found"); } uint256 ovk = ovkForShieldingFromTaddr(seed); // Add transparent inputs for (auto t : m_op->inputs_) { m_op->builder_.SetLockTime((uint32_t)(chainActive.Height())); m_op->builder_.AddTransparentInput(COutPoint(t.txid, t.vout), t.scriptPubKey, t.amount, 0xfffffffe); /* if ((uint64_t)t.amount >= ASSETCHAINS_TIMELOCKGTE) { m_op->builder_.SetLockTime((uint32_t)(chainActive.Height())); m_op->builder_.AddTransparentInput(COutPoint(t.txid, t.vout), t.scriptPubKey, t.amount, 0xfffffffe); } else { m_op->builder_.AddTransparentInput(COutPoint(t.txid, t.vout), t.scriptPubKey, t.amount); } */ } // Send all value to the target z-addr m_op->builder_.SendChangeTo(zaddr, ovk); // Build the transaction auto maybe_tx = m_op->builder_.Build(); if (!maybe_tx) { throw JSONRPCError(RPC_WALLET_ERROR, "Failed to build transaction."); } m_op->tx_ = maybe_tx.get(); // Send the transaction // TODO: Use CWallet::CommitTransaction instead of sendrawtransaction auto signedtxn = EncodeHexTx(m_op->tx_); if (!m_op->testmode) { UniValue params = UniValue(UniValue::VARR); params.push_back(signedtxn); UniValue sendResultValue = sendrawtransaction(params, false); if (sendResultValue.isNull()) { throw JSONRPCError(RPC_WALLET_ERROR, "sendrawtransaction did not return an error or a txid."); } auto txid = sendResultValue.get_str(); UniValue o(UniValue::VOBJ); o.push_back(Pair("txid", txid)); m_op->set_result(o); } else { // Test mode does not send the transaction to the network. UniValue o(UniValue::VOBJ); o.push_back(Pair("test", 1)); o.push_back(Pair("txid", m_op->tx_.GetHash().ToString())); o.push_back(Pair("hex", signedtxn)); m_op->set_result(o); } return true; } bool ShieldToAddress::operator()(const libzcash::InvalidEncoding& no) const { return false; } /** * Sign and send a raw transaction. * Raw transaction as hex string should be in object field "rawtxn" */ void AsyncRPCOperation_shieldcoinbase::sign_send_raw_transaction(UniValue obj) { // Sign the raw transaction UniValue rawtxnValue = find_value(obj, "rawtxn"); if (rawtxnValue.isNull()) { throw JSONRPCError(RPC_WALLET_ERROR, "Missing hex data for raw transaction"); } std::string rawtxn = rawtxnValue.get_str(); UniValue params = UniValue(UniValue::VARR); params.push_back(rawtxn); UniValue signResultValue = signrawtransaction(params, false); UniValue signResultObject = signResultValue.get_obj(); UniValue completeValue = find_value(signResultObject, "complete"); bool complete = completeValue.get_bool(); if (!complete) { // TODO: #1366 Maybe get "errors" and print array vErrors into a string throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Failed to sign transaction"); } UniValue hexValue = find_value(signResultObject, "hex"); if (hexValue.isNull()) { throw JSONRPCError(RPC_WALLET_ERROR, "Missing hex data for signed transaction"); } std::string signedtxn = hexValue.get_str(); // Send the signed transaction if (!testmode) { params.clear(); params.setArray(); params.push_back(signedtxn); UniValue sendResultValue = sendrawtransaction(params, false); if (sendResultValue.isNull()) { throw JSONRPCError(RPC_WALLET_ERROR, "Send raw transaction did not return an error or a txid."); } std::string txid = sendResultValue.get_str(); UniValue o(UniValue::VOBJ); o.push_back(Pair("txid", txid)); set_result(o); } else { // Test mode does not send the transaction to the network. CDataStream stream(ParseHex(signedtxn), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; UniValue o(UniValue::VOBJ); o.push_back(Pair("test", 1)); o.push_back(Pair("txid", tx.GetHash().ToString())); o.push_back(Pair("hex", signedtxn)); set_result(o); } // Keep the signed transaction so we can hash to the same txid CDataStream stream(ParseHex(signedtxn), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; tx_ = tx; } UniValue AsyncRPCOperation_shieldcoinbase::perform_joinsplit(ShieldCoinbaseJSInfo & info) { uint32_t consensusBranchId; uint256 anchor; { LOCK(cs_main); consensusBranchId = CurrentEpochBranchId(chainActive.Height() + 1, Params().GetConsensus()); anchor = pcoinsTip->GetBestAnchor(SPROUT); } if (anchor.IsNull()) { throw std::runtime_error("anchor is null"); } // Make sure there are two inputs and two outputs while (info.vjsin.size() < ZC_NUM_JS_INPUTS) { info.vjsin.push_back(JSInput()); } while (info.vjsout.size() < ZC_NUM_JS_OUTPUTS) { info.vjsout.push_back(JSOutput()); } if (info.vjsout.size() != ZC_NUM_JS_INPUTS || info.vjsin.size() != ZC_NUM_JS_OUTPUTS) { throw runtime_error("unsupported joinsplit input/output counts"); } CMutableTransaction mtx(tx_); LogPrint("zrpcunsafe", "%s: creating joinsplit at index %d (vpub_old=%s, vpub_new=%s, in[0]=%s, in[1]=%s, out[0]=%s, out[1]=%s)\n", getId(), tx_.vjoinsplit.size(), FormatMoney(info.vpub_old), FormatMoney(info.vpub_new), FormatMoney(info.vjsin[0].note.value()), FormatMoney(info.vjsin[1].note.value()), FormatMoney(info.vjsout[0].value), FormatMoney(info.vjsout[1].value) ); // Generate the proof, this can take over a minute. std::array<libzcash::JSInput, ZC_NUM_JS_INPUTS> inputs {info.vjsin[0], info.vjsin[1]}; std::array<libzcash::JSOutput, ZC_NUM_JS_OUTPUTS> outputs {info.vjsout[0], info.vjsout[1]}; std::array<size_t, ZC_NUM_JS_INPUTS> inputMap; std::array<size_t, ZC_NUM_JS_OUTPUTS> outputMap; uint256 esk; // payment disclosure - secret JSDescription jsdesc = JSDescription::Randomized( mtx.fOverwintered && (mtx.nVersion >= SAPLING_TX_VERSION), *pzcashParams, joinSplitPubKey_, anchor, inputs, outputs, inputMap, outputMap, info.vpub_old, info.vpub_new, !this->testmode, &esk); // parameter expects pointer to esk, so pass in address { auto verifier = libzcash::ProofVerifier::Strict(); if (!(jsdesc.Verify(*pzcashParams, verifier, joinSplitPubKey_))) { throw std::runtime_error("error verifying joinsplit"); } } mtx.vjoinsplit.push_back(jsdesc); // Empty output script. CScript scriptCode; CTransaction signTx(mtx); uint256 dataToBeSigned = SignatureHash(scriptCode, signTx, NOT_AN_INPUT, SIGHASH_ALL, 0, consensusBranchId); // Add the signature if (!(crypto_sign_detached(&mtx.joinSplitSig[0], NULL, dataToBeSigned.begin(), 32, joinSplitPrivKey_ ) == 0)) { throw std::runtime_error("crypto_sign_detached failed"); } // Sanity check if (!(crypto_sign_verify_detached(&mtx.joinSplitSig[0], dataToBeSigned.begin(), 32, mtx.joinSplitPubKey.begin() ) == 0)) { throw std::runtime_error("crypto_sign_verify_detached failed"); } CTransaction rawTx(mtx); tx_ = rawTx; CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; std::string encryptedNote1; std::string encryptedNote2; { CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION); ss2 << ((unsigned char) 0x00); ss2 << jsdesc.ephemeralKey; ss2 << jsdesc.ciphertexts[0]; ss2 << jsdesc.h_sig(*pzcashParams, joinSplitPubKey_); encryptedNote1 = HexStr(ss2.begin(), ss2.end()); } { CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION); ss2 << ((unsigned char) 0x01); ss2 << jsdesc.ephemeralKey; ss2 << jsdesc.ciphertexts[1]; ss2 << jsdesc.h_sig(*pzcashParams, joinSplitPubKey_); encryptedNote2 = HexStr(ss2.begin(), ss2.end()); } UniValue arrInputMap(UniValue::VARR); UniValue arrOutputMap(UniValue::VARR); for (size_t i = 0; i < ZC_NUM_JS_INPUTS; i++) { arrInputMap.push_back(static_cast<uint64_t>(inputMap[i])); } for (size_t i = 0; i < ZC_NUM_JS_OUTPUTS; i++) { arrOutputMap.push_back(static_cast<uint64_t>(outputMap[i])); } // !!! Payment disclosure START unsigned char buffer[32] = {0}; memcpy(&buffer[0], &joinSplitPrivKey_[0], 32); // private key in first half of 64 byte buffer std::vector<unsigned char> vch(&buffer[0], &buffer[0] + 32); uint256 joinSplitPrivKey = uint256(vch); size_t js_index = tx_.vjoinsplit.size() - 1; uint256 placeholder; for (int i = 0; i < ZC_NUM_JS_OUTPUTS; i++) { uint8_t mapped_index = outputMap[i]; // placeholder for txid will be filled in later when tx has been finalized and signed. PaymentDisclosureKey pdKey = {placeholder, js_index, mapped_index}; JSOutput output = outputs[mapped_index]; libzcash::SproutPaymentAddress zaddr = output.addr; // randomized output PaymentDisclosureInfo pdInfo = {PAYMENT_DISCLOSURE_VERSION_EXPERIMENTAL, esk, joinSplitPrivKey, zaddr}; paymentDisclosureData_.push_back(PaymentDisclosureKeyInfo(pdKey, pdInfo)); LogPrint("paymentdisclosure", "%s: Payment Disclosure: js=%d, n=%d, zaddr=%s\n", getId(), js_index, int(mapped_index), EncodePaymentAddress(zaddr)); } // !!! Payment disclosure END UniValue obj(UniValue::VOBJ); obj.push_back(Pair("encryptednote1", encryptedNote1)); obj.push_back(Pair("encryptednote2", encryptedNote2)); obj.push_back(Pair("rawtxn", HexStr(ss.begin(), ss.end()))); obj.push_back(Pair("inputmap", arrInputMap)); obj.push_back(Pair("outputmap", arrOutputMap)); return obj; } /** * Override getStatus() to append the operation's context object to the default status object. */ UniValue AsyncRPCOperation_shieldcoinbase::getStatus() const { UniValue v = AsyncRPCOperation::getStatus(); if (contextinfo_.isNull()) { return v; } UniValue obj = v.get_obj(); obj.push_back(Pair("method", "z_shieldcoinbase")); obj.push_back(Pair("params", contextinfo_ )); return obj; } /** * Lock input utxos */ void AsyncRPCOperation_shieldcoinbase::lock_utxos() { LOCK2(cs_main, pwalletMain->cs_wallet); for (auto utxo : inputs_) { COutPoint outpt(utxo.txid, utxo.vout); pwalletMain->LockCoin(outpt); } } /** * Unlock input utxos */ void AsyncRPCOperation_shieldcoinbase::unlock_utxos() { LOCK2(cs_main, pwalletMain->cs_wallet); for (auto utxo : inputs_) { COutPoint outpt(utxo.txid, utxo.vout); pwalletMain->UnlockCoin(outpt); } }
33.658249
156
0.654029
[ "object", "vector" ]
4fef6fb9b2c51dc63fe67ef1c4d03afe30aac723
2,244
cpp
C++
atcoder/abc185/c.cpp
polylogarithm/cp
426cb6f6ba389ff5f492e5bc2e957aac128781b5
[ "MIT" ]
null
null
null
atcoder/abc185/c.cpp
polylogarithm/cp
426cb6f6ba389ff5f492e5bc2e957aac128781b5
[ "MIT" ]
null
null
null
atcoder/abc185/c.cpp
polylogarithm/cp
426cb6f6ba389ff5f492e5bc2e957aac128781b5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define pb push_back #define all(x) (x).begin(), (x).end() #define um unordered_map #define pq priority_queue #define sz(x) ((int)(x).size()) #define fi first #define se second #define endl '\n' typedef vector<int> vi; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; mt19937 mrand(random_device{}()); const ll mod = 1000000007; int rnd(int x) { return mrand() % x;} ll mulmod(ll a, ll b) {ll res = 0; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = (res + a) % mod; a = 2 * a % mod;} return res;} ll powmod(ll a, ll b) {ll res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = res * a % mod; a = a * a % mod;} return res;} ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;} //head const int N = 5010; int primes[N], cnt; int sum[N]; bool st[N]; int p; //求组合数 C(l-1,11) 不取模 //直接套板子即可 void get_primes(int n) { for (int i = 2; i <= n; i++) { if (!st[i]) primes[cnt++] = i; for (int j = 0; primes[j] <= n / i; j++) { st[primes[j] * i] = 1; if (i % primes[j] == 0) break; } } } int get(int n) { //求出n!中包含的p的个数 int res = 0; while (n) { res += n / p; n /= p; } return res; } ll qmi(int a, int b) { ll res = 1; while (b) { if (b & 1) res *= a; b >>= 1; a = a * a; } return res; } //高精度乘法 vector<int> mul(vector<int> &a, int b) { vector<int> c; int t = 0; for (int i = 0; i < a.size(); i++) { t += a[i] * b; c.push_back(t % 10); t /= 10; } while (t) { c.push_back(t % 10); t /= 10; } return c; } void solve() { int a, b; cin >> a; a -= 1; b = 11; get_primes(a); //求出1 ~ a 中所有质数 for (int i = 0; i < cnt; i++) { p = primes[i]; sum[i] = get(a) - get(b) - get(a - b); //p的次数,0就相当于不减 } vector<int> res; //高精度乘法 res.push_back(1); for (int i = 0; i < cnt; i++) res = mul(res, qmi(primes[i], sum[i])); //输出答案 for (int i = res.size() - 1 ; i >= 0; i--) cout << res[i]; cout << endl; } int main() { int t = 1; // cin >> t; while (t --) solve(); return 0; }
22.897959
144
0.475936
[ "vector" ]
4fefdea077b6cfbeb6d42716585987c76a545983
2,596
cpp
C++
Userland/Libraries/LibJS/Runtime/SymbolConstructor.cpp
diego-gt/serenity
52a1be5eae81bd2eea767cfce569e089ec1bb3df
[ "BSD-2-Clause" ]
1
2021-02-19T08:49:51.000Z
2021-02-19T08:49:51.000Z
Userland/Libraries/LibJS/Runtime/SymbolConstructor.cpp
diego-gt/serenity
52a1be5eae81bd2eea767cfce569e089ec1bb3df
[ "BSD-2-Clause" ]
null
null
null
Userland/Libraries/LibJS/Runtime/SymbolConstructor.cpp
diego-gt/serenity
52a1be5eae81bd2eea767cfce569e089ec1bb3df
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibJS/Runtime/Error.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/SymbolConstructor.h> namespace JS { SymbolConstructor::SymbolConstructor(GlobalObject& global_object) : NativeFunction(vm().names.Symbol.as_string(), *global_object.function_prototype()) { } void SymbolConstructor::initialize(GlobalObject& global_object) { auto& vm = this->vm(); NativeFunction::initialize(global_object); // 20.4.2.9 Symbol.prototype, https://tc39.es/ecma262/#sec-symbol.prototype define_direct_property(vm.names.prototype, global_object.symbol_prototype(), 0); u8 attr = Attribute::Writable | Attribute::Configurable; define_old_native_function(vm.names.for_, for_, 1, attr); define_old_native_function(vm.names.keyFor, key_for, 1, attr); #define __JS_ENUMERATE(SymbolName, snake_name) \ define_direct_property(vm.names.SymbolName, vm.well_known_symbol_##snake_name(), 0); JS_ENUMERATE_WELL_KNOWN_SYMBOLS #undef __JS_ENUMERATE define_direct_property(vm.names.length, Value(0), Attribute::Configurable); } SymbolConstructor::~SymbolConstructor() { } // 20.4.1.1 Symbol ( [ description ] ), https://tc39.es/ecma262/#sec-symbol-description ThrowCompletionOr<Value> SymbolConstructor::call() { if (vm().argument(0).is_undefined()) return js_symbol(heap(), {}, false); return js_symbol(heap(), TRY(vm().argument(0).to_string(global_object())), false); } // 20.4.1.1 Symbol ( [ description ] ), https://tc39.es/ecma262/#sec-symbol-description ThrowCompletionOr<Object*> SymbolConstructor::construct(FunctionObject&) { return vm().throw_completion<TypeError>(global_object(), ErrorType::NotAConstructor, "Symbol"); } // 20.4.2.2 Symbol.for ( key ), https://tc39.es/ecma262/#sec-symbol.for JS_DEFINE_OLD_NATIVE_FUNCTION(SymbolConstructor::for_) { auto description = TRY_OR_DISCARD(vm.argument(0).to_string(global_object)); return global_object.vm().get_global_symbol(description); } // 20.4.2.6 Symbol.keyFor ( sym ), https://tc39.es/ecma262/#sec-symbol.keyfor JS_DEFINE_OLD_NATIVE_FUNCTION(SymbolConstructor::key_for) { auto argument = vm.argument(0); if (!argument.is_symbol()) { vm.throw_exception<TypeError>(global_object, ErrorType::NotASymbol, argument.to_string_without_side_effects()); return {}; } auto& symbol = argument.as_symbol(); if (symbol.is_global()) return js_string(vm, symbol.description()); return js_undefined(); } }
32.45
119
0.73151
[ "object" ]
4ff2c2e8edb41d6da166579cfc737b6a0101a86e
3,343
cpp
C++
src/gpu/nvidia/cudnn_eltwise.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
971
2020-04-03T19:48:05.000Z
2022-03-31T19:42:43.000Z
src/gpu/nvidia/cudnn_eltwise.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
583
2020-04-04T02:37:25.000Z
2022-03-31T00:12:03.000Z
src/gpu/nvidia/cudnn_eltwise.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
295
2020-04-03T20:07:00.000Z
2022-03-30T13:10:15.000Z
/******************************************************************************* * Copyright 2020-2021 Intel Corporation * Copyright 2020 Codeplay Software Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "gpu/nvidia/cudnn_eltwise.hpp" #include "gpu/nvidia/sycl_cuda_scoped_context.hpp" #include "gpu/nvidia/sycl_cuda_stream.hpp" #include "sycl/sycl_buffer_memory_storage.hpp" namespace dnnl { namespace impl { namespace gpu { namespace nvidia { status_t cudnn_eltwise_fwd_t::execute(const exec_ctx_t &ctx) const { if (memory_desc_wrapper(pd()->src_md()).has_zero_dim()) return status::success; nvidia::sycl_cuda_stream_t *cuda_stream = utils::downcast<nvidia::sycl_cuda_stream_t *>(ctx.stream()); return cuda_stream->interop_task([&](::sycl::handler &cgh) { auto src_acc = CTX_IN_ACCESSOR(DNNL_ARG_SRC); auto dst_acc = CTX_OUT_ACCESSOR(DNNL_ARG_DST); compat::host_task(cgh, [=](const compat::interop_handle &ih) { std::vector<void *> args; auto &sycl_engine = *utils::downcast<sycl_cuda_engine_t *>( cuda_stream->engine()); auto sc = cuda_sycl_scoped_context_handler_t(sycl_engine); auto handle = cuda_stream->get_cudnn_handle(); args.push_back(sc.memory<void *>(ih, src_acc)); args.push_back(sc.memory<void *>(ih, dst_acc)); pd()->eltwise_fwd_impl_->execute(handle, args.data(), args.size()); }); }); } status_t cudnn_eltwise_bwd_t::execute(const exec_ctx_t &ctx) const { if (memory_desc_wrapper(pd()->src_md()).has_zero_dim()) return status::success; nvidia::sycl_cuda_stream_t *cuda_stream = utils::downcast<nvidia::sycl_cuda_stream_t *>(ctx.stream()); return cuda_stream->interop_task([&](::sycl::handler &cgh) { auto src_acc = CTX_IN_ACCESSOR(DNNL_ARG_SRC); auto diff_dst_acc = CTX_IN_ACCESSOR(DNNL_ARG_DIFF_DST); auto diff_src_acc = CTX_OUT_ACCESSOR(DNNL_ARG_DIFF_SRC); compat::host_task(cgh, [=](const compat::interop_handle &ih) { std::vector<void *> args; auto &sycl_engine = *utils::downcast<sycl_cuda_engine_t *>( cuda_stream->engine()); auto sc = cuda_sycl_scoped_context_handler_t(sycl_engine); auto handle = cuda_stream->get_cudnn_handle(); args.push_back(sc.memory<void *>(ih, src_acc)); args.push_back(sc.memory<void *>(ih, diff_dst_acc)); args.push_back(sc.memory<void *>(ih, diff_src_acc)); pd()->eltwise_bwd_impl_->execute(handle, args.data(), args.size()); }); }); } } // namespace nvidia } // namespace gpu } // namespace impl } // namespace dnnl
38.872093
80
0.639246
[ "vector" ]
4ff4090a1c60115505b7ef428e37f9c2ca2cfe13
2,449
cpp
C++
rellic/AST/NestedScopeCombiner.cpp
rustomas/rellic
b7845a79dcd600f1cc63752a9ee412058620e13c
[ "Apache-2.0" ]
null
null
null
rellic/AST/NestedScopeCombiner.cpp
rustomas/rellic
b7845a79dcd600f1cc63752a9ee412058620e13c
[ "Apache-2.0" ]
null
null
null
rellic/AST/NestedScopeCombiner.cpp
rustomas/rellic
b7845a79dcd600f1cc63752a9ee412058620e13c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gflags/gflags.h> #include <glog/logging.h> #include "rellic/AST/NestedScopeCombiner.h" #include "rellic/AST/Util.h" namespace rellic { char NestedScopeCombiner::ID = 0; NestedScopeCombiner::NestedScopeCombiner(clang::ASTContext &ctx, rellic::IRToASTVisitor &ast_gen) : ModulePass(NestedScopeCombiner::ID), ast_ctx(&ctx), ast_gen(&ast_gen) {} bool NestedScopeCombiner::VisitIfStmt(clang::IfStmt *ifstmt) { // DLOG(INFO) << "VisitIfStmt"; // Determine whether `cond` is a constant expression that is always true and // `ifstmt` should be replaced by `then` in it's parent nodes. llvm::APSInt val; bool is_const = ifstmt->getCond()->isIntegerConstantExpr(val, *ast_ctx); if (is_const && val.getBoolValue()) { substitutions[ifstmt] = ifstmt->getThen(); } return true; } bool NestedScopeCombiner::VisitCompoundStmt(clang::CompoundStmt *compound) { // DLOG(INFO) << "VisitCompoundStmt"; bool has_compound = false; std::vector<clang::Stmt *> new_body; for (auto stmt : compound->body()) { if (auto child = llvm::dyn_cast<clang::CompoundStmt>(stmt)) { new_body.insert(new_body.end(), child->body_begin(), child->body_end()); has_compound = true; } else { new_body.push_back(stmt); } } if (has_compound) { substitutions[compound] = CreateCompoundStmt(*ast_ctx, new_body); } return true; } bool NestedScopeCombiner::runOnModule(llvm::Module &module) { LOG(INFO) << "Combining nested scopes"; Initialize(); TraverseDecl(ast_ctx->getTranslationUnitDecl()); return changed; } llvm::ModulePass *createNestedScopeCombinerPass(clang::ASTContext &ctx, rellic::IRToASTVisitor &gen) { return new NestedScopeCombiner(ctx, gen); } } // namespace rellic
32.223684
78
0.685994
[ "vector" ]
4ff41aaff352a853267ebf922f57e1a01eb4b804
13,247
cc
C++
content/browser/frame_host/render_frame_host_impl.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-04-27T20:21:55.000Z
2019-04-27T20:21:55.000Z
content/browser/frame_host/render_frame_host_impl.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/frame_host/render_frame_host_impl.cc
hokein/chromium
69328672dd0c5b93e0b65fc344feb11bbdc37b6b
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/frame_host/render_frame_host_impl.h" #include "base/containers/hash_tables.h" #include "base/lazy_instance.h" #include "base/metrics/user_metrics_action.h" #include "content/browser/frame_host/cross_process_frame_connector.h" #include "content/browser/frame_host/frame_tree.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/navigator.h" #include "content/browser/frame_host/render_frame_host_delegate.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/common/frame_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/user_metrics.h" #include "content/public/common/url_constants.h" #include "url/gurl.h" namespace content { // The (process id, routing id) pair that identifies one RenderFrame. typedef std::pair<int32, int32> RenderFrameHostID; typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*> RoutingIDFrameMap; static base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map = LAZY_INSTANCE_INITIALIZER; RenderFrameHost* RenderFrameHost::FromID(int render_process_id, int render_frame_id) { return RenderFrameHostImpl::FromID(render_process_id, render_frame_id); } // static RenderFrameHostImpl* RenderFrameHostImpl::FromID( int process_id, int routing_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer(); RoutingIDFrameMap::iterator it = frames->find( RenderFrameHostID(process_id, routing_id)); return it == frames->end() ? NULL : it->second; } RenderFrameHostImpl::RenderFrameHostImpl( RenderViewHostImpl* render_view_host, RenderFrameHostDelegate* delegate, FrameTree* frame_tree, FrameTreeNode* frame_tree_node, int routing_id, bool is_swapped_out) : render_view_host_(render_view_host), delegate_(delegate), cross_process_frame_connector_(NULL), frame_tree_(frame_tree), frame_tree_node_(frame_tree_node), routing_id_(routing_id), is_swapped_out_(is_swapped_out) { frame_tree_->RegisterRenderFrameHost(this); GetProcess()->AddRoute(routing_id_, this); g_routing_id_frame_map.Get().insert(std::make_pair( RenderFrameHostID(GetProcess()->GetID(), routing_id_), this)); } RenderFrameHostImpl::~RenderFrameHostImpl() { GetProcess()->RemoveRoute(routing_id_); g_routing_id_frame_map.Get().erase( RenderFrameHostID(GetProcess()->GetID(), routing_id_)); if (delegate_) delegate_->RenderFrameDeleted(this); // Notify the FrameTree that this RFH is going away, allowing it to shut down // the corresponding RenderViewHost if it is no longer needed. frame_tree_->UnregisterRenderFrameHost(this); } SiteInstance* RenderFrameHostImpl::GetSiteInstance() { return render_view_host_->GetSiteInstance(); } RenderProcessHost* RenderFrameHostImpl::GetProcess() { // TODO(nasko): This should return its own process, once we have working // cross-process navigation for subframes. return render_view_host_->GetProcess(); } int RenderFrameHostImpl::GetRoutingID() { return routing_id_; } gfx::NativeView RenderFrameHostImpl::GetNativeView() { RenderWidgetHostView* view = render_view_host_->GetView(); if (!view) return NULL; return view->GetNativeView(); } void RenderFrameHostImpl::NotifyContextMenuClosed( const CustomContextMenuContext& context) { Send(new FrameMsg_ContextMenuClosed(routing_id_, context)); } void RenderFrameHostImpl::ExecuteCustomContextMenuCommand( int action, const CustomContextMenuContext& context) { Send(new FrameMsg_CustomContextMenuAction(routing_id_, context, action)); } RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() { return render_view_host_; } bool RenderFrameHostImpl::Send(IPC::Message* message) { return GetProcess()->Send(message); } bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { if (delegate_->OnMessageReceived(this, msg)) return true; if (cross_process_frame_connector_ && cross_process_frame_connector_->OnMessageReceived(msg)) return true; bool handled = true; bool msg_is_ok = true; IPC_BEGIN_MESSAGE_MAP_EX(RenderFrameHostImpl, msg, msg_is_ok) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame, OnDidStartProvisionalLoadForFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidRedirectProvisionalLoad, OnDidRedirectProvisionalLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad, OnNavigate(msg)) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_END_MESSAGE_MAP_EX() if (!msg_is_ok) { // The message had a handler, but its de-serialization failed. // Kill the renderer. RecordAction(base::UserMetricsAction("BadMessageTerminate_RFH")); GetProcess()->ReceivedBadMessage(); } return handled; } void RenderFrameHostImpl::Init() { GetProcess()->ResumeRequestsForView(routing_id_); } void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id, const std::string& frame_name) { RenderFrameHostImpl* new_frame = frame_tree_->AddFrame( frame_tree_node_, new_routing_id, frame_name); if (delegate_) delegate_->RenderFrameCreated(new_frame); } void RenderFrameHostImpl::OnDetach() { frame_tree_->RemoveFrame(frame_tree_node_); } void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame( int parent_routing_id, bool is_main_frame, const GURL& url) { frame_tree_node_->navigator()->DidStartProvisionalLoad( this, parent_routing_id, is_main_frame, url); } void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError( const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) { frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params); } void RenderFrameHostImpl::OnDidFailLoadWithError( const GURL& url, bool is_main_frame, int error_code, const base::string16& error_description) { GURL validated_url(url); GetProcess()->FilterURL(false, &validated_url); frame_tree_node_->navigator()->DidFailLoadWithError( this, validated_url, is_main_frame, error_code, error_description); } void RenderFrameHostImpl::OnDidRedirectProvisionalLoad( int32 page_id, const GURL& source_url, const GURL& target_url) { frame_tree_node_->navigator()->DidRedirectProvisionalLoad( this, page_id, source_url, target_url); } // Called when the renderer navigates. For every frame loaded, we'll get this // notification containing parameters identifying the navigation. // // Subframes are identified by the page transition type. For subframes loaded // as part of a wider page load, the page_id will be the same as for the top // level frame. If the user explicitly requests a subframe navigation, we will // get a new page_id because we need to create a new navigation entry for that // action. void RenderFrameHostImpl::OnNavigate(const IPC::Message& msg) { // Read the parameters out of the IPC message directly to avoid making another // copy when we filter the URLs. PickleIterator iter(msg); FrameHostMsg_DidCommitProvisionalLoad_Params validated_params; if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>:: Read(&msg, &iter, &validated_params)) return; // If we're waiting for a cross-site beforeunload ack from this renderer and // we receive a Navigate message from the main frame, then the renderer was // navigating already and sent it before hearing the ViewMsg_Stop message. // We do not want to cancel the pending navigation in this case, since the // old page will soon be stopped. Instead, treat this as a beforeunload ack // to allow the pending navigation to continue. if (render_view_host_->is_waiting_for_beforeunload_ack_ && render_view_host_->unload_ack_is_for_cross_site_transition_ && PageTransitionIsMainFrame(validated_params.transition)) { render_view_host_->OnShouldCloseACK( true, render_view_host_->send_should_close_start_time_, base::TimeTicks::Now()); return; } // If we're waiting for an unload ack from this renderer and we receive a // Navigate message, then the renderer was navigating before it received the // unload request. It will either respond to the unload request soon or our // timer will expire. Either way, we should ignore this message, because we // have already committed to closing this renderer. if (render_view_host_->is_waiting_for_unload_ack_) return; RenderProcessHost* process = GetProcess(); // Attempts to commit certain off-limits URL should be caught more strictly // than our FilterURL checks below. If a renderer violates this policy, it // should be killed. if (!CanCommitURL(validated_params.url)) { VLOG(1) << "Blocked URL " << validated_params.url.spec(); validated_params.url = GURL(kAboutBlankURL); RecordAction(base::UserMetricsAction("CanCommitURL_BlockedAndKilled")); // Kills the process. process->ReceivedBadMessage(); } // Now that something has committed, we don't need to track whether the // initial page has been accessed. render_view_host_->has_accessed_initial_document_ = false; // Without this check, an evil renderer can trick the browser into creating // a navigation entry for a banned URL. If the user clicks the back button // followed by the forward button (or clicks reload, or round-trips through // session restore, etc), we'll think that the browser commanded the // renderer to load the URL and grant the renderer the privileges to request // the URL. To prevent this attack, we block the renderer from inserting // banned URLs into the navigation controller in the first place. process->FilterURL(false, &validated_params.url); process->FilterURL(true, &validated_params.referrer.url); for (std::vector<GURL>::iterator it(validated_params.redirects.begin()); it != validated_params.redirects.end(); ++it) { process->FilterURL(false, &(*it)); } process->FilterURL(true, &validated_params.searchable_form_url); // Without this check, the renderer can trick the browser into using // filenames it can't access in a future session restore. if (!render_view_host_->CanAccessFilesOfPageState( validated_params.page_state)) { GetProcess()->ReceivedBadMessage(); return; } frame_tree_node()->navigator()->DidNavigate(this, validated_params); } void RenderFrameHostImpl::SwapOut() { if (render_view_host_->IsRenderViewLive()) { Send(new FrameMsg_SwapOut(routing_id_)); } else { // Our RenderViewHost doesn't have a live renderer, so just skip the unload // event. OnSwappedOut(true); } } void RenderFrameHostImpl::OnDidStartLoading() { delegate_->DidStartLoading(this); } void RenderFrameHostImpl::OnDidStopLoading() { delegate_->DidStopLoading(this); } void RenderFrameHostImpl::OnSwapOutACK() { OnSwappedOut(false); } void RenderFrameHostImpl::OnSwappedOut(bool timed_out) { frame_tree_node_->render_manager()->SwappedOutFrame(this); } void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) { // Validate the URLs in |params|. If the renderer can't request the URLs // directly, don't show them in the context menu. ContextMenuParams validated_params(params); RenderProcessHost* process = GetProcess(); // We don't validate |unfiltered_link_url| so that this field can be used // when users want to copy the original link URL. process->FilterURL(true, &validated_params.link_url); process->FilterURL(true, &validated_params.src_url); process->FilterURL(false, &validated_params.page_url); process->FilterURL(true, &validated_params.frame_url); delegate_->ShowContextMenu(this, validated_params); } bool RenderFrameHostImpl::CanCommitURL(const GURL& url) { // TODO(creis): We should also check for WebUI pages here. Also, when the // out-of-process iframes implementation is ready, we should check for // cross-site URLs that are not allowed to commit in this process. // Give the client a chance to disallow URLs from committing. return GetContentClient()->browser()->CanCommitURL(GetProcess(), url); } } // namespace content
38.508721
80
0.758285
[ "vector" ]
4ff543f64189d38987761f215ff6948f012f7692
35,423
cpp
C++
src/crypto/equihash.cpp
bitcoinpostquantum/bitcoinpq
28a1f3ce998e5b37b52e0505e1f7ab18a4b785a7
[ "MIT" ]
1
2020-09-29T20:01:39.000Z
2020-09-29T20:01:39.000Z
src/crypto/equihash.cpp
bitcoinpostquantum/bitcoinpq
28a1f3ce998e5b37b52e0505e1f7ab18a4b785a7
[ "MIT" ]
null
null
null
src/crypto/equihash.cpp
bitcoinpostquantum/bitcoinpq
28a1f3ce998e5b37b52e0505e1f7ab18a4b785a7
[ "MIT" ]
3
2022-01-09T03:01:47.000Z
2022-02-18T08:20:08.000Z
// Copyright (c) 2016 Jack Grigg // Copyright (c) 2016 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Implementation of the Equihash Proof-of-Work algorithm. // // Reference // ========= // Alex Biryukov and Dmitry Khovratovich // Equihash: Asymmetric Proof-of-Work Based on the Generalized Birthday Problem // NDSS ’16, 21-24 February 2016, San Diego, CA, USA // https://www.internetsociety.org/sites/default/files/blogs-media/equihash-asymmetric-proof-of-work-based-generalized-birthday-problem.pdf #if defined(HAVE_CONFIG_H) #include "config/bpq-config.h" #endif #include "crypto/equihash.h" #ifndef NO_UTIL_LOG #include "util.h" #else #define LogPrint(...) #endif #include <algorithm> #include <iostream> #include <stdexcept> #include <boost/optional.hpp> EhSolverCancelledException solver_cancelled; template<unsigned int N, unsigned int K> int Equihash<N,K>::InitialiseState(eh_HashState& base_state) { uint32_t le_N = htole32(N); uint32_t le_K = htole32(K); unsigned char personalization[crypto_generichash_blake2b_PERSONALBYTES] = {}; memcpy(personalization, "ZcashPoW", 8); memcpy(personalization+8, &le_N, 4); memcpy(personalization+12, &le_K, 4); return crypto_generichash_blake2b_init_salt_personal(&base_state, NULL, 0, // No key. (512/N)*N/8, NULL, // No salt. personalization); } void GenerateHash(const eh_HashState& base_state, eh_index g, unsigned char* hash, size_t hLen) { eh_HashState state; state = base_state; eh_index lei = htole32(g); crypto_generichash_blake2b_update(&state, (const unsigned char*) &lei, sizeof(eh_index)); crypto_generichash_blake2b_final(&state, hash, hLen); } void ExpandArray(const unsigned char* in, size_t in_len, unsigned char* out, size_t out_len, size_t bit_len, size_t byte_pad) { assert(bit_len >= 8); assert(8*sizeof(uint32_t) >= 7+bit_len); size_t out_width { (bit_len+7)/8 + byte_pad }; assert(out_len == 8*out_width*in_len/bit_len); uint32_t bit_len_mask { ((uint32_t)1 << bit_len) - 1 }; // The acc_bits least-significant bits of acc_value represent a bit sequence // in big-endian order. size_t acc_bits = 0; uint32_t acc_value = 0; size_t j = 0; for (size_t i = 0; i < in_len; i++) { acc_value = (acc_value << 8) | in[i]; acc_bits += 8; // When we have bit_len or more bits in the accumulator, write the next // output element. if (acc_bits >= bit_len) { acc_bits -= bit_len; for (size_t x = 0; x < byte_pad; x++) { out[j+x] = 0; } for (size_t x = byte_pad; x < out_width; x++) { out[j+x] = ( // Big-endian acc_value >> (acc_bits+(8*(out_width-x-1))) ) & ( // Apply bit_len_mask across byte boundaries (bit_len_mask >> (8*(out_width-x-1))) & 0xFF ); } j += out_width; } } } void CompressArray(const unsigned char* in, size_t in_len, unsigned char* out, size_t out_len, size_t bit_len, size_t byte_pad) { assert(bit_len >= 8); assert(8*sizeof(uint32_t) >= 7+bit_len); size_t in_width { (bit_len+7)/8 + byte_pad }; assert(out_len == bit_len*in_len/(8*in_width)); uint32_t bit_len_mask { ((uint32_t)1 << bit_len) - 1 }; // The acc_bits least-significant bits of acc_value represent a bit sequence // in big-endian order. size_t acc_bits = 0; uint32_t acc_value = 0; size_t j = 0; for (size_t i = 0; i < out_len; i++) { // When we have fewer than 8 bits left in the accumulator, read the next // input element. if (acc_bits < 8) { acc_value = acc_value << bit_len; for (size_t x = byte_pad; x < in_width; x++) { acc_value = acc_value | ( ( // Apply bit_len_mask across byte boundaries in[j+x] & ((bit_len_mask >> (8*(in_width-x-1))) & 0xFF) ) << (8*(in_width-x-1))); // Big-endian } j += in_width; acc_bits += bit_len; } acc_bits -= 8; out[i] = (acc_value >> acc_bits) & 0xFF; } } // Big-endian so that lexicographic array comparison is equivalent to integer // comparison void EhIndexToArray(const eh_index i, unsigned char* array) { BOOST_STATIC_ASSERT(sizeof(eh_index) == 4); eh_index bei = htobe32(i); memcpy(array, &bei, sizeof(eh_index)); } // Big-endian so that lexicographic array comparison is equivalent to integer // comparison eh_index ArrayToEhIndex(const unsigned char* array) { BOOST_STATIC_ASSERT(sizeof(eh_index) == 4); eh_index bei; memcpy(&bei, array, sizeof(eh_index)); return be32toh(bei); } eh_trunc TruncateIndex(const eh_index i, const unsigned int ilen) { // Truncate to 8 bits BOOST_STATIC_ASSERT(sizeof(eh_trunc) == 1); return (i >> (ilen - 8)) & 0xff; } eh_index UntruncateIndex(const eh_trunc t, const eh_index r, const unsigned int ilen) { eh_index i{t}; return (i << (ilen - 8)) | r; } std::vector<eh_index> GetIndicesFromMinimal(std::vector<unsigned char> minimal, size_t cBitLen) { assert(((cBitLen+1)+7)/8 <= sizeof(eh_index)); size_t lenIndices { 8*sizeof(eh_index)*minimal.size()/(cBitLen+1) }; size_t bytePad { sizeof(eh_index) - ((cBitLen+1)+7)/8 }; std::vector<unsigned char> array(lenIndices); ExpandArray(minimal.data(), minimal.size(), array.data(), lenIndices, cBitLen+1, bytePad); std::vector<eh_index> ret; for (size_t i = 0; i < lenIndices; i += sizeof(eh_index)) { ret.push_back(ArrayToEhIndex(array.data()+i)); } return ret; } std::vector<unsigned char> GetMinimalFromIndices(std::vector<eh_index> indices, size_t cBitLen) { assert(((cBitLen+1)+7)/8 <= sizeof(eh_index)); size_t lenIndices { indices.size()*sizeof(eh_index) }; size_t minLen { (cBitLen+1)*lenIndices/(8*sizeof(eh_index)) }; size_t bytePad { sizeof(eh_index) - ((cBitLen+1)+7)/8 }; std::vector<unsigned char> array(lenIndices); for (size_t i = 0; i < indices.size(); i++) { EhIndexToArray(indices[i], array.data()+(i*sizeof(eh_index))); } std::vector<unsigned char> ret(minLen); CompressArray(array.data(), lenIndices, ret.data(), minLen, cBitLen+1, bytePad); return ret; } template<size_t WIDTH> StepRow<WIDTH>::StepRow(const unsigned char* hashIn, size_t hInLen, size_t hLen, size_t cBitLen) { assert(hLen <= WIDTH); ExpandArray(hashIn, hInLen, hash, hLen, cBitLen); } template<size_t WIDTH> template<size_t W> StepRow<WIDTH>::StepRow(const StepRow<W>& a) { BOOST_STATIC_ASSERT(W <= WIDTH); std::copy(a.hash, a.hash+W, hash); } template<size_t WIDTH> FullStepRow<WIDTH>::FullStepRow(const unsigned char* hashIn, size_t hInLen, size_t hLen, size_t cBitLen, eh_index i) : StepRow<WIDTH> {hashIn, hInLen, hLen, cBitLen} { EhIndexToArray(i, hash+hLen); } template<size_t WIDTH> template<size_t W> FullStepRow<WIDTH>::FullStepRow(const FullStepRow<W>& a, const FullStepRow<W>& b, size_t len, size_t lenIndices, size_t trim) : StepRow<WIDTH> {a} { assert(len+lenIndices <= W); assert(len-trim+(2*lenIndices) <= WIDTH); for (size_t i = trim; i < len; i++) hash[i-trim] = a.hash[i] ^ b.hash[i]; if (a.IndicesBefore(b, len, lenIndices)) { std::copy(a.hash+len, a.hash+len+lenIndices, hash+len-trim); std::copy(b.hash+len, b.hash+len+lenIndices, hash+len-trim+lenIndices); } else { std::copy(b.hash+len, b.hash+len+lenIndices, hash+len-trim); std::copy(a.hash+len, a.hash+len+lenIndices, hash+len-trim+lenIndices); } } template<size_t WIDTH> FullStepRow<WIDTH>& FullStepRow<WIDTH>::operator=(const FullStepRow<WIDTH>& a) { std::copy(a.hash, a.hash+WIDTH, hash); return *this; } template<size_t WIDTH> bool StepRow<WIDTH>::IsZero(size_t len) { // This doesn't need to be constant time. for (size_t i = 0; i < len; i++) { if (hash[i] != 0) return false; } return true; } template<size_t WIDTH> std::vector<unsigned char> FullStepRow<WIDTH>::GetIndices(size_t len, size_t lenIndices, size_t cBitLen) const { assert(((cBitLen+1)+7)/8 <= sizeof(eh_index)); size_t minLen { (cBitLen+1)*lenIndices/(8*sizeof(eh_index)) }; size_t bytePad { sizeof(eh_index) - ((cBitLen+1)+7)/8 }; std::vector<unsigned char> ret(minLen); CompressArray(hash+len, lenIndices, ret.data(), minLen, cBitLen+1, bytePad); return ret; } template<size_t WIDTH> bool HasCollision(StepRow<WIDTH>& a, StepRow<WIDTH>& b, size_t l) { // This doesn't need to be constant time. for (size_t j = 0; j < l; j++) { if (a.hash[j] != b.hash[j]) return false; } return true; } template<size_t WIDTH> TruncatedStepRow<WIDTH>::TruncatedStepRow(const unsigned char* hashIn, size_t hInLen, size_t hLen, size_t cBitLen, eh_index i, unsigned int ilen) : StepRow<WIDTH> {hashIn, hInLen, hLen, cBitLen} { hash[hLen] = TruncateIndex(i, ilen); } template<size_t WIDTH> template<size_t W> TruncatedStepRow<WIDTH>::TruncatedStepRow(const TruncatedStepRow<W>& a, const TruncatedStepRow<W>& b, size_t len, size_t lenIndices, size_t trim) : StepRow<WIDTH> {a} { assert(len+lenIndices <= W); assert(len-trim+(2*lenIndices) <= WIDTH); for (size_t i = trim; i < len; i++) hash[i-trim] = a.hash[i] ^ b.hash[i]; if (a.IndicesBefore(b, len, lenIndices)) { std::copy(a.hash+len, a.hash+len+lenIndices, hash+len-trim); std::copy(b.hash+len, b.hash+len+lenIndices, hash+len-trim+lenIndices); } else { std::copy(b.hash+len, b.hash+len+lenIndices, hash+len-trim); std::copy(a.hash+len, a.hash+len+lenIndices, hash+len-trim+lenIndices); } } template<size_t WIDTH> TruncatedStepRow<WIDTH>& TruncatedStepRow<WIDTH>::operator=(const TruncatedStepRow<WIDTH>& a) { std::copy(a.hash, a.hash+WIDTH, hash); return *this; } template<size_t WIDTH> std::shared_ptr<eh_trunc> TruncatedStepRow<WIDTH>::GetTruncatedIndices(size_t len, size_t lenIndices) const { std::shared_ptr<eh_trunc> p (new eh_trunc[lenIndices], std::default_delete<eh_trunc[]>()); std::copy(hash+len, hash+len+lenIndices, p.get()); return p; } template<unsigned int N, unsigned int K> bool Equihash<N,K>::BasicSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled) { eh_index init_size { 1 << (CollisionBitLength + 1) }; // So, for <200,9>, that’s 2 ^ ( (200 / (9+1) ) + 1), or 2 to the 21st power, or 2,097,152.strings. 2097152 * 1030=2 160 066 560 //200x9 = 2097152 * 1030 = 2 160 066 560 // 3m4.064s, 2m56.177s, 5m46.537s //176x7 = 8388608 * 262 = 2 197 815 296 // 2m12.193s, 2m21.114s, 2m20.580s //144x5 = 33554432 * 70 = 2 348 810 240 // 3m39.719s, 3m58.309s, 7m22.785s //168x7 = 4194304 * 262 = 1 098 907 648 // 0m56.635s, 1m0.621s, 0m55.824s // 1) Generate first list LogPrint(BCLog::POW, "Generating first list\n"); size_t hashLen = HashLength; size_t lenIndices = sizeof(eh_index); std::vector<FullStepRow<FullWidth>> X; X.reserve(init_size); //size_t fullWidth = FullWidth; unsigned char tmpHash[HashOutput]; for (eh_index g = 0; X.size() < init_size; g++) { GenerateHash(base_state, g, tmpHash, HashOutput); for (eh_index i = 0; i < IndicesPerHashOutput && X.size() < init_size; i++) { X.emplace_back(tmpHash+(i*N/8), N/8, HashLength, CollisionBitLength, (g*IndicesPerHashOutput)+i); } if (cancelled(ListGeneration)) throw solver_cancelled; } // 3) Repeat step 2 until 2n/(k+1) bits remain for (unsigned int r = 1; r < K && X.size() > 0; r++) { LogPrint(BCLog::POW, "Round %u:\n", r); // 2a) Sort the list LogPrint(BCLog::POW, "- Sorting list\n"); std::sort(X.begin(), X.end(), CompareSR(CollisionByteLength)); if (cancelled(ListSorting)) throw solver_cancelled; LogPrint(BCLog::POW, "- Finding collisions\n"); size_t i = 0; size_t posFree = 0; std::vector<FullStepRow<FullWidth>> Xc; while (i < X.size() - 1) { // 2b) Find next set of unordered pairs with collisions on the next n/(k+1) bits size_t j = 1; while (i+j < X.size() && HasCollision(X[i], X[i+j], CollisionByteLength)) { j++; } // 2c) Calculate tuples (X_i ^ X_j, (i, j)) for (size_t l = 0; l < j - 1; l++) { for (size_t m = l + 1; m < j; m++) { if (DistinctIndices(X[i+l], X[i+m], hashLen, lenIndices)) { Xc.emplace_back(X[i+l], X[i+m], hashLen, lenIndices, CollisionByteLength); } } } // 2d) Store tuples on the table in-place if possible while (posFree < i+j && Xc.size() > 0) { X[posFree++] = Xc.back(); Xc.pop_back(); } i += j; if (cancelled(ListColliding)) throw solver_cancelled; } // 2e) Handle edge case where final table entry has no collision while (posFree < X.size() && Xc.size() > 0) { X[posFree++] = Xc.back(); Xc.pop_back(); } if (Xc.size() > 0) { // 2f) Add overflow to end of table X.insert(X.end(), Xc.begin(), Xc.end()); } else if (posFree < X.size()) { // 2g) Remove empty space at the end X.erase(X.begin()+posFree, X.end()); X.shrink_to_fit(); } hashLen -= CollisionByteLength; lenIndices *= 2; if (cancelled(RoundEnd)) throw solver_cancelled; } // k+1) Find a collision on last 2n(k+1) bits LogPrint(BCLog::POW, "Final round:\n"); if (X.size() > 1) { LogPrint(BCLog::POW, "- Sorting list\n"); std::sort(X.begin(), X.end(), CompareSR(hashLen)); if (cancelled(FinalSorting)) throw solver_cancelled; LogPrint(BCLog::POW, "- Finding collisions\n"); size_t i = 0; while (i < X.size() - 1) { size_t j = 1; while (i+j < X.size() && HasCollision(X[i], X[i+j], hashLen)) { j++; } for (size_t l = 0; l < j - 1; l++) { for (size_t m = l + 1; m < j; m++) { FullStepRow<FinalFullWidth> res(X[i+l], X[i+m], hashLen, lenIndices, 0); if (DistinctIndices(X[i+l], X[i+m], hashLen, lenIndices)) { auto soln = res.GetIndices(hashLen, 2*lenIndices, CollisionBitLength); assert(soln.size() == equihash_solution_size(N, K)); if (validBlock(soln)) { return true; } } } } i += j; if (cancelled(FinalColliding)) throw solver_cancelled; } } else LogPrint(BCLog::POW, "- List is empty\n"); return false; } template<size_t WIDTH> void CollideBranches(std::vector<FullStepRow<WIDTH>>& X, const size_t hlen, const size_t lenIndices, const unsigned int clen, const unsigned int ilen, const eh_trunc lt, const eh_trunc rt) { size_t i = 0; size_t posFree = 0; std::vector<FullStepRow<WIDTH>> Xc; while (i < X.size() - 1) { // 2b) Find next set of unordered pairs with collisions on the next n/(k+1) bits size_t j = 1; while (i+j < X.size() && HasCollision(X[i], X[i+j], clen)) { j++; } // 2c) Calculate tuples (X_i ^ X_j, (i, j)) for (size_t l = 0; l < j - 1; l++) { for (size_t m = l + 1; m < j; m++) { if (DistinctIndices(X[i+l], X[i+m], hlen, lenIndices)) { if (IsValidBranch(X[i+l], hlen, ilen, lt) && IsValidBranch(X[i+m], hlen, ilen, rt)) { Xc.emplace_back(X[i+l], X[i+m], hlen, lenIndices, clen); } else if (IsValidBranch(X[i+m], hlen, ilen, lt) && IsValidBranch(X[i+l], hlen, ilen, rt)) { Xc.emplace_back(X[i+m], X[i+l], hlen, lenIndices, clen); } } } } // 2d) Store tuples on the table in-place if possible while (posFree < i+j && Xc.size() > 0) { X[posFree++] = Xc.back(); Xc.pop_back(); } i += j; } // 2e) Handle edge case where final table entry has no collision while (posFree < X.size() && Xc.size() > 0) { X[posFree++] = Xc.back(); Xc.pop_back(); } if (Xc.size() > 0) { // 2f) Add overflow to end of table X.insert(X.end(), Xc.begin(), Xc.end()); } else if (posFree < X.size()) { // 2g) Remove empty space at the end X.erase(X.begin()+posFree, X.end()); X.shrink_to_fit(); } } template<unsigned int N, unsigned int K> bool Equihash<N,K>::OptimisedSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled) { eh_index init_size { 1 << (CollisionBitLength + 1) }; eh_index recreate_size { UntruncateIndex(1, 0, CollisionBitLength + 1) }; // First run the algorithm with truncated indices const eh_index soln_size { 1 << K }; std::vector<std::shared_ptr<eh_trunc>> partialSolns; size_t invalidCount = 0; { // 1) Generate first list LogPrint(BCLog::POW, "Generating first list\n"); size_t hashLen = HashLength; size_t lenIndices = sizeof(eh_trunc); std::vector<TruncatedStepRow<TruncatedWidth>> Xt; Xt.reserve(init_size); unsigned char tmpHash[HashOutput]; for (eh_index g = 0; Xt.size() < init_size; g++) { GenerateHash(base_state, g, tmpHash, HashOutput); for (eh_index i = 0; i < IndicesPerHashOutput && Xt.size() < init_size; i++) { Xt.emplace_back(tmpHash+(i*N/8), N/8, HashLength, CollisionBitLength, (g*IndicesPerHashOutput)+i, CollisionBitLength + 1); } if (cancelled(ListGeneration)) throw solver_cancelled; } // 3) Repeat step 2 until 2n/(k+1) bits remain for (size_t r = 1; r < K && Xt.size() > 0; r++) { LogPrint(BCLog::POW, "Round %zu:\n", r); // 2a) Sort the list LogPrint(BCLog::POW, "- Sorting list\n"); std::sort(Xt.begin(), Xt.end(), CompareSR(CollisionByteLength)); if (cancelled(ListSorting)) throw solver_cancelled; LogPrint(BCLog::POW, "- Finding collisions\n"); size_t i = 0; size_t posFree = 0; std::vector<TruncatedStepRow<TruncatedWidth>> Xc; while (i < Xt.size() - 1) { // 2b) Find next set of unordered pairs with collisions on the next n/(k+1) bits size_t j = 1; while (i+j < Xt.size() && HasCollision(Xt[i], Xt[i+j], CollisionByteLength)) { j++; } // 2c) Calculate tuples (X_i ^ X_j, (i, j)) //bool checking_for_zero = (i == 0 && Xt[0].IsZero(hashLen)); for (size_t l = 0; l < j - 1; l++) { for (size_t m = l + 1; m < j; m++) { // We truncated, so don't check for distinct indices here TruncatedStepRow<TruncatedWidth> Xi {Xt[i+l], Xt[i+m], hashLen, lenIndices, CollisionByteLength}; if (!(Xi.IsZero(hashLen-CollisionByteLength) && IsProbablyDuplicate<soln_size>(Xi.GetTruncatedIndices(hashLen-CollisionByteLength, 2*lenIndices), 2*lenIndices))) { Xc.emplace_back(Xi); } } } // 2d) Store tuples on the table in-place if possible while (posFree < i+j && Xc.size() > 0) { Xt[posFree++] = Xc.back(); Xc.pop_back(); } i += j; if (cancelled(ListColliding)) throw solver_cancelled; } // 2e) Handle edge case where final table entry has no collision while (posFree < Xt.size() && Xc.size() > 0) { Xt[posFree++] = Xc.back(); Xc.pop_back(); } if (Xc.size() > 0) { // 2f) Add overflow to end of table Xt.insert(Xt.end(), Xc.begin(), Xc.end()); } else if (posFree < Xt.size()) { // 2g) Remove empty space at the end Xt.erase(Xt.begin()+posFree, Xt.end()); Xt.shrink_to_fit(); } hashLen -= CollisionByteLength; lenIndices *= 2; if (cancelled(RoundEnd)) throw solver_cancelled; } // k+1) Find a collision on last 2n(k+1) bits LogPrint(BCLog::POW, "Final round:\n"); if (Xt.size() > 1) { LogPrint(BCLog::POW, "- Sorting list\n"); std::sort(Xt.begin(), Xt.end(), CompareSR(hashLen)); if (cancelled(FinalSorting)) throw solver_cancelled; LogPrint(BCLog::POW, "- Finding collisions\n"); size_t i = 0; while (i < Xt.size() - 1) { size_t j = 1; while (i+j < Xt.size() && HasCollision(Xt[i], Xt[i+j], hashLen)) { j++; } for (size_t l = 0; l < j - 1; l++) { for (size_t m = l + 1; m < j; m++) { TruncatedStepRow<FinalTruncatedWidth> res(Xt[i+l], Xt[i+m], hashLen, lenIndices, 0); auto soln = res.GetTruncatedIndices(hashLen, 2*lenIndices); if (!IsProbablyDuplicate<soln_size>(soln, 2*lenIndices)) { partialSolns.push_back(soln); } } } i += j; if (cancelled(FinalColliding)) throw solver_cancelled; } } else LogPrint(BCLog::POW, "- List is empty\n"); } // Ensure Xt goes out of scope and is destroyed LogPrint(BCLog::POW, "Found %d partial solutions\n", partialSolns.size()); // Now for each solution run the algorithm again to recreate the indices LogPrint(BCLog::POW, "Culling solutions\n"); for (std::shared_ptr<eh_trunc> partialSoln : partialSolns) { std::set<std::vector<unsigned char>> solns; size_t hashLen; size_t lenIndices; unsigned char tmpHash[HashOutput]; std::vector<boost::optional<std::vector<FullStepRow<FinalFullWidth>>>> X; X.reserve(K+1); // 3) Repeat steps 1 and 2 for each partial index for (eh_index i = 0; i < soln_size; i++) { // 1) Generate first list of possibilities std::vector<FullStepRow<FinalFullWidth>> icv; icv.reserve(recreate_size); for (eh_index j = 0; j < recreate_size; j++) { eh_index newIndex { UntruncateIndex(partialSoln.get()[i], j, CollisionBitLength + 1) }; if (j == 0 || newIndex % IndicesPerHashOutput == 0) { GenerateHash(base_state, newIndex/IndicesPerHashOutput, tmpHash, HashOutput); } icv.emplace_back(tmpHash+((newIndex % IndicesPerHashOutput) * N/8), N/8, HashLength, CollisionBitLength, newIndex); if (cancelled(PartialGeneration)) throw solver_cancelled; } boost::optional<std::vector<FullStepRow<FinalFullWidth>>> ic = icv; // 2a) For each pair of lists: hashLen = HashLength; lenIndices = sizeof(eh_index); size_t rti = i; for (size_t r = 0; r <= K; r++) { // 2b) Until we are at the top of a subtree: if (r < X.size()) { if (X[r]) { // 2c) Merge the lists ic->reserve(ic->size() + X[r]->size()); ic->insert(ic->end(), X[r]->begin(), X[r]->end()); std::sort(ic->begin(), ic->end(), CompareSR(hashLen)); if (cancelled(PartialSorting)) throw solver_cancelled; size_t lti = rti-(1<<r); CollideBranches(*ic, hashLen, lenIndices, CollisionByteLength, CollisionBitLength + 1, partialSoln.get()[lti], partialSoln.get()[rti]); // 2d) Check if this has become an invalid solution if (ic->size() == 0) goto invalidsolution; X[r] = boost::none; hashLen -= CollisionByteLength; lenIndices *= 2; rti = lti; } else { X[r] = *ic; break; } } else { X.push_back(ic); break; } if (cancelled(PartialSubtreeEnd)) throw solver_cancelled; } if (cancelled(PartialIndexEnd)) throw solver_cancelled; } // We are at the top of the tree assert(X.size() == K+1); for (FullStepRow<FinalFullWidth> row : *X[K]) { auto soln = row.GetIndices(hashLen, lenIndices, CollisionBitLength); assert(soln.size() == equihash_solution_size(N, K)); solns.insert(soln); } for (auto soln : solns) { if (validBlock(soln)) return true; } if (cancelled(PartialEnd)) throw solver_cancelled; continue; invalidsolution: invalidCount++; } LogPrint(BCLog::POW, "- Number of invalid solutions found: %zu\n", invalidCount); return false; } template<unsigned int N, unsigned int K> bool Equihash<N,K>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln) { if (soln.size() != SolutionWidth) { LogPrint(BCLog::POW, "Invalid solution length: %d (expected %d)\n", soln.size(), SolutionWidth); return false; } std::vector<FullStepRow<FinalFullWidth>> X; X.reserve(1 << K); unsigned char tmpHash[HashOutput]; for (eh_index i : GetIndicesFromMinimal(soln, CollisionBitLength)) { GenerateHash(base_state, i/IndicesPerHashOutput, tmpHash, HashOutput); X.emplace_back(tmpHash+((i % IndicesPerHashOutput) * N/8), N/8, HashLength, CollisionBitLength, i); } size_t hashLen = HashLength; size_t lenIndices = sizeof(eh_index); while (X.size() > 1) { std::vector<FullStepRow<FinalFullWidth>> Xc; for (size_t i = 0; i < X.size(); i += 2) { if (!HasCollision(X[i], X[i+1], CollisionByteLength)) { LogPrint(BCLog::POW, "Invalid solution: invalid collision length between StepRows\n"); LogPrint(BCLog::POW, "X[i] = %s\n", X[i].GetHex(hashLen)); LogPrint(BCLog::POW, "X[i+1] = %s\n", X[i+1].GetHex(hashLen)); return false; } if (X[i+1].IndicesBefore(X[i], hashLen, lenIndices)) { LogPrint(BCLog::POW, "Invalid solution: Index tree incorrectly ordered\n"); return false; } if (!DistinctIndices(X[i], X[i+1], hashLen, lenIndices)) { LogPrint(BCLog::POW, "Invalid solution: duplicate indices\n"); return false; } Xc.emplace_back(X[i], X[i+1], hashLen, lenIndices, CollisionByteLength); } X = Xc; hashLen -= CollisionByteLength; lenIndices *= 2; } assert(X.size() == 1); return X[0].IsZero(hashLen); } // Explicit instantiations for Equihash<96,3> template int Equihash<96,3>::InitialiseState(eh_HashState& base_state); template bool Equihash<96,3>::BasicSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<96,3>::OptimisedSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<96,3>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln); // Explicit instantiations for Equihash<200,9> template int Equihash<200,9>::InitialiseState(eh_HashState& base_state); template bool Equihash<200,9>::BasicSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<200,9>::OptimisedSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<200,9>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln); // Explicit instantiations for Equihash<96,5> template int Equihash<96,5>::InitialiseState(eh_HashState& base_state); template bool Equihash<96,5>::BasicSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<96,5>::OptimisedSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<96,5>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln); // Explicit instantiations for Equihash<48,5> template int Equihash<48,5>::InitialiseState(eh_HashState& base_state); template bool Equihash<48,5>::BasicSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<48,5>::OptimisedSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<48,5>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln); // Explicit instantiations for Equihash<176,7> template int Equihash<176,7>::InitialiseState(eh_HashState& base_state); template bool Equihash<176,7>::BasicSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<176,7>::OptimisedSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<176,7>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln); // Explicit instantiations for Equihash<144,5> template int Equihash<144,5>::InitialiseState(eh_HashState& base_state); template bool Equihash<144,5>::BasicSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<144,5>::OptimisedSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<144,5>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln); // Explicit instantiations for Equihash<168,7> template int Equihash<168,7>::InitialiseState(eh_HashState& base_state); template bool Equihash<168,7>::BasicSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<168,7>::OptimisedSolve(const eh_HashState& base_state, const std::function<bool(std::vector<unsigned char>)> validBlock, const std::function<bool(EhSolverCancelCheck)> cancelled); template bool Equihash<168,7>::IsValidSolution(const eh_HashState& base_state, std::vector<unsigned char> soln);
41.625147
188
0.553398
[ "vector" ]
4ff87c9b7ddf253dbe2eddcc892c1ac21e295825
15,573
cc
C++
src/core/lib/security/credentials/google_default/google_default_credentials.cc
grepme/grpc
dc08d01e102a2a6829f04b48531048a663fe2ced
[ "Apache-2.0" ]
1
2020-12-26T19:21:59.000Z
2020-12-26T19:21:59.000Z
src/core/lib/security/credentials/google_default/google_default_credentials.cc
grepme/grpc
dc08d01e102a2a6829f04b48531048a663fe2ced
[ "Apache-2.0" ]
null
null
null
src/core/lib/security/credentials/google_default/google_default_credentials.cc
grepme/grpc
dc08d01e102a2a6829f04b48531048a663fe2ced
[ "Apache-2.0" ]
null
null
null
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <grpc/support/port_platform.h> #include "src/core/lib/security/credentials/credentials.h" #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h" #include "src/core/ext/filters/client_channel/lb_policy/xds/xds_channel_args.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/env.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/http/httpcli.h" #include "src/core/lib/http/parser.h" #include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/iomgr/polling_entity.h" #include "src/core/lib/security/credentials/alts/alts_credentials.h" #include "src/core/lib/security/credentials/alts/check_gcp_environment.h" #include "src/core/lib/security/credentials/google_default/google_default_credentials.h" #include "src/core/lib/security/credentials/jwt/jwt_credentials.h" #include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/lib/surface/api_trace.h" using grpc_core::Json; /* -- Constants. -- */ #define GRPC_COMPUTE_ENGINE_DETECTION_HOST "metadata.google.internal." #define GRPC_GOOGLE_CREDENTIAL_CREATION_ERROR \ "Failed to create Google credentials" /* -- Default credentials. -- */ /* A sticky bit that will be set only if the result of metadata server detection * is positive. We do not set the bit if the result is negative. Because it * means the detection is done via network test that is unreliable and the * unreliable result should not be referred by successive calls. */ static int g_metadata_server_available = 0; static gpr_mu g_state_mu; /* Protect a metadata_server_detector instance that can be modified by more than * one gRPC threads */ static gpr_mu* g_polling_mu; static gpr_once g_once = GPR_ONCE_INIT; static grpc_core::internal::grpc_gce_tenancy_checker g_gce_tenancy_checker = grpc_alts_is_running_on_gcp; static void init_default_credentials(void) { gpr_mu_init(&g_state_mu); } struct metadata_server_detector { grpc_polling_entity pollent; int is_done; int success; grpc_http_response response; }; grpc_core::RefCountedPtr<grpc_channel_security_connector> grpc_google_default_channel_credentials::create_security_connector( grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, const char* target, const grpc_channel_args* args, grpc_channel_args** new_args) { const bool is_grpclb_load_balancer = grpc_channel_args_find_bool( args, GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER, false); const bool is_backend_from_grpclb_load_balancer = grpc_channel_args_find_bool( args, GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER, false); const char* xds_cluster = grpc_channel_args_find_string(args, GRPC_ARG_XDS_CLUSTER_NAME); const bool is_xds_non_cfe_cluster = xds_cluster != nullptr && strcmp(xds_cluster, "google_cfe") != 0; const bool use_alts = is_grpclb_load_balancer || is_backend_from_grpclb_load_balancer || is_xds_non_cfe_cluster; /* Return failure if ALTS is selected but not running on GCE. */ if (use_alts && alts_creds_ == nullptr) { gpr_log(GPR_ERROR, "ALTS is selected, but not running on GCE."); return nullptr; } grpc_core::RefCountedPtr<grpc_channel_security_connector> sc = use_alts ? alts_creds_->create_security_connector(call_creds, target, args, new_args) : ssl_creds_->create_security_connector(call_creds, target, args, new_args); /* grpclb-specific channel args are removed from the channel args set * to ensure backends and fallback adresses will have the same set of channel * args. By doing that, it guarantees the connections to backends will not be * torn down and re-connected when switching in and out of fallback mode. */ if (use_alts) { static const char* args_to_remove[] = { GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER, GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER, }; *new_args = grpc_channel_args_copy_and_add_and_remove( args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), nullptr, 0); } return sc; } grpc_channel_args* grpc_google_default_channel_credentials::update_arguments( grpc_channel_args* args) { grpc_channel_args* updated = args; if (grpc_channel_args_find(args, GRPC_ARG_DNS_ENABLE_SRV_QUERIES) == nullptr) { grpc_arg new_srv_arg = grpc_channel_arg_integer_create( const_cast<char*>(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true); updated = grpc_channel_args_copy_and_add(args, &new_srv_arg, 1); grpc_channel_args_destroy(args); } return updated; } static void on_metadata_server_detection_http_response(void* user_data, grpc_error* error) { metadata_server_detector* detector = static_cast<metadata_server_detector*>(user_data); if (error == GRPC_ERROR_NONE && detector->response.status == 200 && detector->response.hdr_count > 0) { /* Internet providers can return a generic response to all requests, so it is necessary to check that metadata header is present also. */ size_t i; for (i = 0; i < detector->response.hdr_count; i++) { grpc_http_header* header = &detector->response.hdrs[i]; if (strcmp(header->key, "Metadata-Flavor") == 0 && strcmp(header->value, "Google") == 0) { detector->success = 1; break; } } } gpr_mu_lock(g_polling_mu); detector->is_done = 1; GRPC_LOG_IF_ERROR( "Pollset kick", grpc_pollset_kick(grpc_polling_entity_pollset(&detector->pollent), nullptr)); gpr_mu_unlock(g_polling_mu); } static void destroy_pollset(void* p, grpc_error* /*e*/) { grpc_pollset_destroy(static_cast<grpc_pollset*>(p)); } static int is_metadata_server_reachable() { metadata_server_detector detector; grpc_httpcli_request request; grpc_httpcli_context context; grpc_closure destroy_closure; /* The http call is local. If it takes more than one sec, it is for sure not on compute engine. */ grpc_millis max_detection_delay = GPR_MS_PER_SEC; grpc_pollset* pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size())); grpc_pollset_init(pollset, &g_polling_mu); detector.pollent = grpc_polling_entity_create_from_pollset(pollset); detector.is_done = 0; detector.success = 0; memset(&request, 0, sizeof(grpc_httpcli_request)); request.host = const_cast<char*>(GRPC_COMPUTE_ENGINE_DETECTION_HOST); request.http.path = const_cast<char*>("/"); grpc_httpcli_context_init(&context); grpc_resource_quota* resource_quota = grpc_resource_quota_create("google_default_credentials"); grpc_httpcli_get( &context, &detector.pollent, resource_quota, &request, grpc_core::ExecCtx::Get()->Now() + max_detection_delay, GRPC_CLOSURE_CREATE(on_metadata_server_detection_http_response, &detector, grpc_schedule_on_exec_ctx), &detector.response); grpc_resource_quota_unref_internal(resource_quota); grpc_core::ExecCtx::Get()->Flush(); /* Block until we get the response. This is not ideal but this should only be called once for the lifetime of the process by the default credentials. */ gpr_mu_lock(g_polling_mu); while (!detector.is_done) { grpc_pollset_worker* worker = nullptr; if (!GRPC_LOG_IF_ERROR( "pollset_work", grpc_pollset_work(grpc_polling_entity_pollset(&detector.pollent), &worker, GRPC_MILLIS_INF_FUTURE))) { detector.is_done = 1; detector.success = 0; } } gpr_mu_unlock(g_polling_mu); grpc_httpcli_context_destroy(&context); GRPC_CLOSURE_INIT(&destroy_closure, destroy_pollset, grpc_polling_entity_pollset(&detector.pollent), grpc_schedule_on_exec_ctx); grpc_pollset_shutdown(grpc_polling_entity_pollset(&detector.pollent), &destroy_closure); g_polling_mu = nullptr; grpc_core::ExecCtx::Get()->Flush(); gpr_free(grpc_polling_entity_pollset(&detector.pollent)); grpc_http_response_destroy(&detector.response); return detector.success; } /* Takes ownership of creds_path if not NULL. */ static grpc_error* create_default_creds_from_path( const std::string& creds_path, grpc_core::RefCountedPtr<grpc_call_credentials>* creds) { grpc_auth_json_key key; grpc_auth_refresh_token token; grpc_core::RefCountedPtr<grpc_call_credentials> result; grpc_slice creds_data = grpc_empty_slice(); grpc_error* error = GRPC_ERROR_NONE; Json json; if (creds_path.empty()) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("creds_path unset"); goto end; } error = grpc_load_file(creds_path.c_str(), 0, &creds_data); if (error != GRPC_ERROR_NONE) goto end; json = Json::Parse(grpc_core::StringViewFromSlice(creds_data), &error); if (error != GRPC_ERROR_NONE) goto end; if (json.type() != Json::Type::OBJECT) { error = grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Failed to parse JSON"), GRPC_ERROR_STR_RAW_BYTES, grpc_slice_ref_internal(creds_data)); goto end; } /* First, try an auth json key. */ key = grpc_auth_json_key_create_from_json(json); if (grpc_auth_json_key_is_valid(&key)) { result = grpc_service_account_jwt_access_credentials_create_from_auth_json_key( key, grpc_max_auth_token_lifetime()); if (result == nullptr) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "grpc_service_account_jwt_access_credentials_create_from_auth_json_" "key failed"); } goto end; } /* Then try a refresh token if the auth json key was invalid. */ token = grpc_auth_refresh_token_create_from_json(json); if (grpc_auth_refresh_token_is_valid(&token)) { result = grpc_refresh_token_credentials_create_from_auth_refresh_token(token); if (result == nullptr) { error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "grpc_refresh_token_credentials_create_from_auth_refresh_token " "failed"); } goto end; } end: GPR_ASSERT((result == nullptr) + (error == GRPC_ERROR_NONE) == 1); grpc_slice_unref_internal(creds_data); *creds = result; return error; } static void update_tenancy() { gpr_once_init(&g_once, init_default_credentials); grpc_core::MutexLock lock(&g_state_mu); /* Try a platform-provided hint for GCE. */ if (!g_metadata_server_available) { g_metadata_server_available = g_gce_tenancy_checker(); } /* TODO: Add a platform-provided hint for GAE. */ /* Do a network test for metadata server. */ if (!g_metadata_server_available) { g_metadata_server_available = is_metadata_server_reachable(); } } static bool metadata_server_available() { grpc_core::MutexLock lock(&g_state_mu); return static_cast<bool>(g_metadata_server_available); } static grpc_core::RefCountedPtr<grpc_call_credentials> make_default_call_creds( grpc_error** error) { grpc_core::RefCountedPtr<grpc_call_credentials> call_creds; grpc_error* err; /* First, try the environment variable. */ char* path_from_env = gpr_getenv(GRPC_GOOGLE_CREDENTIALS_ENV_VAR); if (path_from_env != nullptr) { err = create_default_creds_from_path(path_from_env, &call_creds); gpr_free(path_from_env); if (err == GRPC_ERROR_NONE) return call_creds; *error = grpc_error_add_child(*error, err); } /* Then the well-known file. */ err = create_default_creds_from_path( grpc_get_well_known_google_credentials_file_path(), &call_creds); if (err == GRPC_ERROR_NONE) return call_creds; *error = grpc_error_add_child(*error, err); update_tenancy(); if (metadata_server_available()) { call_creds = grpc_core::RefCountedPtr<grpc_call_credentials>( grpc_google_compute_engine_credentials_create(nullptr)); if (call_creds == nullptr) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( GRPC_GOOGLE_CREDENTIAL_CREATION_ERROR); *error = grpc_error_add_child( *error, GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Failed to get credentials from network")); } } return call_creds; } grpc_channel_credentials* grpc_google_default_credentials_create( grpc_call_credentials* call_credentials) { grpc_channel_credentials* result = nullptr; grpc_core::RefCountedPtr<grpc_call_credentials> call_creds(call_credentials); grpc_error* error = nullptr; grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE("grpc_google_default_credentials_create(%p)", 1, (call_credentials)); if (call_creds == nullptr) { call_creds = make_default_call_creds(&error); } if (call_creds != nullptr) { /* Create google default credentials. */ grpc_channel_credentials* ssl_creds = grpc_ssl_credentials_create(nullptr, nullptr, nullptr, nullptr); GPR_ASSERT(ssl_creds != nullptr); grpc_alts_credentials_options* options = grpc_alts_credentials_client_options_create(); grpc_channel_credentials* alts_creds = grpc_alts_credentials_create(options); grpc_alts_credentials_options_destroy(options); auto creds = grpc_core::MakeRefCounted<grpc_google_default_channel_credentials>( grpc_core::RefCountedPtr<grpc_channel_credentials>(alts_creds), grpc_core::RefCountedPtr<grpc_channel_credentials>(ssl_creds)); result = grpc_composite_channel_credentials_create( creds.get(), call_creds.get(), nullptr); GPR_ASSERT(result != nullptr); } else { gpr_log(GPR_ERROR, "Could not create google default credentials: %s", grpc_error_string(error)); } GRPC_ERROR_UNREF(error); return result; } namespace grpc_core { namespace internal { void set_gce_tenancy_checker_for_testing(grpc_gce_tenancy_checker checker) { g_gce_tenancy_checker = checker; } void grpc_flush_cached_google_default_credentials(void) { grpc_core::ExecCtx exec_ctx; gpr_once_init(&g_once, init_default_credentials); gpr_mu_lock(&g_state_mu); g_metadata_server_available = 0; gpr_mu_unlock(&g_state_mu); } } // namespace internal } // namespace grpc_core /* -- Well known credentials path. -- */ static grpc_well_known_credentials_path_getter creds_path_getter = nullptr; std::string grpc_get_well_known_google_credentials_file_path(void) { if (creds_path_getter != nullptr) return creds_path_getter(); return grpc_get_well_known_google_credentials_file_path_impl(); } void grpc_override_well_known_credentials_path_getter( grpc_well_known_credentials_path_getter getter) { creds_path_getter = getter; }
38.262899
88
0.735825
[ "object" ]
4ff9f7becade61e119ba99ca42304c9ea9ac8b81
1,270
cpp
C++
src/lib/ecl/test/sensor_simulator/ekf_logger.cpp
zhengnici/PX4-Autopilot
7f2acb6d593c95933b456e2eecf8466d94b34240
[ "BSD-3-Clause" ]
287
2015-12-24T16:40:16.000Z
2020-10-26T02:45:57.000Z
src/lib/ecl/test/sensor_simulator/ekf_logger.cpp
zhengnici/PX4-Autopilot
7f2acb6d593c95933b456e2eecf8466d94b34240
[ "BSD-3-Clause" ]
646
2015-12-24T12:49:52.000Z
2020-10-28T10:43:47.000Z
src/lib/ecl/test/sensor_simulator/ekf_logger.cpp
zhengnici/PX4-Autopilot
7f2acb6d593c95933b456e2eecf8466d94b34240
[ "BSD-3-Clause" ]
470
2015-12-25T02:25:56.000Z
2020-10-26T18:33:16.000Z
#include "ekf_logger.h" EkfLogger::EkfLogger(std::shared_ptr<Ekf> ekf): _ekf{ekf}, _ekf_wrapper(ekf) { } EkfLogger::~EkfLogger() {} void EkfLogger::setFilePath(std::string file_path) { _file_path = file_path; } void EkfLogger::writeStateToFile() { if(!_file_opened) { _file.open(_file_path); _file_opened = true; _file << "Timestamp"; if(_state_logging_enabled) { for(int i = 0; i < 24; i++) { _file << ",state[" << i << "]"; } } if(_variance_logging_enabled) { for(int i = 0; i < 24; i++) { _file << ",variance[" << i << "]"; } } _file << std::endl; } if (_file) { writeState(); } else { std::cerr << "Can not write to output file" << std::endl; std::exit(-1); } } void EkfLogger::writeState() { if(_state_logging_enabled) { uint64_t time = _ekf->get_imu_sample_delayed().time_us; _file << time; if(_state_logging_enabled) { matrix::Vector<float, 24> state = _ekf->getStateAtFusionHorizonAsVector(); for(int i = 0; i < 24; i++) { _file << "," << state(i); } } if(_variance_logging_enabled) { matrix::Vector<float, 24> variance = _ekf->covariances_diagonal(); for(int i = 0; i < 24; i++) { _file << "," << variance(i); } } _file << std::endl; } }
16.282051
77
0.589764
[ "vector" ]
4ffb6648a18999d030b3bce77e9ed008daef1b58
4,120
cpp
C++
test/test2.cpp
Gnomus042/crypto
eaea809886c99234484170376c8c20bf11436807
[ "MIT" ]
null
null
null
test/test2.cpp
Gnomus042/crypto
eaea809886c99234484170376c8c20bf11436807
[ "MIT" ]
null
null
null
test/test2.cpp
Gnomus042/crypto
eaea809886c99234484170376c8c20bf11436807
[ "MIT" ]
null
null
null
// // Created by anast on 10/11/2020. // #include <gtest/gtest.h> #include <iostream> #include <vector> #include "../Lab1/AES.h" #include "../Lab2/RC4.h" #include "../Lab2/Salsa20.h" TEST (RC4, encrypt_decrypt) { string key_str = "12345678901234561234567890123456"; string data_str = "Absolutely random sentence"; vector<uint8_t> key(begin(key_str), end(key_str)); vector<uint8_t> data(begin(data_str), end(data_str)); RC4 rc4 = RC4(key); string res = ""; for (uint8_t q: rc4.decrypt(rc4.encrypt(data))) { res += (char)q; } res = res.substr(0, data.size()); EXPECT_EQ(res, data_str); } TEST (Salsa20, encrypt_decrypt) { string key_str = "12345678901234561234567890123456"; string data_str = "Absolutely random sentence"; vector<uint8_t> key(begin(key_str), end(key_str)); vector<uint8_t> data(begin(data_str), end(data_str)); Salsa20 salsa20 = Salsa20(key); string res = ""; for (uint8_t q: salsa20.crypt(salsa20.crypt(data))) { res += (char)q; } res = res.substr(0, data.size()); EXPECT_EQ(res, data_str); } TEST (AES, 128_key_ecb) { string key_str = "1234567890123456"; string data_str = "Absolutely random sentence"; string init_vector_str = "This is an initt"; vector<uint8_t> key(begin(key_str), end(key_str)); vector<uint8_t> init_vector(begin(init_vector_str), end(init_vector_str)); vector<uint8_t> data(begin(data_str), end(data_str)); AES aes(key, init_vector); string res = ""; for (uint8_t q: aes.decrypt(aes.encrypt(data, AES::Mode::ECB), AES::Mode::ECB)) { res += (char)q; } res = res.substr(0, data.size()); EXPECT_EQ(res, data_str); } TEST (AES, 128_key_cbc) { string key_str = "1234567890123456"; string data_str = "Absolutely random sentence"; string init_vector_str = "This is an initt"; vector<uint8_t> key(begin(key_str), end(key_str)); vector<uint8_t> init_vector(begin(init_vector_str), end(init_vector_str)); vector<uint8_t> data(begin(data_str), end(data_str)); AES aes(key, init_vector); string res = ""; for (uint8_t q: aes.decrypt(aes.encrypt(data, AES::Mode::CBC), AES::Mode::CBC)) { res += (char)q; } res = res.substr(0, data.size()); EXPECT_EQ(res, data_str); } TEST (AES, 128_key_ofb) { string key_str = "1234567890123456"; string data_str = "Absolutely random sentence"; string init_vector_str = "This is an initt"; vector<uint8_t> key(begin(key_str), end(key_str)); vector<uint8_t> init_vector(begin(init_vector_str), end(init_vector_str)); vector<uint8_t> data(begin(data_str), end(data_str)); AES aes(key, init_vector); string res = ""; for (uint8_t q: aes.decrypt(aes.encrypt(data, AES::Mode::OFB), AES::Mode::OFB)) { res += (char)q; } res = res.substr(0, data.size()); EXPECT_EQ(res, data_str); } TEST (AES, 128_key_ctr) { string key_str = "1234567890123456"; string data_str = "Absolutely random sentence"; string init_vector_str = "This is an initt"; vector<uint8_t> key(begin(key_str), end(key_str)); vector<uint8_t> init_vector(begin(init_vector_str), end(init_vector_str)); vector<uint8_t> data(begin(data_str), end(data_str)); AES aes(key, init_vector); string res = ""; for (uint8_t q: aes.decrypt(aes.encrypt(data, AES::Mode::CTR), AES::Mode::CTR)) { res += (char)q; } res = res.substr(0, data.size()); EXPECT_EQ(res, data_str); } TEST (AES, 128_key_cfb) { string key_str = "1234567890123456"; string data_str = "Absolutely random sentence"; string init_vector_str = "This is an initt"; vector<uint8_t> key(begin(key_str), end(key_str)); vector<uint8_t> init_vector(begin(init_vector_str), end(init_vector_str)); vector<uint8_t> data(begin(data_str), end(data_str)); AES aes(key, init_vector); string res = ""; for (uint8_t q: aes.decrypt(aes.encrypt(data, AES::Mode::CFB), AES::Mode::CFB)) { res += (char)q; } res = res.substr(0, data.size()); EXPECT_EQ(res, data_str); }
28.811189
85
0.650971
[ "vector" ]
4ffcd63599da1cda0dcc816e6353ef9f1ec27c82
5,064
cc
C++
content/renderer/pepper/pepper_platform_context_3d_impl.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-05-03T06:33:56.000Z
2021-11-14T18:39:42.000Z
content/renderer/pepper/pepper_platform_context_3d_impl.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/pepper/pepper_platform_context_3d_impl.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/pepper/pepper_platform_context_3d_impl.h" #include "base/bind.h" #include "content/common/gpu/client/context_provider_command_buffer.h" #include "content/common/gpu/client/gpu_channel_host.h" #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/renderer/render_thread_impl.h" #include "googleurl/src/gurl.h" #include "gpu/command_buffer/client/gles2_cmd_helper.h" #include "gpu/command_buffer/client/gles2_implementation.h" #include "gpu/ipc/command_buffer_proxy.h" #include "ppapi/c/pp_graphics_3d.h" #include "ui/gl/gpu_preference.h" #ifdef ENABLE_GPU namespace content { PlatformContext3DImpl::PlatformContext3DImpl() : has_alpha_(false), command_buffer_(NULL), weak_ptr_factory_(this) { } PlatformContext3DImpl::~PlatformContext3DImpl() { if (command_buffer_) { DCHECK(channel_.get()); channel_->DestroyCommandBuffer(command_buffer_); command_buffer_ = NULL; } channel_ = NULL; } bool PlatformContext3DImpl::Init(const int32* attrib_list, PlatformContext3D* share_context) { // Ignore initializing more than once. if (command_buffer_) return true; RenderThreadImpl* render_thread = RenderThreadImpl::current(); if (!render_thread) return false; gfx::GpuPreference gpu_preference = gfx::PreferDiscreteGpu; channel_ = render_thread->EstablishGpuChannelSync( CAUSE_FOR_GPU_LAUNCH_PEPPERPLATFORMCONTEXT3DIMPL_INITIALIZE); if (!channel_.get()) return false; gfx::Size surface_size; std::vector<int32> attribs; // TODO(alokp): Change GpuChannelHost::CreateOffscreenCommandBuffer() // interface to accept width and height in the attrib_list so that // we do not need to filter for width and height here. if (attrib_list) { for (const int32_t* attr = attrib_list; attr[0] != PP_GRAPHICS3DATTRIB_NONE; attr += 2) { switch (attr[0]) { case PP_GRAPHICS3DATTRIB_WIDTH: surface_size.set_width(attr[1]); break; case PP_GRAPHICS3DATTRIB_HEIGHT: surface_size.set_height(attr[1]); break; case PP_GRAPHICS3DATTRIB_GPU_PREFERENCE: gpu_preference = (attr[1] == PP_GRAPHICS3DATTRIB_GPU_PREFERENCE_LOW_POWER) ? gfx::PreferIntegratedGpu : gfx::PreferDiscreteGpu; break; case PP_GRAPHICS3DATTRIB_ALPHA_SIZE: has_alpha_ = attr[1] > 0; // fall-through default: attribs.push_back(attr[0]); attribs.push_back(attr[1]); break; } } attribs.push_back(PP_GRAPHICS3DATTRIB_NONE); } CommandBufferProxyImpl* share_buffer = NULL; if (share_context) { PlatformContext3DImpl* share_impl = static_cast<PlatformContext3DImpl*>(share_context); share_buffer = share_impl->command_buffer_; } command_buffer_ = channel_->CreateOffscreenCommandBuffer( surface_size, share_buffer, "*", attribs, GURL::EmptyGURL(), gpu_preference); if (!command_buffer_) return false; if (!command_buffer_->Initialize()) return false; std::vector<gpu::Mailbox> names; if (!command_buffer_->GenerateMailboxNames(1, &names)) return false; DCHECK_EQ(names.size(), 1u); if (!command_buffer_->ProduceFrontBuffer(names[0])) return false; mailbox_ = names[0]; command_buffer_->SetChannelErrorCallback( base::Bind(&PlatformContext3DImpl::OnContextLost, weak_ptr_factory_.GetWeakPtr())); command_buffer_->SetOnConsoleMessageCallback( base::Bind(&PlatformContext3DImpl::OnConsoleMessage, weak_ptr_factory_.GetWeakPtr())); return true; } void PlatformContext3DImpl::GetBackingMailbox(gpu::Mailbox* mailbox) { *mailbox = mailbox_; } bool PlatformContext3DImpl::IsOpaque() { DCHECK(command_buffer_); return !has_alpha_; } gpu::CommandBuffer* PlatformContext3DImpl::GetCommandBuffer() { return command_buffer_; } int PlatformContext3DImpl::GetCommandBufferRouteId() { DCHECK(command_buffer_); return command_buffer_->GetRouteID(); } void PlatformContext3DImpl::SetContextLostCallback(const base::Closure& task) { context_lost_callback_ = task; } void PlatformContext3DImpl::SetOnConsoleMessageCallback( const ConsoleMessageCallback& task) { console_message_callback_ = task; } bool PlatformContext3DImpl::Echo(const base::Closure& task) { return command_buffer_->Echo(task); } void PlatformContext3DImpl::OnContextLost() { DCHECK(command_buffer_); if (!context_lost_callback_.is_null()) context_lost_callback_.Run(); } void PlatformContext3DImpl::OnConsoleMessage(const std::string& msg, int id) { DCHECK(command_buffer_); if (!console_message_callback_.is_null()) console_message_callback_.Run(msg, id); } } // namespace content #endif // ENABLE_GPU
29.271676
79
0.718009
[ "vector" ]
4ffda1ada8f576ae774378c6f9d23e9924d23c6e
3,783
cc
C++
src/coord/net/tcp_listener.cc
lujingwei002/coord
cb5e5723293d8529663ca89e0c1d6b8c348fffff
[ "MIT" ]
null
null
null
src/coord/net/tcp_listener.cc
lujingwei002/coord
cb5e5723293d8529663ca89e0c1d6b8c348fffff
[ "MIT" ]
null
null
null
src/coord/net/tcp_listener.cc
lujingwei002/coord
cb5e5723293d8529663ca89e0c1d6b8c348fffff
[ "MIT" ]
null
null
null
#include "coord/net/tcp_listener.h" #include "coord/net/tcp_agent.h" #include "coord/object/object.h" #include "coord/log/log.h" #include "coord/coord.h" #include <uv.h> #include <limits> namespace coord { namespace net { CC_IMPLEMENT(TcpListener, "coord::net::TcpListener") static void uv_connection_cb(uv_stream_t *server, int status) { TcpListener* listener = (TcpListener*)server->data; listener->recvTcpNew(status); } TcpListener* NewTcpListener(Coord* coord) { TcpListener* listener = new TcpListener(coord); return listener; } TcpListener::TcpListener(Coord* coord) : coord(coord) { this->handler = NULL; } TcpListener::~TcpListener() { } void TcpListener::recvTcpNew(int status) { if (status < 0) { this->coord->coreLogDebug("[TcpListener] recvTcpNew failed, error='%s'", uv_strerror(status)); return; } TcpAgent *agent = newTcpAgent(this->coord, this); uv_tcp_init(&this->coord->loop, (uv_tcp_t*)&agent->handle); int err = 0; err = uv_accept((uv_stream_t*)&this->server, (uv_stream_t*) &agent->handle); if (err < 0) { delete agent; this->coord->coreLogDebug("[TcpListener] recvTcpNew.uv_accept failed, error='%s'", uv_strerror(err)); return; } uv_os_sock_t sockfd; err = uv_fileno((uv_handle_t*)&agent->handle, &sockfd); if (err < 0) { delete agent; this->coord->coreLogDebug("[TcpListener] recvTcpNew.uv_fileno failed, error='%s'", uv_strerror(err)); return; } agent->sockfd = sockfd; int sessionId = sockfd; agent->sessionId = sessionId; agent->handle.data = agent; auto it = this->agentDict.find(sessionId); if (it != this->agentDict.end()){ delete agent; this->coord->coreLogDebug("[TcpListener] recvTcpNew failed, sessionId=%d, error='sessionId conflict'", sessionId); return; } struct sockaddr_in remoteSockAddr; int remoteSockAddrLen = sizeof(remoteSockAddr); char remoteAddr[32]; err = uv_tcp_getpeername((uv_tcp_t*)&agent->handle, (struct sockaddr *)&remoteSockAddr, &remoteSockAddrLen); if (err == 0){ int err = uv_ip4_name(&remoteSockAddr, remoteAddr, sizeof(remoteAddr)); if (err == 0){ agent->remoteAddr = remoteAddr; } } this->agentDict[sessionId] = agent; this->coord->coreLogDebug("[TcpListener] recvTcpNew, sockfd=%d, sessionId=%d", sockfd, sessionId); if(this->handler)this->handler->recvTcpNew(this, agent); agent->recvTcpNew(); } int TcpListener::Listen(const char* host, unsigned short port, int backlog){ this->coord->coreLogDebug("[TcpListener] Listen, host:%s, port=%d", host, port); this->server.data = this; uv_tcp_init(&this->coord->loop, &this->server); sockaddr_in addr; uv_ip4_addr(host, port, &addr); uv_tcp_bind(&this->server, (const struct sockaddr*)&addr, 0); int r = uv_listen((uv_stream_t*) &this->server, backlog, uv_connection_cb); if (r) { this->coord->coreLogError("[TcpListener] Listen failed, error='%s'", uv_strerror(r)); return -1; } return 0; } void TcpListener::recvAgentClose(TcpAgent* agent) { this->coord->coreLogDebug("[TcpListener] recvAgentClose ref=%d", agent->_ref); auto it = this->agentDict.find(agent->sessionId); if (it == this->agentDict.end()) { this->coord->coreLogDebug("[TcpListener] recvAgentClose failed, sessionid=%d, error='agent not found'", agent->sessionId); } else { this->agentDict.erase(it); this->coord->Destory(agent); } } void TcpListener::SetHandler(ITcpHandler* handler) { this->handler = handler; } void TcpListener::Close() { this->coord->coreLogError("[TcpListener] Close failed, error='not implement'"); } } }
33.184211
130
0.659265
[ "object" ]
8b051188fe3e2525f04aa5cb906761d7bb401999
2,622
cpp
C++
src/motion_functions/ChFunction_Sigma.cpp
scpeters/chrono
a7cefda35d8a445963297cbe2dbb3cdfb4397f16
[ "BSD-3-Clause" ]
1
2020-02-16T16:52:08.000Z
2020-02-16T16:52:08.000Z
src/motion_functions/ChFunction_Sigma.cpp
Milad-Rakhsha/Project-Chrono
6ab7abcd532cfb3c5e3876478fdd49c7ab783f63
[ "BSD-3-Clause" ]
null
null
null
src/motion_functions/ChFunction_Sigma.cpp
Milad-Rakhsha/Project-Chrono
6ab7abcd532cfb3c5e3876478fdd49c7ab783f63
[ "BSD-3-Clause" ]
null
null
null
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2011 Alessandro Tasora // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // /////////////////////////////////////////////////// // // ChFunction_Sigma.cpp // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "ChFunction_Sigma.h" namespace chrono { // Register into the object factory, to enable run-time // dynamic creation and persistence ChClassRegister<ChFunction_Sigma> a_registration_sigma; void ChFunction_Sigma::Copy (ChFunction_Sigma* source) { Set_start (source->start); Set_end (source->end); Set_amp (source->amp); } ChFunction* ChFunction_Sigma::new_Duplicate () { ChFunction_Sigma* m_func; m_func = new ChFunction_Sigma; m_func->Copy(this); return (m_func); } void ChFunction_Sigma::Extimate_x_range (double& xmin, double& xmax) { double mdx = end-start; xmin = start +mdx*0.1; xmax = end -mdx*0.1; } double ChFunction_Sigma::Get_y (double x) { double ret; double A = (end - start); if (x < start) return 0; if (x > end) return amp; else { ret = amp *( (3*(pow(((x-start)/A),2))) - 2*(pow(((x-start)/A),3)) ); } return ret; } double ChFunction_Sigma::Get_y_dx (double x) { double ret; double A = (end - start); if ((x < start) || (x > end)) ret = 0; else { ret = amp * ( 6*((x-start) / pow(A,2)) - 6*(pow((x-start),2)/pow(A,3)) ); } return ret; } double ChFunction_Sigma::Get_y_dxdx (double x) { double ret; double A = (end - start); if ((x < start) || (x > end)) ret = 0; else { ret = amp * ( 6*(1/pow(A,2)) - 12*((x-start)/pow(A,3)) ); } return ret; } void ChFunction_Sigma::StreamOUT(ChStreamOutBinary& mstream) { // class version number mstream.VersionWrite(1); // serialize parent class too ChFunction::StreamOUT(mstream); // stream out all member data mstream << start; mstream << end; mstream << amp; } void ChFunction_Sigma::StreamIN(ChStreamInBinary& mstream) { // class version number int version = mstream.VersionRead(); // deserialize parent class too ChFunction::StreamIN(mstream); // stream in all member data mstream >> start; mstream >> end; mstream >> amp; } void ChFunction_Sigma::StreamOUT(ChStreamOutAscii& mstream) { mstream << "FUNCT_CONST \n"; //***TO DO*** } } // END_OF_NAMESPACE____ // eof
19.863636
76
0.611365
[ "object" ]
8b07c7022fea3253c8001019b349b8d6e2861667
17,110
cpp
C++
PhysX_3.4/Source/SimulationController/src/ScShapeSim.cpp
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
1
2019-12-09T16:03:55.000Z
2019-12-09T16:03:55.000Z
PhysX_3.4/Source/SimulationController/src/ScShapeSim.cpp
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
null
null
null
PhysX_3.4/Source/SimulationController/src/ScShapeSim.cpp
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
null
null
null
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScBodySim.h" #include "ScStaticSim.h" #include "ScScene.h" #include "ScRbElementInteraction.h" #include "ScParticleBodyInteraction.h" #include "ScShapeInteraction.h" #include "ScTriggerInteraction.h" #include "ScSimStats.h" #include "ScObjectIDTracker.h" #include "GuHeightFieldUtil.h" #include "GuTriangleMesh.h" #include "GuConvexMeshData.h" #include "GuHeightField.h" #include "PxsContext.h" #include "BpSimpleAABBManager.h" #include "PxsTransformCache.h" #include "CmTransformUtils.h" #include "GuBounds.h" #include "PxsRigidBody.h" #include "ScSqBoundsManager.h" #include "PxsSimulationController.h" #if PX_USE_PARTICLE_SYSTEM_API #include "PtContext.h" #endif #if PX_USE_PARTICLE_SYSTEM_API && PX_SUPPORT_GPU_PHYSX #include "PxSceneGpu.h" #endif using namespace physx; using namespace Gu; using namespace Sc; // PT: keep local functions in cpp, no need to pollute the header. Don't force conversions to bool if not necessary. static PX_FORCE_INLINE PxU32 hasTriggerFlags(PxShapeFlags flags) { return PxU32(flags) & PxU32(PxShapeFlag::eTRIGGER_SHAPE); } static PX_FORCE_INLINE PxU32 isBroadPhase(PxShapeFlags flags) { return PxU32(flags) & PxU32(PxShapeFlag::eTRIGGER_SHAPE|PxShapeFlag::eSIMULATION_SHAPE); } namespace physx { extern bool gUnifiedHeightfieldCollision; } static PX_FORCE_INLINE void resetElementID(Sc::Scene& scene, Sc::ShapeSim& shapeSim) { PX_ASSERT(!shapeSim.isInBroadPhase()); scene.getDirtyShapeSimMap().reset(shapeSim.getElementID()); if(shapeSim.getSqBoundsId() != PX_INVALID_U32) shapeSim.destroySqBounds(); } void Sc::ShapeSim::initSubsystemsDependingOnElementID() { Sc::Scene& scScene = getScene(); Bp::BoundsArray& boundsArray = scScene.getBoundsArray(); const PxU32 index = getElementID(); PX_ALIGN(16, PxTransform absPos); getAbsPoseAligned(&absPos); PxsTransformCache& cache = scScene.getLowLevelContext()->getTransformCache(); cache.initEntry(index); cache.setTransformCache(absPos, 0, index); boundsArray.updateBounds(absPos, mCore.getGeometryUnion(), index, !gUnifiedHeightfieldCollision); { PX_PROFILE_ZONE("API.simAddShapeToBroadPhase", scScene.getContextId()); if(isBroadPhase(mCore.getFlags())) internalAddToBroadPhase(); else scScene.getAABBManager()->reserveSpaceForBounds(index); scScene.updateContactDistance(index, getContactOffset()); } if(scScene.getDirtyShapeSimMap().size() <= index) scScene.getDirtyShapeSimMap().resize(PxMax(index+1, (scScene.getDirtyShapeSimMap().size()+1) * 2u)); RigidSim& owner = getRbSim(); if(owner.isDynamicRigid() && static_cast<BodySim&>(owner).isActive()) createSqBounds(); // Init LL shape { mLLShape.mElementIndex = index; mLLShape.mShapeCore = const_cast<PxsShapeCore*>(&mCore.getCore()); if(owner.getActorType()==PxActorType::eRIGID_STATIC) { mLLShape.mBodySimIndex = 0xffffffff; } else { BodySim& bodySim = static_cast<BodySim&>(getActor()); const PxU32 nodeIndex = bodySim.getNodeIndex().index(); mLLShape.mBodySimIndex = nodeIndex; //mLLShape.mLocalBound = computeBounds(mCore.getGeometry(), PxTransform(PxIdentity)); } } } Sc::ShapeSim::ShapeSim(RigidSim& owner, const ShapeCore& core) : ElementSim (owner, ElementType::eSHAPE), mCore (core), mSqBoundsId (PX_INVALID_U32) { // sizeof(ShapeSim) = 32 bytes Sc::Scene& scScene = getScene(); mId = scScene.getShapeIDTracker().createID(); initSubsystemsDependingOnElementID(); } Sc::ShapeSim::~ShapeSim() { Sc::Scene& scScene = getScene(); resetElementID(scScene, *this); scScene.getShapeIDTracker().releaseID(mId); } Bp::FilterGroup::Enum ShapeSim::getBPGroup() const { bool isKinematic = false; BodySim* bs = getBodySim(); if(bs) isKinematic = bs->isKinematic(); RigidSim& rbSim = getRbSim(); return Bp::getFilterGroup(rbSim.getActorType()==PxActorType::eRIGID_STATIC, rbSim.getRigidID(), isKinematic); } PX_FORCE_INLINE void Sc::ShapeSim::internalAddToBroadPhase() { PX_ASSERT(!isInBroadPhase()); addToAABBMgr(mCore.getContactOffset(), getBPGroup(), Ps::IntBool(mCore.getCore().mShapeFlags & PxShapeFlag::eTRIGGER_SHAPE)); } PX_FORCE_INLINE void Sc::ShapeSim::internalRemoveFromBroadPhase(bool wakeOnLostTouch) { PX_ASSERT(isInBroadPhase()); removeFromAABBMgr(); Scene& scene = getScene(); PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs(); scene.getNPhaseCore()->onVolumeRemoved(this, wakeOnLostTouch ? PxU32(PairReleaseFlag::eWAKE_ON_LOST_TOUCH) : 0, outputs, scene.getPublicFlags() & PxSceneFlag::eADAPTIVE_FORCE); } void Sc::ShapeSim::removeFromBroadPhase(bool wakeOnLostTouch) { if(isInBroadPhase()) internalRemoveFromBroadPhase(wakeOnLostTouch); } void Sc::ShapeSim::reinsertBroadPhase() { if(isInBroadPhase()) internalRemoveFromBroadPhase(); // internalAddToBroadPhase(); Sc::Scene& scene = getScene(); // Sc::Scene::removeShape { //unregisterShapeFromNphase(shape.getCore()); // PT: "getID" is const but the addShape call used LLShape, which uses elementID, so.... scene.getSimulationController()->removeShape(getID()); } // Call ShapeSim dtor { resetElementID(scene, *this); } // Call ElementSim dtor { releaseID(); } // Call ElementSim ctor { initID(); } // Call ShapeSim ctor { initSubsystemsDependingOnElementID(); } // Sc::Scene::addShape { scene.getSimulationController()->addShape(&getLLShapeSim(), getID()); // PT: TODO: anything else needed here? //registerShapeInNphase(shapeCore); } } void Sc::ShapeSim::onFilterDataChange() { setElementInteractionsDirty(InteractionDirtyFlag::eFILTER_STATE, InteractionFlag::eFILTERABLE); } void Sc::ShapeSim::onResetFiltering() { if(isInBroadPhase()) reinsertBroadPhase(); } void Sc::ShapeSim::onMaterialChange() { setElementInteractionsDirty(InteractionDirtyFlag::eMATERIAL, InteractionFlag::eRB_ELEMENT); } void Sc::ShapeSim::onRestOffsetChange() { setElementInteractionsDirty(InteractionDirtyFlag::eREST_OFFSET, InteractionFlag::eRB_ELEMENT); } void Sc::ShapeSim::onContactOffsetChange() { if(isInBroadPhase()) getScene().getAABBManager()->setContactOffset(getElementID(), mCore.getContactOffset()); } void Sc::ShapeSim::onFlagChange(PxShapeFlags oldFlags) { PxShapeFlags newFlags = mCore.getFlags(); const bool oldBp = isBroadPhase(oldFlags)!=0; const bool newBp = isBroadPhase(newFlags)!=0; // Change of collision shape flags requires removal/add to broadphase if(oldBp != newBp) { if(!oldBp && newBp) internalAddToBroadPhase(); else internalRemoveFromBroadPhase(); } else { Scene& scene = getScene(); const PxSceneFlags sceneFlags = scene.getPublicFlags(); const bool wasTrigger = hasTriggerFlags(oldFlags)!=0; const bool isTrigger = hasTriggerFlags(newFlags)!=0; if(!(sceneFlags & PxSceneFlag::eDEPRECATED_TRIGGER_TRIGGER_REPORTS)) { if (wasTrigger != isTrigger) reinsertBroadPhase(); // re-insertion is necessary because trigger-trigger pairs get killed } else { scene.getAABBManager()->setVolumeType(this->getElementID(), PxU8((isTrigger ? Sc::ElementType::eTRIGGER : getElementType()))); if (wasTrigger != isTrigger) setElementInteractionsDirty(InteractionDirtyFlag::eFILTER_STATE, InteractionFlag::eFILTERABLE); } } PxShapeFlags hadSq = oldFlags&PxShapeFlag::eSCENE_QUERY_SHAPE, hasSq = newFlags&PxShapeFlag::eSCENE_QUERY_SHAPE; if(hasSq && !hadSq) { BodySim* body = getBodySim(); if(body && body->isActive()) createSqBounds(); } else if(hadSq && !hasSq) destroySqBounds(); } void Sc::ShapeSim::getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const { filterAttr = 0; const PxShapeFlags flags = mCore.getFlags(); if (hasTriggerFlags(flags)) filterAttr |= PxFilterObjectFlag::eTRIGGER; BodySim* b = getBodySim(); if (b) { if (!b->isArticulationLink()) { if (b->isKinematic()) filterAttr |= PxFilterObjectFlag::eKINEMATIC; setFilterObjectAttributeType(filterAttr, PxFilterObjectType::eRIGID_DYNAMIC); } else setFilterObjectAttributeType(filterAttr, PxFilterObjectType::eARTICULATION); } else { setFilterObjectAttributeType(filterAttr, PxFilterObjectType::eRIGID_STATIC); } filterData = mCore.getSimulationFilterData(); } void Sc::ShapeSim::getAbsPoseAligned(PxTransform* PX_RESTRICT globalPose) const { const PxTransform& shape2Actor = mCore.getCore().transform; const PxTransform* actor2World = NULL; if(getActor().getActorType()==PxActorType::eRIGID_STATIC) { PxsRigidCore& core = static_cast<StaticSim&>(getActor()).getStaticCore().getCore(); actor2World = &core.body2World; } else { PxsBodyCore& core = static_cast<BodySim&>(getActor()).getBodyCore().getCore(); if(!core.mIdtBody2Actor) { Cm::getDynamicGlobalPoseAligned(core.body2World, shape2Actor, core.getBody2Actor(), *globalPose); return; } actor2World = &core.body2World; } Cm::getStaticGlobalPoseAligned(*actor2World, shape2Actor, *globalPose); } Sc::BodySim* Sc::ShapeSim::getBodySim() const { ActorSim& a = getActor(); return a.isDynamicRigid() ? static_cast<BodySim*>(&a) : NULL; } PxsRigidCore& Sc::ShapeSim::getPxsRigidCore() const { ActorSim& a = getActor(); return a.isDynamicRigid() ? static_cast<BodySim&>(a).getBodyCore().getCore() : static_cast<StaticSim&>(a).getStaticCore().getCore(); } bool Sc::ShapeSim::actorIsDynamic() const { return getActor().isDynamicRigid(); } void Sc::ShapeSim::updateCached(PxU32 transformCacheFlags, Cm::BitMapPinned* shapeChangedMap) { PX_ALIGN(16, PxTransform absPose); getAbsPoseAligned(&absPose); Sc::Scene& scene = getScene(); const PxU32 index = getElementID(); scene.getLowLevelContext()->getTransformCache().setTransformCache(absPose, transformCacheFlags, index); scene.getBoundsArray().updateBounds(absPose, mCore.getGeometryUnion(), index, !gUnifiedHeightfieldCollision); if (shapeChangedMap && isInBroadPhase()) shapeChangedMap->growAndSet(index); } void Sc::ShapeSim::updateCached(PxsTransformCache& transformCache, Bp::BoundsArray& boundsArray) { const PxU32 index = getElementID(); PxsCachedTransform& ct = transformCache.getTransformCache(index); Ps::prefetchLine(&ct); getAbsPoseAligned(&ct.transform); ct.flags = 0; PxBounds3& b = boundsArray.begin()[index]; Gu::computeBounds(b, mCore.getGeometryUnion().getGeometry(), ct.transform, 0.0f, NULL, 1.0f, !physx::gUnifiedHeightfieldCollision); } void Sc::ShapeSim::updateContactDistance(PxReal* contactDistance, const PxReal inflation, const PxVec3 angVel, const PxReal dt, Bp::BoundsArray& boundsArray) { const PxU32 index = getElementID(); const PxBounds3& bounds = boundsArray.getBounds(index); PxReal radius = bounds.getExtents().magnitude(); //Heuristic for angular velocity... PxReal angularInflation = angVel.magnitude() * dt * radius; contactDistance[index] = getContactOffset() + inflation + angularInflation; } Ps::IntBool Sc::ShapeSim::updateSweptBounds() { Vec3p endOrigin, endExtent; const ShapeCore& shapeCore = mCore; const PxTransform& endPose = getScene().getLowLevelContext()->getTransformCache().getTransformCache(getElementID()).transform; PxReal ccdThreshold = computeBoundsWithCCDThreshold(endOrigin, endExtent, shapeCore.getGeometry(), endPose, NULL); PxBounds3 bounds = PxBounds3::centerExtents(endOrigin, endExtent); BodySim* body = getBodySim(); PxcRigidBody& rigidBody = body->getLowLevelBody(); PxsBodyCore& bodyCore = body->getBodyCore().getCore(); PX_ALIGN(16, PxTransform shape2World); Cm::getDynamicGlobalPoseAligned(rigidBody.mLastTransform, shapeCore.getShape2Actor(), bodyCore.getBody2Actor(), shape2World); PxBounds3 startBounds = computeBounds(shapeCore.getGeometry(), shape2World, !physx::gUnifiedHeightfieldCollision); const Ps::IntBool isFastMoving = (startBounds.getCenter() - endOrigin).magnitudeSquared() >= ccdThreshold * ccdThreshold ? 1 : 0; if (isFastMoving) bounds.include(startBounds); PX_ASSERT(bounds.minimum.x <= bounds.maximum.x && bounds.minimum.y <= bounds.maximum.y && bounds.minimum.z <= bounds.maximum.z); getScene().getBoundsArray().setBounds(bounds, getElementID()); return isFastMoving; } void ShapeSim::updateBPGroup() { if(isInBroadPhase()) { Sc::Scene& scene = getScene(); scene.getAABBManager()->setBPGroup(getElementID(), getBPGroup()); //reinsertBroadPhase(); } } void Sc::ShapeSim::markBoundsForUpdate(bool forceBoundsUpdate, bool isDynamic) { PX_UNUSED(isDynamic); Sc::Scene& scene = getScene(); if(forceBoundsUpdate) updateCached(0, &scene.getAABBManager()->getChangedAABBMgActorHandleMap()); else if(isInBroadPhase()) scene.getDirtyShapeSimMap().growAndSet(getElementID()); #if PX_USE_PARTICLE_SYSTEM_API #if PX_SUPPORT_GPU_PHYSX // PT: onShapeChange currently only used for GPU physics. Inlined 'getSceneGpu' call avoids // extra function calls and additional work from getPxsRigidCore(), etc Pt::Context* context = scene.getParticleContext(); if(context->getSceneGpuFast()) context->getSceneGpuFast()->onShapeChange(size_t(&mCore.getCore()), size_t(&getPxsRigidCore()), isDynamic); #endif #endif } static PX_FORCE_INLINE void updateInteraction(Sc::Scene& scene, Sc::Interaction* i, const bool isDynamic, const bool isAsleep) { if(i->getType() == Sc::InteractionType::eOVERLAP) { Sc::ShapeInteraction* si = static_cast<Sc::ShapeInteraction*>(i); si->resetManagerCachedState(); if(isAsleep) si->onShapeChangeWhileSleeping(isDynamic); } else if(i->getType() == Sc::InteractionType::eTRIGGER) (static_cast<Sc::TriggerInteraction*>(i))->forceProcessingThisFrame(scene); // trigger pairs need to be checked next frame #if PX_USE_PARTICLE_SYSTEM_API else if(i->getType() == Sc::InteractionType::ePARTICLE_BODY) (static_cast<Sc::ParticleElementRbElementInteraction *>(i))->onRbShapeChange(); #endif } void Sc::ShapeSim::onVolumeOrTransformChange(bool forceBoundsUpdate) { Sc::Scene& scene = getScene(); Sc::BodySim* body = getBodySim(); const bool isDynamic = (body != NULL); const bool isAsleep = body ? !body->isActive() : true; ElementSim::ElementInteractionIterator iter = getElemInteractions(); ElementSimInteraction* i = iter.getNext(); while(i) { updateInteraction(scene, i, isDynamic, isAsleep); i = iter.getNext(); } markBoundsForUpdate(forceBoundsUpdate, isDynamic); } bool notifyActorInteractionsOfTransformChange(Sc::ActorSim& actor) { bool isDynamic; bool isAsleep; if(actor.isDynamicRigid()) { isDynamic = true; isAsleep = !static_cast<Sc::BodySim&>(actor).isActive(); } else { isDynamic = false; isAsleep = true; } Sc::Scene& scene = actor.getScene(); PxU32 nbInteractions = actor.getActorInteractionCount(); Sc::Interaction** interactions = actor.getActorInteractions(); while(nbInteractions--) updateInteraction(scene, *interactions++, isDynamic, isAsleep); return isDynamic; } void Sc::ShapeSim::createSqBounds() { if(mSqBoundsId!=PX_INVALID_U32) return; Sc::BodySim* bodySim = getBodySim(); PX_ASSERT(bodySim); if(bodySim->usingSqKinematicTarget() || bodySim->isFrozen() || !bodySim->isActive()) return; if(mCore.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE) getScene().getSqBoundsManager().addShape(*this); } void Sc::ShapeSim::destroySqBounds() { if(mSqBoundsId!=PX_INVALID_U32) getScene().getSqBoundsManager().removeShape(*this); }
30.499109
177
0.7564
[ "shape", "transform" ]
8b0b7334bea3fcbb7f16fa02ec125a27ffb5da56
1,562
cpp
C++
dsa_zju_textbook/5.13.cpp
sonaspy/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
1
2018-11-28T09:38:23.000Z
2018-11-28T09:38:23.000Z
dsa_zju_textbook/5.13.cpp
NewGuonx/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
null
null
null
dsa_zju_textbook/5.13.cpp
NewGuonx/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
null
null
null
// author - sonaspy@outlook.com // coding - utf_8 #include <iostream> #include <vector> #include <string> #include <algorithm> #include <unordered_map> #define test() freopen("in", "r", stdin) using namespace std; struct Node { string word; int times = 0; bool operator<(const struct Node b) const { if (times == b.times) return word < b.word; return times > b.times; } }; void resolve(unordered_map<string, int> &mp, string &s) { for (int i = 0; i < s.size(); i++) { string word; while ((isdigit(s[i]) || isalpha(s[i]) || s[i] == '_') && i < s.size()) word.push_back(tolower(s[i++])); if (word.size()) { if(word.size()> 15) word = word.substr(0,15); mp[word]++; } } } int main(int argc, char const *argv[]) { /* code */ //test(); unordered_map<string, int> mp; vector<Node> list; string s; getline(cin, s); while (true) { resolve(mp, s); if (s.back() == '#') break; getline(cin, s); } for (auto i : mp) { Node tmp; tmp.word = i.first, tmp.times = i.second; list.push_back(tmp); } sort(list.begin(), list.end()); int num = list.size()/10; cout << list.size() << endl; for(int i = 0; i < num; i++) cout << list[i].times << ":" << list[i].word << endl; return 0; }
23.313433
83
0.460307
[ "vector" ]
8b0bc6588419901de5f3d88569a3e56a815ce90a
5,286
cpp
C++
extra/news/src/apk/dataset/dsmain/dsmain-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/dataset/dsmain/dsmain-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/dataset/dsmain/dsmain-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
// Copyright Nathaniel Christen 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <QApplication> #include <QGraphicsView> #include <QList> #include <QDebug> #include <QMessageBox> #include <QMenu> #include <QGraphicsItem> #include <QScreen> #include <QTimer> #include <QTime> #include <QImage> #include <QApplication> #include <QDesktopWidget> #include <QFileDialog> #include "defines.h" #include "ScignStage-ling/ScignStage-ling-dialog.h" #include "ScignStage-ling/xpdf-bridge.h" #ifdef USING_LEXPAIR #include "lexpair/lexpair-dialog.h" #endif // USING_LEXPAIR #include "dsmain/language-sample.h" #include "dsmain/language-sample-group.h" #include "dsmain/dataset.h" #ifdef USING_KPH #include "phaon-ir/phr-code-model.h" #include "phaon-lib/phr-runner.h" #include "phr-direct-eval/phr-direct-eval.h" #include "phaon-ir/table/phr-symbol-scope.h" #include "phaon-ir/table/phr-channel-group-table.h" #include "phaon-ir/scopes/phr-runtime-scope.h" #include "phaon-ir/scopes/phr-scope-system.h" extern void init_test_functions(PhaonIR& phr, PHR_Code_Model& pcm, PHR_Channel_Group_Table& table, PHR_Symbol_Scope& pss); #endif // USING_KPH #include "application-model/application-model.h" #ifdef USING_CONFIG_DIALOG #include "application-model/application-config-model.h" #include "application-model/application-model.h" #include "config-dialog/config-dialog.h" #endif #include "kans.h" #include "textio.h" USING_KANS(TextIO) #ifdef USING_KPH USING_KANS(Phaon) #endif //?USING_QSNS(ScignStage) #ifdef USING_CONFIG_DIALOG void launch_config_dialog(Config_Dialog*& dlg, QWidget* parent) { if(!dlg) { dlg = new Config_Dialog(parent); } dlg->set_reset_callback([]() { Application_Config_Model::reset( { DEFINES_SRC_FOLDER "/UNIBUILD-custom_defines.h", CHOICES_PRI_FOLDER "/UNIBUILD-custom_choices.pri", UNIBUILD_PRI_FOLDER "/build-custom.pro", CUSTOM_LIBS_PRI_FOLDER "/_xpdf.pri", CUSTOM_LIBS_PRI_FOLDER "/_kph.pri", CUSTOM_LIBS_PRI_FOLDER "/_ss3d.pri", }, ".reset"); }); dlg->set_proceed_callback([&dlg](QString qs) { qDebug() << qs; Application_Config_Model acm; acm.parse_config_code(qs); { QString result; QString f = acm.insert_to_defines(DEFINES_SRC_FOLDER "/UNIBUILD-custom_defines.h", result); save_file(f, result); } { QString result; QString f = acm.insert_to_choices(CHOICES_PRI_FOLDER "/UNIBUILD-custom_choices.pri", result); save_file(f, result); } { QString result; QString f = acm.insert_to_unibuild(UNIBUILD_PRI_FOLDER "/build-custom.pro", result); save_file(f, result); } { QMap<QString, QString> result; QMap<QString, QString> files {{ { "xpdf", CUSTOM_LIBS_PRI_FOLDER "/_xpdf.pri" }, { "kph", CUSTOM_LIBS_PRI_FOLDER "/_kph.pri" }, { "ss3d", CUSTOM_LIBS_PRI_FOLDER "/_ss3d.pri" } }}; acm.insert_to_custom_libs(files, result); QMapIterator<QString, QString> it(result); while(it.hasNext()) { it.next(); save_file(it.key(), it.value()); } } dlg->register_proceed_completed(qs); }); dlg->show(); } #endif //def HIDE int main(int argc, char **argv) { QApplication qapp(argc, argv); qapp.setWindowIcon(QIcon(DEFAULT_ICON_FOLDER "/app-icon.png")); Dataset ds; ds.load_from_file(DEFAULT_NTXH_FOLDER "/ctg.ngml.ntxh"); ds.set_pdf_path(DEFAULT_NTXH_FOLDER "/main.pdf"); #ifdef USING_XPDF XPDF_Bridge xpdf_bridge(argc, argv); ScignStage_Ling_Dialog dlg (&xpdf_bridge, &ds); #else ScignStage_Ling_Dialog dlg (nullptr, &ds); #endif dlg.set_replace_dataset_function([](QString path) -> Dataset* { Dataset* result = new Dataset; result->load_from_file(path); if(result->groups().isEmpty()) return nullptr; return result; }); #ifdef USING_KPH dlg.set_phr_init_function([&dlg](PHR_Runner& phr, PHR_Symbol_Scope*& pss) { PHR_Code_Model& pcm = phr.get_pcm(); pcm.set_origin(phr.origin()); pcm.set_direct_eval_fn(&phr_direct_eval); PHR_Runtime_Scope* prs = new PHR_Runtime_Scope(nullptr); pss = new PHR_Symbol_Scope(prs); init_test_functions(*phr.get_pcm().phaon_ir(), pcm, phr.get_table(), *pss); pcm.scopes()->phr_scope_queue().push_front(prs); }); #endif Application_Model apm(&dlg); dlg.set_application_model(&apm); #ifdef USING_LEXPAIR dlg.set_launch_lexpair_dialog_function([](QString s) { Lexpair_Dialog* dlg = new Lexpair_Dialog(Lexpair_Dialog::split(s), nullptr); dlg->show(); }); #endif // USING_LEXPAIR dlg.set_screenshot_function([&dlg, &qapp]() { QScreen* screen = QGuiApplication::primaryScreen(); if (!screen) return; QApplication::beep(); int target_window_id = dlg.winId(); QTimer::singleShot(10000, [=] { QPixmap pixmap = screen->grabWindow(target_window_id ); QString path = SCREENSHOTS_FOLDER "/ScignStage_Ling_Dialog.png"; qDebug() << "Saving to path: " << path; QFile file(path); if(file.open(QIODevice::WriteOnly)) { pixmap.save(&file, "PNG"); } }); }); #ifdef USING_CONFIG_DIALOG Config_Dialog* cdlg = nullptr; dlg.set_launch_config_function([&cdlg, &dlg]() { launch_config_dialog(cdlg, &dlg); }); #endif dlg.show(); qapp.exec(); }
22.210084
96
0.713961
[ "model" ]
8b110d7b24a994ae3d6d90ff5033cd4c6c480dcc
7,678
cpp
C++
build/plugins/qCMAT/qCMAT_autogen/include_Debug/UPWGDAZVBU/moc_ccColorScaleEditorDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
build/plugins/qCMAT/qCMAT_autogen/include_Debug/UPWGDAZVBU/moc_ccColorScaleEditorDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
null
null
null
build/plugins/qCMAT/qCMAT_autogen/include_Debug/UPWGDAZVBU/moc_ccColorScaleEditorDlg.cpp
ohanlonl/qCMAT
f6ca04fa7c171629f094ee886364c46ff8b27c0b
[ "BSD-Source-Code" ]
1
2019-02-03T12:19:42.000Z
2019-02-03T12:19:42.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'ccColorScaleEditorDlg.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../../../../qCC/ccColorScaleEditorDlg.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'ccColorScaleEditorDlg.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.11.1. 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 QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_ccColorScaleEditorDialog_t { QByteArrayData data[20]; char stringdata0[345]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_ccColorScaleEditorDialog_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_ccColorScaleEditorDialog_t qt_meta_stringdata_ccColorScaleEditorDialog = { { QT_MOC_LITERAL(0, 0, 24), // "ccColorScaleEditorDialog" QT_MOC_LITERAL(1, 25, 17), // "colorScaleChanged" QT_MOC_LITERAL(2, 43, 0), // "" QT_MOC_LITERAL(3, 44, 19), // "relativeModeChanged" QT_MOC_LITERAL(4, 64, 14), // "onStepSelected" QT_MOC_LITERAL(5, 79, 14), // "onStepModified" QT_MOC_LITERAL(6, 94, 19), // "deletecSelectedStep" QT_MOC_LITERAL(7, 114, 23), // "changeSelectedStepColor" QT_MOC_LITERAL(8, 138, 23), // "changeSelectedStepValue" QT_MOC_LITERAL(9, 162, 25), // "onCustomLabelsListChanged" QT_MOC_LITERAL(10, 188, 22), // "toggleCustomLabelsList" QT_MOC_LITERAL(11, 211, 16), // "copyCurrentScale" QT_MOC_LITERAL(12, 228, 16), // "saveCurrentScale" QT_MOC_LITERAL(13, 245, 18), // "deleteCurrentScale" QT_MOC_LITERAL(14, 264, 18), // "renameCurrentScale" QT_MOC_LITERAL(15, 283, 18), // "exportCurrentScale" QT_MOC_LITERAL(16, 302, 11), // "importScale" QT_MOC_LITERAL(17, 314, 14), // "createNewScale" QT_MOC_LITERAL(18, 329, 7), // "onApply" QT_MOC_LITERAL(19, 337, 7) // "onClose" }, "ccColorScaleEditorDialog\0colorScaleChanged\0" "\0relativeModeChanged\0onStepSelected\0" "onStepModified\0deletecSelectedStep\0" "changeSelectedStepColor\0changeSelectedStepValue\0" "onCustomLabelsListChanged\0" "toggleCustomLabelsList\0copyCurrentScale\0" "saveCurrentScale\0deleteCurrentScale\0" "renameCurrentScale\0exportCurrentScale\0" "importScale\0createNewScale\0onApply\0" "onClose" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_ccColorScaleEditorDialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 18, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 104, 2, 0x09 /* Protected */, 3, 1, 107, 2, 0x09 /* Protected */, 4, 1, 110, 2, 0x09 /* Protected */, 5, 1, 113, 2, 0x09 /* Protected */, 6, 0, 116, 2, 0x09 /* Protected */, 7, 0, 117, 2, 0x09 /* Protected */, 8, 1, 118, 2, 0x09 /* Protected */, 9, 0, 121, 2, 0x09 /* Protected */, 10, 1, 122, 2, 0x09 /* Protected */, 11, 0, 125, 2, 0x09 /* Protected */, 12, 0, 126, 2, 0x09 /* Protected */, 13, 0, 127, 2, 0x09 /* Protected */, 14, 0, 128, 2, 0x09 /* Protected */, 15, 0, 129, 2, 0x09 /* Protected */, 16, 0, 130, 2, 0x09 /* Protected */, 17, 0, 131, 2, 0x09 /* Protected */, 18, 0, 132, 2, 0x09 /* Protected */, 19, 0, 133, 2, 0x09 /* Protected */, // slots: parameters QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Int, 2, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Double, 2, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 2, QMetaType::Void, QMetaType::Bool, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void ccColorScaleEditorDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { ccColorScaleEditorDialog *_t = static_cast<ccColorScaleEditorDialog *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->colorScaleChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->relativeModeChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: _t->onStepSelected((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: _t->onStepModified((*reinterpret_cast< int(*)>(_a[1]))); break; case 4: _t->deletecSelectedStep(); break; case 5: _t->changeSelectedStepColor(); break; case 6: _t->changeSelectedStepValue((*reinterpret_cast< double(*)>(_a[1]))); break; case 7: _t->onCustomLabelsListChanged(); break; case 8: _t->toggleCustomLabelsList((*reinterpret_cast< bool(*)>(_a[1]))); break; case 9: _t->copyCurrentScale(); break; case 10: { bool _r = _t->saveCurrentScale(); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = std::move(_r); } break; case 11: _t->deleteCurrentScale(); break; case 12: _t->renameCurrentScale(); break; case 13: _t->exportCurrentScale(); break; case 14: _t->importScale(); break; case 15: _t->createNewScale(); break; case 16: _t->onApply(); break; case 17: _t->onClose(); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject ccColorScaleEditorDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_ccColorScaleEditorDialog.data, qt_meta_data_ccColorScaleEditorDialog, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *ccColorScaleEditorDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *ccColorScaleEditorDialog::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_ccColorScaleEditorDialog.stringdata0)) return static_cast<void*>(this); if (!strcmp(_clname, "Ui::ColorScaleEditorDlg")) return static_cast< Ui::ColorScaleEditorDlg*>(this); return QDialog::qt_metacast(_clname); } int ccColorScaleEditorDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 18) qt_static_metacall(this, _c, _id, _a); _id -= 18; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 18) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 18; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
39.57732
107
0.61305
[ "object" ]
8b1276b87cc70802e0c08e802c7f6362fc35de74
875
cpp
C++
atcoder/abc192/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
atcoder/abc192/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
atcoder/abc192/C/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
#include <bits/stdc++.h> using namespace std; using ll = int64_t; using ff = long double; vector<int> digits(ll x) { vector<int> xs; while (x > 0) { xs.push_back(x % 10); x /= 10; } return xs; } ll g1(vector<int>& digits) { sort(digits.begin(), digits.end(), greater<int>()); ll y = 0; for (auto d : digits) { y = y * 10 + d; } return y; } ll g2(vector<int>& digits) { sort(digits.begin(), digits.end(), less<int>()); ll y = 0; for (auto d : digits) { y = y * 10 + d; } return y; } ll f(ll x) { vector<int> xs = digits(x); return g1(xs) - g2(xs); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int N, K; cin >> N >> K; ll a = N; for (int i = 0; i < K; ++i) { a = f(a); } cout << a << endl; return 0; }
17.156863
55
0.48
[ "vector" ]
8b177ea480cf57bb3408fa6f3d5ed38fbaf20514
6,199
cpp
C++
src/Protocol/Protocol14x.cpp
TigerHix/MCServer
01e9d6311a4c27af044e8c9be3c67000124321e9
[ "Apache-2.0" ]
2
2019-01-03T13:30:44.000Z
2020-04-12T07:28:58.000Z
src/Protocol/Protocol14x.cpp
TigerHix/MCServer
01e9d6311a4c27af044e8c9be3c67000124321e9
[ "Apache-2.0" ]
null
null
null
src/Protocol/Protocol14x.cpp
TigerHix/MCServer
01e9d6311a4c27af044e8c9be3c67000124321e9
[ "Apache-2.0" ]
null
null
null
// Protocol14x.cpp /* Implements the 1.4.x protocol classes representing these protocols: - cProtocol142: - release 1.4.2 protocol (#47) - release 1.4.4 protocol (#49) - the same protocol class is used, because the only difference is in a packet that MCServer doesn't implement yet (ITEM_DATA) - release 1.4.5 protocol (same as 1.4.4) - cProtocol146: - release 1.4.6 protocol (#51) */ #include "Globals.h" #include "Protocol14x.h" #include "../Root.h" #include "../Server.h" #include "../ClientHandle.h" #include "../Item.h" #include "ChunkDataSerializer.h" #include "../Entities/Player.h" #include "../Mobs/Monster.h" #include "../UI/Window.h" #include "../Entities/Pickup.h" #include "../Entities/FallingBlock.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4127) #pragma warning(disable:4244) #pragma warning(disable:4231) #pragma warning(disable:4189) #pragma warning(disable:4702) #endif #ifdef _MSC_VER #pragma warning(pop) #endif #define HANDLE_PACKET_READ(Proc, Type, Var) \ Type Var; \ { \ if (!m_ReceivedData.Proc(Var)) \ { \ m_ReceivedData.CheckValid(); \ return PARSE_INCOMPLETE; \ } \ m_ReceivedData.CheckValid(); \ } enum { PACKET_UPDATE_TIME = 0x04, PACKET_PICKUP_SPAWN = 0x15, PACKET_SPAWN_OBJECT = 0x17, PACKET_ENTITY_METADATA = 0x28, PACKET_SOUND_PARTICLE_EFFECT = 0x3d } ; //////////////////////////////////////////////////////////////////////////////// // cProtocol142: cProtocol142::cProtocol142(cClientHandle * a_Client) : super(a_Client) { } int cProtocol142::ParseLocaleViewDistance(void) { HANDLE_PACKET_READ(ReadBEUTF16String16, AString, Locale); HANDLE_PACKET_READ(ReadChar, char, ViewDistance); HANDLE_PACKET_READ(ReadChar, char, ChatFlags); HANDLE_PACKET_READ(ReadChar, char, ClientDifficulty); HANDLE_PACKET_READ(ReadChar, char, ShouldShowCape); // <-- new in 1.4.2 m_Client->SetLocale(Locale); // TODO: m_Client->HandleViewDistance(ViewDistance); // TODO: m_Client->HandleChatFlags(ChatFlags); // Ignoring client difficulty return PARSE_OK; } void cProtocol142::SendPickupSpawn(const cPickup & a_Pickup) { cCSLock Lock(m_CSPacket); WriteByte (PACKET_PICKUP_SPAWN); WriteInt (a_Pickup.GetUniqueID()); WriteItem (a_Pickup.GetItem()); WriteVectorI((Vector3i)(a_Pickup.GetPosition() * 32)); WriteChar((char)(a_Pickup.GetSpeedX() * 8)); WriteChar((char)(a_Pickup.GetSpeedY() * 8)); WriteChar((char)(a_Pickup.GetSpeedZ() * 8)); Flush(); } void cProtocol142::SendSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) { cCSLock Lock(m_CSPacket); WriteByte(PACKET_SOUND_PARTICLE_EFFECT); WriteInt (a_EffectID); WriteInt (a_SrcX); WriteByte((Byte)a_SrcY); WriteInt (a_SrcZ); WriteInt (a_Data); WriteBool(0); Flush(); } void cProtocol142::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay) { cCSLock Lock(m_CSPacket); WriteByte (PACKET_UPDATE_TIME); WriteInt64(a_WorldAge); WriteInt64(a_TimeOfDay); Flush(); } //////////////////////////////////////////////////////////////////////////////// // cProtocol146: cProtocol146::cProtocol146(cClientHandle * a_Client) : super(a_Client) { } void cProtocol146::SendPickupSpawn(const cPickup & a_Pickup) { ASSERT(!a_Pickup.GetItem().IsEmpty()); cCSLock Lock(m_CSPacket); // Send a SPAWN_OBJECT packet for the base entity: WriteByte(PACKET_SPAWN_OBJECT); WriteInt (a_Pickup.GetUniqueID()); WriteByte(0x02); WriteInt ((int)(a_Pickup.GetPosX() * 32)); WriteInt ((int)(a_Pickup.GetPosY() * 32)); WriteInt ((int)(a_Pickup.GetPosZ() * 32)); WriteInt (1); WriteShort((short)(a_Pickup.GetSpeedX() * 32)); WriteShort((short)(a_Pickup.GetSpeedY() * 32)); WriteShort((short)(a_Pickup.GetSpeedZ() * 32)); WriteByte(0); WriteByte(0); // Send a ENTITY_METADATA packet with the slot info: WriteByte(PACKET_ENTITY_METADATA); WriteInt(a_Pickup.GetUniqueID()); WriteByte(0xaa); // a slot value at index 10 WriteItem(a_Pickup.GetItem()); WriteByte(0x7f); // End of metadata Flush(); } void cProtocol146::SendSpawnFallingBlock(const cFallingBlock & a_FallingBlock) { // Send a spawn object / vehicle packet cCSLock Lock(m_CSPacket); WriteByte(PACKET_SPAWN_OBJECT); WriteInt (a_FallingBlock.GetUniqueID()); WriteByte(70); WriteInt ((int)(a_FallingBlock.GetPosX() * 32)); WriteInt ((int)(a_FallingBlock.GetPosY() * 32)); WriteInt ((int)(a_FallingBlock.GetPosZ() * 32)); WriteByte (0); // Pitch WriteByte (0); // Yaw WriteInt (a_FallingBlock.GetBlockType()); // data indicator = blocktype WriteShort((short)(a_FallingBlock.GetSpeedX() * 400)); WriteShort((short)(a_FallingBlock.GetSpeedY() * 400)); WriteShort((short)(a_FallingBlock.GetSpeedZ() * 400)); Flush(); } void cProtocol146::SendSpawnObject(const cEntity & a_Entity, char a_ObjectType, int a_ObjectData, Byte a_Yaw, Byte a_Pitch) { cCSLock Lock(m_CSPacket); WriteByte(PACKET_SPAWN_OBJECT); WriteInt (a_Entity.GetUniqueID()); WriteChar(a_ObjectType); WriteInt ((int)(a_Entity.GetPosX() * 32)); WriteInt ((int)(a_Entity.GetPosY() * 32)); WriteInt ((int)(a_Entity.GetPosZ() * 32)); WriteByte(a_Pitch); WriteByte(a_Yaw); WriteInt (a_ObjectData); if (a_ObjectData != 0) { WriteShort((short)(a_Entity.GetSpeedX() * 400)); WriteShort((short)(a_Entity.GetSpeedY() * 400)); WriteShort((short)(a_Entity.GetSpeedZ() * 400)); } Flush(); } void cProtocol146::SendSpawnVehicle(const cEntity & a_Vehicle, char a_VehicleType, char a_VehicleSubType) { cCSLock Lock(m_CSPacket); WriteByte (PACKET_SPAWN_OBJECT); WriteInt (a_Vehicle.GetUniqueID()); WriteChar (a_VehicleType); WriteInt ((int)(a_Vehicle.GetPosX() * 32)); WriteInt ((int)(a_Vehicle.GetPosY() * 32)); WriteInt ((int)(a_Vehicle.GetPosZ() * 32)); WriteByte ((Byte)((a_Vehicle.GetPitch() / 360.f) * 256)); WriteByte ((Byte)((a_Vehicle.GetYaw() / 360.f) * 256)); WriteInt (a_VehicleSubType); if (a_VehicleSubType != 0) { WriteShort((short)(a_Vehicle.GetSpeedX() * 400)); WriteShort((short)(a_Vehicle.GetSpeedY() * 400)); WriteShort((short)(a_Vehicle.GetSpeedZ() * 400)); } Flush(); }
23.304511
157
0.689143
[ "object" ]
8b1b794af895e456eab9b08ebc0830fea0e6b7cd
43,342
cc
C++
caffe2/onnx/backend.cc
VisualJoyce/caffe2
4b5c2b5dfd13f057cd93558278d938d2bce0cff0
[ "Apache-2.0" ]
585
2015-08-10T02:48:52.000Z
2021-12-01T08:46:59.000Z
caffe2/onnx/backend.cc
PDFxy/caffe2
28523ff1ff33f18eaf8b04cc4e0f308826e1861a
[ "Apache-2.0" ]
23
2015-08-30T11:54:51.000Z
2017-03-06T03:01:07.000Z
caffe2/onnx/backend.cc
PDFxy/caffe2
28523ff1ff33f18eaf8b04cc4e0f308826e1861a
[ "Apache-2.0" ]
183
2015-08-10T02:49:04.000Z
2021-12-01T08:47:13.000Z
#include "backend.h" #include "device.h" #include "helper.h" #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "onnx/optimizer/optimize.h" #include "onnx/defs/schema.h" #include "onnx/checker.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl_lite.h" #include <cassert> #include <cmath> #include <iostream> #include <sstream> #include <unordered_map> #include <unordered_set> namespace caffe2 { namespace onnx { namespace { constexpr static int kKnownOpsetVersion = 5; bool AlmostEqual(double a, double b) { constexpr static double kEps = 1e-15; return (fabs(a - b) < kEps); } template <class T> bool TryConvertingTensorRawValues(const TensorProto &onnx_tensor, ::google::protobuf::RepeatedField<T> *field) { if (!onnx_tensor.has_raw_data()) { return false; } size_t raw_size = onnx_tensor.raw_data().size(); assert(raw_size % sizeof(T) == 0); size_t num_elements = raw_size / sizeof(T); const void *src_ptr = static_cast<const void *>(onnx_tensor.raw_data().data()); field->Resize(num_elements, 0); void *target_ptr = static_cast<void *>(field->mutable_data()); memcpy(target_ptr, src_ptr, raw_size); return true; } bool IsOperator(const std::string& op_type) { // pull in all the operators upon first invocation // Intentional leaky static std::set<std::string>* ops_ = new std::set<std::string>(caffe2::GetRegisteredOperators()); return ops_->count(caffe2::OpRegistryKey(op_type, "DEFAULT")); } //TODO We probably should have only one copy of this function (copied from pybind_state.cc) bool ParseProtobufFromLargeString(const std::string &str, ::google::protobuf::Message *proto) { ::google::protobuf::io::ArrayInputStream input_stream(str.data(), str.size()); ::google::protobuf::io::CodedInputStream coded_stream(&input_stream); // Set PlanDef message size limit to 1G. coded_stream.SetTotalBytesLimit(1024LL << 20, 512LL << 20); return proto->ParseFromCodedStream(&coded_stream); } caffe2::DeviceOption GetDeviceOption(const Device &onnx_device) { static const std::unordered_map<DeviceType, caffe2::DeviceType> m = { {DeviceType::CPU, caffe2::DeviceType::CPU}, {DeviceType::CUDA, caffe2::DeviceType::CUDA} }; caffe2::DeviceOption d; d.set_device_type(static_cast<int32_t>(m.at(onnx_device.type))); d.set_cuda_gpu_id(onnx_device.device_id); return d; } ModelProto OptimizeOnnx(const ModelProto &input, bool init) { std::vector<std::string> passes{"fuse_consecutive_transposes", "eliminate_nop_transpose", "fuse_transpose_into_gemm"}; if (init) { passes.emplace_back("split_init"); } else { passes.emplace_back("split_predict"); } return ONNX_NAMESPACE::optimization::Optimize(input, passes); } template <class T, class U> U LookUpWithDefault(const std::unordered_map<T, U> &map, const T &key, const U &default_value) { const auto it = map.find(key); if (it == map.end()) { return default_value; } else { return it->second; } } const ONNX_NAMESPACE::OpSchema &GetOnnxSchema(const std::string &key) { const auto *schema = ONNX_NAMESPACE::OpSchemaRegistry::Schema(key); if (!schema) { throw std::runtime_error("No ONNX schema registered for '" + key + "'!"); } return *schema; } void UpdateNames(const caffe2::OperatorDef& op) { for (const auto& n : op.input()) { DummyName::AddName(n); } for (const auto& n : op.output()) { DummyName::AddName(n); } } void BuildOperator( caffe2::OperatorDef* c2_op, const std::string &op_type, const std::vector<std::string> &inputs, const std::vector<std::string> &outputs, const std::vector<caffe2::Argument>& args) { c2_op->set_name(""); c2_op->set_type(op_type); for (const auto& input: inputs) { c2_op->add_input(input); } for (const auto& output: outputs) { c2_op->add_output(output); } for (const auto& arg: args) { auto* tmp = c2_op->add_arg(); tmp->CopyFrom(arg); } } void BuildOperator( caffe2::OperatorDef* c2_op, const std::string &op_type, const std::vector<std::string> &inputs, const std::vector<std::string> &outputs) { std::vector<caffe2::Argument> empty; BuildOperator(c2_op, op_type, inputs, outputs, empty); } void CopyOnnxAttrValueToCaffe2Arg( caffe2::Argument* arg, const AttributeProto& attr) { if (attr.has_f()) { arg->set_f(attr.f()); } else if (attr.has_i()) { arg->set_i(attr.i()); } else if (attr.has_s()) { arg->set_s(attr.s()); } else if (attr.has_t()) { // For proto, we convert it to serialized string std::string buffer; attr.t().SerializeToString(&buffer); arg->set_s(buffer); } else if (attr.floats_size()) { arg->mutable_floats()->CopyFrom(attr.floats()); } else if (attr.ints_size()) { arg->mutable_ints()->CopyFrom(attr.ints()); } else if (attr.strings_size()) { arg->mutable_strings()->CopyFrom(attr.strings()); } else { throw std::runtime_error( caffe2::MakeString("Unsupported ONNX attribute: ", attr.name())); } } } // namespace OnnxAttributes::OnnxAttributes(const NodeProto &node) { for(const auto& attr: node.attribute()) { onnx_attrs_.emplace(attr.name(), &attr); } } template <> int64_t OnnxAttributes::get(const std::string &key) const { int64_t value = 0; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto &attr = *it->second; value = attr.i(); } return value; } template <> float OnnxAttributes::get(const std::string &key) const { float value = 0.0; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto &attr = *it->second; value = attr.f(); } return value; } template <> ::google::protobuf::RepeatedPtrField<std::string> OnnxAttributes::get(const std::string &key) const { ::google::protobuf::RepeatedPtrField<std::string> value; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto& attr = *it->second; value.CopyFrom(attr.strings()); } return value; } template <> ::google::protobuf::RepeatedField<::google::protobuf::int64> OnnxAttributes::get(const std::string &key) const { ::google::protobuf::RepeatedField<::google::protobuf::int64> value; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto &attr = *it->second; value.CopyFrom(attr.ints()); } return value; } template <> const TensorProto *OnnxAttributes::get(const std::string &key) const { const TensorProto *value = nullptr; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto &attr = *it->second; value = &attr.t(); } return value; } ::google::protobuf::RepeatedPtrField<caffe2::Argument> OnnxAttributes::OnnxAttrToCaffe2Arg( std::function<std::string(const std::string &)> mapper) const { ::google::protobuf::RepeatedPtrField<caffe2::Argument> args; for (const auto& kv: onnx_attrs_) { // If the attribute was rewritten, we use it instead. Note that the // rewritten attibute still has the unmapped name const auto &attr = rewritten_onnx_attrs_.count(kv.first) ? rewritten_onnx_attrs_.at(kv.first) : (*kv.second); auto* arg = args.Add(); arg->set_name(mapper(attr.name())); CopyOnnxAttrValueToCaffe2Arg(arg, attr); } for (const auto& kv:rewritten_onnx_attrs_) { // If rewritten attribute doesn't appear in the original attributes, this is // a newlly added one and we need to add this to argument too if (!onnx_attrs_.count(kv.first)) { const auto& attr = kv.second; auto* arg = args.Add(); arg->set_name(mapper(attr.name())); CopyOnnxAttrValueToCaffe2Arg(arg, attr); } } return args; } const std::unordered_map<std::string, int>& Caffe2Backend::get_broken_operators() const { const static std::unordered_map<std::string, int> kBrokenOperators{}; return kBrokenOperators; } // Temporary hack for RNN related operators, as we don't have C++ interface in // C2 to build those operators yet const std::unordered_set<std::string>& Caffe2Backend::get_rnn_operators() const { const static std::unordered_set<std::string> kRNNOperators{ "LSTM", "GRU", "RNN"}; return kRNNOperators; } // Operators that are different between Caffe2 and // ONNX but only in their name. // In most cases, this should be empty - as the effort of ONNX is // to unify the operator definitions. const std::unordered_map<std::string, std::string>& Caffe2Backend::get_renamed_operators() const { const static std::unordered_map<std::string, std::string> kRenamedOperators{ {"Caffe2ConvTranspose", "ConvTranspose"}, {"GlobalMaxPool", "MaxPool"}, {"GlobalAveragePool", "AveragePool"}, {"Pad", "PadImage"}, {"Neg", "Negative"}, {"BatchNormalization", "SpatialBN"}, {"InstanceNormalization", "InstanceNorm"}, {"MatMul", "BatchMatMul"}, {"Upsample", "ResizeNearest"}, {"Identity", "Copy"}, {"InstanceNormalization", "InstanceNorm"}, {"Equal", "EQ"}, {"Less", "LT"}, {"Greater", "GT"}, {"Unsqueeze", "ExpandDims"}}; return kRenamedOperators; } const std::unordered_map<std::string, std::string>& Caffe2Backend::get_renamed_attrs() const { const static std::unordered_map<std::string, std::string> kRenamedAttrs{ {"kernel_shape", "kernels"}}; return kRenamedAttrs; } const std:: unordered_map<std::string, std::unordered_map<std::string, std::string>>& Caffe2Backend::get_per_op_renamed_attrs() const { const static std:: unordered_map<std::string, std::unordered_map<std::string, std::string>> kPerOpRenamedAttrs = {{"Squeeze", {{"axes", "dims"}}}, {"Unsqueeze", {{"axes", "dims"}}}, {"Transpose", {{"perm", "axes"}}}, {"Upsample", {{"mode", ""}}}, {"ConvTranspose", {{"output_padding", "adjs"}}}, {"Selu", {{"gamma", "scale"}}}}; return kPerOpRenamedAttrs; } // operators whose behavior is different beyond renaming // the value is an attribute of this class that is a // function from ToffeIR node_def to caffe2 op_def const std::unordered_map<std::string, Caffe2Backend::SpecialOpConverter>& Caffe2Backend::get_special_operators() const { const static std:: unordered_map<std::string, Caffe2Backend::SpecialOpConverter> kSpecialOperators = { {"Constant", &Caffe2Backend::CreateConstant}, {"Conv", &Caffe2Backend::CreateConvePoolOpBase}, {"AveragePool", &Caffe2Backend::CreateConvePoolOpBase}, {"GlobalAveragePool", &Caffe2Backend::CreateConvePoolOpBase}, {"GlobalMaxPool", &Caffe2Backend::CreateConvePoolOpBase}, {"MaxPool", &Caffe2Backend::CreateConvePoolOpBase}, {"Reshape", &Caffe2Backend::CreateReshape}, {"Gather", &Caffe2Backend::CreateGather}, {"Gemm", &Caffe2Backend::CreateGemm}, {"Pad", &Caffe2Backend::CreatePad}, {"Concat", &Caffe2Backend::CreateConcat}, {"LogSoftmax", &Caffe2Backend::CreateLogSoftmax}, {"Slice", &Caffe2Backend::CreateSlice}, {"Sqrt", &Caffe2Backend::CreateSqrt}, {"Reciprocal", &Caffe2Backend::CreateReciprocal}, {"MatMul", &Caffe2Backend::CreateMatMul}}; return kSpecialOperators; } //============================ // Special Operator Converters //============================ Caffe2Ops Caffe2Backend::CreateConstant(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node, int opset_version) { assert(onnx_node->node.output_size() == 1); Caffe2Ops ret; auto *c2_op = ret.ops.Add(); const auto *value = onnx_node->attributes.get<const TensorProto *>("value"); BuildTensorFillingOp(c2_op, *value, onnx_node->node.output(0)); return ret; } // Note [Caffe2 ConvPoolOpBase] // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // To understand what is going on here, we have to talk a little bit about // Caffe2's internals. // // First, it's important to know that all of Caffe2's pooling and convolution // operators inherit from "ConvPoolOpBase", which is an abstract class that // defines all of the attributes (kernels, dilations, strides, etc) which one // sees on these operators. Unfortunately, Caffe2's documentation generator // doesn't know how to handle cases like this, so for example, if you look at // the docs for MaxPool at // <https://caffe2.ai/docs/operators-catalogue.html#maxpool> you won't see any // of the attributes. You have to go source diving to find the information; in // particular, you want to look at: // https://github.com/caffe2/caffe2/blob/master/caffe2/operators/conv_pool_op_base.h // This class handles *global* pooling as well. // // Second, it's important to know what Caffe2 expects for padding, which can // be somewhat difficult to understand from the code because Caffe2 handles // both singular/pluralized spellings of padding, and there is also legacy // padding business. The short version of the story is that, for NON-legacy // padding (which is what we want to output), padding is expected to be // *twice* the size of kernels. So if you have a 2D convolution, Caffe2 // will accept two values in 'kernels', but FOUR values in 'pads'; // furthermore, this is *mandatory.* // // Finally, ConvPoolOpBase is not the only class of it's kind; there is // also ConvTransposeUnpoolBase, which backs ConvTranspose. So don't // be tricked by the fact that Conv and ConvTranspose have similar // parameters; they exercise different codepaths and need to be handled // differently. Caffe2Ops Caffe2Backend::CreateConvePoolOpBase(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node, int opset_version) { const auto& node = onnx_node->node; auto& attributes = onnx_node->attributes; if (node.op_type().find("Global") == 0) { auto* attr = attributes.AddRewrittenAttibute("global_pooling"); attr->set_i(1); } if (attributes.HasAttribute("kernel_shape") && attributes.HasAttribute("pads")) { auto kernel_shape = attributes .get<::google::protobuf::RepeatedField<::google::protobuf::int64>>( "kernel_shape"); auto pads = attributes .get<::google::protobuf::RepeatedField<::google::protobuf::int64>>( "pads"); if (kernel_shape.size() == pads.size()) { // Caffe2 requires pads to be twice the size of kernels. auto* attr = attributes.AddRewrittenAttibute("pads"); attr->mutable_ints()->CopyFrom(pads); attr->mutable_ints()->MergeFrom(pads); } } return CommonOnnxNodeToCaffe2Ops(init_model, pred_model, onnx_node, opset_version); } Caffe2Ops Caffe2Backend::CreateReshape(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node, int opset_version) { auto c2_op = CommonOnnxNodeToCaffe2Ops(init_model, pred_model, onnx_node, opset_version); assert(c2_op.ops.size() == 1); auto* op = c2_op.ops.Mutable(0); op->add_output(DummyName::NewDummyName()); return c2_op; } Caffe2Ops Caffe2Backend::CreateSqrt( const ModelProto& init_model, const ModelProto& pred_model, OnnxNode* onnx_node, int opset_version) { const auto& node = onnx_node->node; if (node.input_size() != 1 || node.output_size() != 1) { throw std::runtime_error("Caffe2 Sqrt should have 1 input and 1 output"); } Caffe2Ops ret; auto *c2_op = ret.ops.Add(); caffe2::Argument exponent; exponent.set_name("exponent"); exponent.set_f(0.5); BuildOperator(c2_op, "Pow", {node.input(0)}, {node.output(0)}, {exponent}); return ret; } Caffe2Ops Caffe2Backend::CreateReciprocal( const ModelProto& init_model, const ModelProto& pred_model, OnnxNode* onnx_node, int opset_version) { const auto& node = onnx_node->node; if (node.input_size() != 1 || node.output_size() != 1) { throw std::runtime_error("Caffe2 Reciprocal should have 1 input and 1 output"); } Caffe2Ops ret; auto *c2_op = ret.ops.Add(); caffe2::Argument exponent; exponent.set_name("exponent"); exponent.set_f(-1.0); BuildOperator(c2_op, "Pow", {node.input(0)}, {node.output(0)}, {exponent}); return ret; } Caffe2Ops Caffe2Backend::CreateGather( const ModelProto& init_model, const ModelProto& pred_model, OnnxNode* onnx_node, int opset_version) { const auto& node = onnx_node->node; if (node.input_size() < 2 || node.output_size() < 1) { throw std::runtime_error("Caffe2 Gather should have 2 inputs and 1 output"); } Caffe2Ops ret; auto *c2_op = ret.ops.Add(); std::vector<std::string> inputs; inputs.emplace_back(node.input(0)); inputs.emplace_back(node.input(1)); std::vector<std::string> outputs; outputs.emplace_back(node.output(0)); auto axis = onnx_node->attributes.get<int64_t>("axis", 0L); if (axis == 0) { BuildOperator(c2_op, "Gather", inputs, outputs); } else if (axis == 1) { BuildOperator(c2_op, "BatchGather", inputs, outputs); } else { throw std::runtime_error(caffe2::MakeString( "Caffe2 only supports Gather with axis being 1 or 2, ", "whereas axis is ", axis)); } return ret; } Caffe2Ops Caffe2Backend::CreateGemm(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node, int opset_version) { const auto& node = onnx_node->node; if (node.input_size() < 3 || node.output_size() < 1) { throw std::runtime_error("Caffe2 Gemm should have 3 inputs and 1 output"); } Caffe2Ops ret; auto input_a = node.input(0); auto input_b = node.input(1); auto input_c = node.input(2); auto output = node.output(0); auto alpha = onnx_node->attributes.get<float>("alpha", 1.0); auto beta = onnx_node->attributes.get<float>("beta", 1.0); if (!AlmostEqual(alpha, 1)) { auto scaled_a = DummyName::NewDummyName(); caffe2::Argument scale; scale.set_name("scale"); scale.set_f(alpha); auto *c2_op = ret.ops.Add(); BuildOperator(c2_op, "Scale", {input_a}, {scaled_a}, {scale}); input_a = scaled_a; } if (!AlmostEqual(beta, 1)) { auto scaled_c = DummyName::NewDummyName(); caffe2::Argument scale; scale.set_name("scale"); scale.set_f(beta); auto *c2_op = ret.ops.Add(); BuildOperator(c2_op, "Scale", {input_c}, {scaled_c}, {scale}); input_c = scaled_c; } auto trans_a = onnx_node->attributes.get<int64_t>("transA", 0L); auto trans_b = onnx_node->attributes.get<int64_t>("transB", 0L); auto broadcast = onnx_node->attributes.get<int64_t>("broadcast", 0L); if ( (!trans_a) && trans_b && broadcast) { auto *c2_op = ret.ops.Add(); BuildOperator(c2_op, "FC", {input_a, input_b, input_c}, {output}); } else { auto ab = DummyName::NewDummyName(); caffe2::Argument arg_trans_a; arg_trans_a.set_name("trans_a"); arg_trans_a.set_i(trans_a); caffe2::Argument arg_trans_b; arg_trans_b.set_name("trans_b"); arg_trans_b.set_i(trans_b); caffe2::Argument arg_broadcast; arg_broadcast.set_name("broadcast"); arg_broadcast.set_i(broadcast); auto *c2_op = ret.ops.Add(); BuildOperator(c2_op, "MatMul", {input_a, input_b}, {ab}, {arg_trans_a, arg_trans_b}); c2_op = ret.ops.Add(); BuildOperator(c2_op, "Add", {ab, input_c}, {output}, {arg_broadcast}); } return ret; } Caffe2Ops Caffe2Backend::CreatePad(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node, int opset_version) { const auto& node = onnx_node->node; auto& attributes = onnx_node->attributes; ::google::protobuf::RepeatedField<::google::protobuf::int64> pads; std::string pad_name = opset_version < 2 ? "paddings" : "pads"; pads = attributes .get<::google::protobuf::RepeatedField<::google::protobuf::int64>>( pad_name); std::string str; std::stringstream ss; ss << "["; for (const auto& i: pads) { ss << i << ", "; } ss << "]"; str = ss.str(); // Guard the invalid (negative) pads attribute. for (const auto i : pads) { if (i < 0) { throw std::runtime_error(caffe2::MakeString( "ONNX does not support negative pads in Pad, but get ", str)); } } // first two dim is for batch and channel. Note that now all the values are // non-negative if (!(pads.size() == 8 && (pads.Get(0) + pads.Get(1) + pads.Get(4) + pads.Get(5) == 0))) { throw std::runtime_error(caffe2::MakeString( "Caffe2 only supports padding 2D Tensor, whereas padding is ", str)); } // rewrite the padding info auto* attr = attributes.AddRewrittenAttibute(pad_name); attr->add_ints(pads.Get(2)); attr->add_ints(pads.Get(3)); attr->add_ints(pads.Get(6)); attr->add_ints(pads.Get(7)); return CommonOnnxNodeToCaffe2Ops(init_model, pred_model, onnx_node, opset_version); } // TODO: Caffe2 Concat has an extra output. It should be only // used when doing training, so we should change Caffe2 to allow // 1 output. Caffe2Ops Caffe2Backend::CreateConcat(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node, int opset_version) { auto c2_op = CommonOnnxNodeToCaffe2Ops(init_model, pred_model, onnx_node, opset_version); assert(c2_op.ops.size() == 1); auto* op = c2_op.ops.Mutable(0); op->add_output(DummyName::NewDummyName()); return c2_op; } Caffe2Ops Caffe2Backend::CreateLogSoftmax(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node, int opset_version) { const auto& node = onnx_node->node; if (node.input_size() < 1 || node.output_size() < 1) { throw std::runtime_error("LogSoftmax should have 1 input and 1 output"); } auto axis = onnx_node->attributes.get<int64_t>("axis", 1L); caffe2::Argument arg_axis; arg_axis.set_name("axis"); arg_axis.set_i(axis); auto softmax_a = DummyName::NewDummyName(); Caffe2Ops ret; auto *c2_op = ret.ops.Add(); BuildOperator(c2_op, "Softmax", {node.input(0)}, {softmax_a}, {arg_axis}); c2_op = ret.ops.Add(); BuildOperator(c2_op, "Log", {softmax_a}, {node.output(0)}); return ret; } Caffe2Ops Caffe2Backend::CreateSlice(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node,int opset_version) { auto op_tmp = CommonOnnxNodeToCaffe2Ops(init_model, pred_model, onnx_node, opset_version); assert(op_tmp.ops.size() == 1); auto* op = op_tmp.ops.Mutable(0); std::unordered_map<std::string, caffe2::Argument*> args; for (auto& arg: *op->mutable_arg()) { args.emplace(arg.name(), &arg); } caffe2::Argument starts_vals; starts_vals.set_name("values"); auto pos = args.find("starts"); if (pos != args.end()) { for (auto i: pos->second->ints()) { starts_vals.add_ints(i); } args.erase(pos); } caffe2::Argument ends_vals; ends_vals.set_name("values"); pos = args.find("ends"); if (pos != args.end()) { for (auto i: pos->second->ints()) { ends_vals.add_ints(i < 0 ? i - 1 : i); } args.erase(pos); } caffe2::Argument axes_vals; axes_vals.set_name("values"); pos = args.find("axes"); if (pos != args.end()) { for (auto i: pos->second->ints()) { axes_vals.add_ints(i); } args.erase(pos); } else { auto ndim = starts_vals.ints_size(); for (int64_t i = 0; i < ndim; ++i) { axes_vals.add_ints(i); } } assert(op->input_size() >= 1); auto data = op->input(0); auto shape_tensor = DummyName::NewDummyName(); Caffe2Ops ret; auto *c2_op = ret.ops.Add(); BuildOperator(c2_op, "Shape", {data}, {shape_tensor}); auto axes_tensor = DummyName::NewDummyName(); c2_op = ret.ops.Add(); { caffe2::Argument shape; shape.set_name("shape"); shape.add_ints(axes_vals.ints_size()); BuildOperator(c2_op, "GivenTensorIntFill", {}, {axes_tensor}, {shape, axes_vals}); } auto starts_vals_tensor = DummyName::NewDummyName(); auto starts_tensor = DummyName::NewDummyName(); auto casted_starts_tensor = DummyName::NewDummyName(); c2_op = ret.ops.Add(); { caffe2::Argument shape_starts; shape_starts.set_name("shape"); shape_starts.add_ints(starts_vals.ints_size()); BuildOperator(c2_op, "GivenTensorInt64Fill", {}, {starts_vals_tensor}, {shape_starts, starts_vals}); } caffe2::Argument dtype; dtype.set_name("dtype"); dtype.set_i(static_cast<int64_t>(caffe2::TensorProto::INT64)); caffe2::Argument constant; constant.set_name("value"); constant.set_i(0); c2_op = ret.ops.Add(); BuildOperator(c2_op, "ConstantFill", {shape_tensor}, {starts_tensor}, {dtype, constant}); c2_op = ret.ops.Add(); BuildOperator(c2_op, "ScatterAssign", {starts_tensor, axes_tensor, starts_vals_tensor}, {starts_tensor}); // Slice only accepts starts as int caffe2::Argument to; to.set_name("to"); to.set_i(static_cast<int64_t>(caffe2::TensorProto::INT32)); c2_op = ret.ops.Add(); BuildOperator(c2_op, "Cast", {starts_tensor}, {casted_starts_tensor}, {to}); auto ends_vals_tensor = DummyName::NewDummyName(); auto ends_tensor = DummyName::NewDummyName(); auto casted_ends_tensor = DummyName::NewDummyName(); c2_op = ret.ops.Add(); { caffe2::Argument shape_ends; shape_ends.set_name("shape"); shape_ends.add_ints(ends_vals.ints_size()); BuildOperator(c2_op, "GivenTensorInt64Fill", {}, {ends_vals_tensor}, {shape_ends, ends_vals}); } constant.set_i(-1); c2_op = ret.ops.Add(); BuildOperator(c2_op, "ConstantFill", {shape_tensor}, {ends_tensor}, {dtype, constant}); c2_op = ret.ops.Add(); BuildOperator(c2_op, "ScatterAssign", {ends_tensor, axes_tensor, ends_vals_tensor}, {ends_tensor}); // Slice only accepts ends as int c2_op = ret.ops.Add(); BuildOperator(c2_op, "Cast", {ends_tensor}, {casted_ends_tensor}, {to}); // attach the original op at the end c2_op = ret.ops.Add(); c2_op->CopyFrom(*op); c2_op->mutable_input()->Clear(); c2_op->add_input(data); c2_op->add_input(casted_starts_tensor); c2_op->add_input(casted_ends_tensor); c2_op->mutable_arg()->Clear(); for (const auto& kv: args) { c2_op->add_arg()->CopyFrom(*kv.second); } return ret; } Caffe2Ops Caffe2Backend::CreateMatMul( const ModelProto& init_model, const ModelProto& pred_model, OnnxNode* onnx_node, int opset_version) { const auto& node = onnx_node->node; if (node.input_size() != 2) { throw std::runtime_error("MatMul should have 2 inputs"); } auto c2_op = CommonOnnxNodeToCaffe2Ops(init_model, pred_model, onnx_node, opset_version); assert(c2_op.ops.size() == 1); auto* op = c2_op.ops.Mutable(0); auto* broadcast_arg = op->add_arg(); broadcast_arg->set_name("broadcast"); broadcast_arg->set_i(1); return c2_op; } //============================================== // Rest of the member funtions for Caffe2Backend //============================================== void Caffe2Backend::InplaceRewrite(GraphProto* graph) { auto* nodes = graph->mutable_node(); auto renamed = InplaceRewrite(nodes); for (int i = 0; i < graph->output_size(); ++i) { graph->mutable_output(i)->set_name(LookUpWithDefault( renamed, graph->output(i).name(), graph->output(i).name())); } } // \brief currently we use this to translate ONNX-style // consumed_input annotations to Caffe2-style in place // updates (use same input and output names). std::unordered_map<std::string, std::string> Caffe2Backend::InplaceRewrite( ::google::protobuf::RepeatedPtrField<NodeProto> *nodes) { std::unordered_map<std::string, std::string> renamed; for (auto& node: *nodes) { for (auto& input: *node.mutable_input()) { input = LookUpWithDefault(renamed, input, input); } // Get `consumed_inputs` attribute and remove it from node attributes ::google::protobuf::RepeatedField<::google::protobuf::int64> consumed_inputs; int found_idx = -1; for (int i = 0; i < node.attribute_size(); ++i) { const auto& attr = node.attribute(i); if (attr.name() == "consumed_inputs") { consumed_inputs.CopyFrom(attr.ints()); found_idx = i; break; } } if (found_idx >= 0 && found_idx < node.attribute_size()) { if (found_idx != node.attribute_size() - 1) { node.mutable_attribute(found_idx)->CopyFrom( node.attribute(node.attribute_size() - 1)); } node.mutable_attribute()->RemoveLast(); } std::set<int> output_indexes; for (int i = 0; i < node.output_size(); ++i) { output_indexes.insert(i); } const auto& schema = GetOnnxSchema(node.op_type()); int i = 0; for (const auto& consumed: consumed_inputs) { if (!consumed) { ++i; continue; } auto output_idx = schema.consumed(i).second; // consumed outputs are not always present // for instance batch norm in test mode // does not return the consumed inputs if (output_idx < node.output_size()) { output_indexes.erase(output_idx); auto old_val = node.output(output_idx); auto new_val = node.input(i); node.set_output(output_idx, new_val); renamed[old_val] = new_val; } ++i; } for (auto idx: output_indexes) { auto name = node.output(idx); node.set_output(idx, LookUpWithDefault(renamed, name, name)); } } return renamed; } std::unordered_set<std::string> Caffe2Backend::AllNamesInGraph(const GraphProto &graph) { std::unordered_set<std::string> names; for(const auto& input: graph.input()) { names.emplace(input.name()); } for(const auto& output: graph.output()) { names.emplace(output.name()); } for (const auto& node: graph.node()) { for (const auto &n : node.input()) { names.emplace(n); } for (const auto &n : node.output()) { names.emplace(n); } } return names; } // This translator performs the basic translation of ONNX nodes into // Caffe2 operators. Besides doing a straightforward marshalling from // one format to another, it also does these extra things: // // - Renames operators based on 'renamed_operators' // - Renames attributes based on 'renamed_attrs' and // 'get_per_op_renamed_attrs' // // If you're writing a custom translator, consider calling this first, // and then fixing things up further. Caffe2Ops Caffe2Backend::CommonOnnxNodeToCaffe2Ops( const ModelProto &init_model, const ModelProto &pred_model, OnnxNode *onnx_node, int opset_version) { Caffe2Ops ret; auto* c2_op = ret.ops.Add(); const auto& node = onnx_node->node; c2_op->mutable_input()->MergeFrom(node.input()); c2_op->mutable_output()->MergeFrom(node.output()); c2_op->set_name(node.name()); const auto onnx_op_type = node.op_type(); auto broken_version = LookUpWithDefault( get_broken_operators(), onnx_op_type, std::numeric_limits<int>::max()); if (broken_version <= opset_version) { throw std::runtime_error( caffe2::MakeString("Don't know how to translate op ", onnx_op_type, " in ONNX operator set v", opset_version, " (I only support prior to v", broken_version)); } c2_op->set_type( LookUpWithDefault(get_renamed_operators(), onnx_op_type, onnx_op_type)); if (!IsOperator(c2_op->type())) { throw std::runtime_error( caffe2::MakeString("Don't know how to translate op ", onnx_op_type)); } auto mapper = [&, this](const std::string& k) { const auto it = get_per_op_renamed_attrs().find(onnx_op_type); if (it != get_per_op_renamed_attrs().end()) { const auto it_op = it->second.find(k); if (it_op != it->second.end()) { return it_op->second; } } const auto it_global = get_renamed_attrs().find(k); if (it_global != get_renamed_attrs().end()) { return it_global->second; } return k; }; c2_op->mutable_arg()->MergeFrom( onnx_node->attributes.OnnxAttrToCaffe2Arg(mapper)); return ret; } Caffe2Ops Caffe2Backend::ConvertNode(const std::string& node_str, int opset_version) { ::google::protobuf::RepeatedPtrField<NodeProto> nodes; auto* n = nodes.Add(); ParseProtobufFromLargeString(node_str, n); InplaceRewrite(&nodes); ModelProto init_model; ModelProto pred_model; OnnxNode onnx_node = OnnxNode(nodes.Get(0)); return OnnxNodeToCaffe2Ops(init_model, pred_model, &onnx_node, opset_version); } Caffe2Ops Caffe2Backend::OnnxNodeToCaffe2Ops(const ModelProto &init_model, const ModelProto &pred_model, OnnxNode* onnx_node, int opset_version) { if (get_special_operators().count(onnx_node->node.op_type())) { return (this->*get_special_operators().at(onnx_node->node.op_type()))( init_model, pred_model, onnx_node, opset_version); } else { return CommonOnnxNodeToCaffe2Ops(init_model, pred_model, onnx_node, opset_version); } } void Caffe2Backend::OnnxToCaffe2( caffe2::NetDef *init_net, caffe2::NetDef *pred_net, const ModelProto &onnx_model, const std::string &device, int opset_version, bool include_initializers, const std::vector<Caffe2Ops> &extras) { auto device_option = GetDeviceOption(Device(device)); ModelProto init_model = OptimizeOnnx(onnx_model, true); InplaceRewrite(init_model.mutable_graph()); ModelProto pred_model = OptimizeOnnx(onnx_model, false); InplaceRewrite(pred_model.mutable_graph()); init_net->set_name(onnx_model.graph().name() + "_init"); pred_net->set_name(onnx_model.graph().name() + "_predict"); // Convert initializer if necessary if (include_initializers) { for (const auto& tp: onnx_model.graph().initializer()) { auto* c2_op = init_net->add_op(); BuildTensorFillingOp(c2_op, tp); } } auto name_set =AllNamesInGraph(init_model.graph()); auto name_set_pred = AllNamesInGraph(pred_model.graph()); name_set.insert(name_set_pred.begin(), name_set_pred.end()); DummyName::Reset(name_set); size_t idx_extra = 0; auto converter = [&](const ModelProto &model, caffe2::NetDef *net) mutable { net->mutable_device_option()->CopyFrom(device_option); for (const auto &node : model.graph().node()) { auto *init_net_tmp = include_initializers ? init_net : net; // For RNN operators, we rely on Python code to convert them for us, and // we simply deserilize the string. This is hack and eventually we want to // get rid of this to have one flow. Note that we need to update the dummy // name generator to avoid having duplicated names between Python and C++ // generated dummies if (get_rnn_operators().count(node.op_type())) { if (idx_extra < extras.size()) { const auto &c2ops = extras[idx_extra++]; for (const auto& op: c2ops.init_ops) { UpdateNames(op); } init_net_tmp->mutable_op()->MergeFrom(c2ops.init_ops); for (const auto& op: c2ops.ops) { UpdateNames(op); } net->mutable_op()->MergeFrom(c2ops.ops); for (const auto& input: c2ops.interface_blobs) { DummyName::AddName(input); } net->mutable_external_input()->MergeFrom(c2ops.interface_blobs); } else { throw std::runtime_error( caffe2::MakeString("Don't know how to convert ", node.op_type(), " without enough extra preconverted string")); } } else { auto onnx_node = OnnxNode(node); auto c2ops = OnnxNodeToCaffe2Ops(init_model, pred_model, &onnx_node, opset_version); init_net_tmp->mutable_op()->MergeFrom(c2ops.init_ops); net->mutable_op()->MergeFrom(c2ops.ops); net->mutable_external_input()->MergeFrom(c2ops.interface_blobs); } } for (const auto& value: model.graph().output()) { net->add_external_output(value.name()); } for (const auto& value: model.graph().input()) { net->add_external_input(value.name()); } }; converter(init_model, init_net); converter(pred_model, pred_net); } Caffe2BackendRep* Caffe2Backend::Prepare(const std::string &onnx_model_str, const std::string &device, const std::vector<Caffe2Ops> &extras) { Caffe2BackendRep* rep = new Caffe2BackendRep(); ModelProto onnx_model; ParseProtobufFromLargeString(onnx_model_str, &onnx_model); ONNX_NAMESPACE::checker::check_model(onnx_model); int opset_version = -1; for (const auto& imp: onnx_model.opset_import()) { if ((!imp.has_domain()) || imp.domain().empty()) { opset_version = imp.version(); if (opset_version > kKnownOpsetVersion) { std::cout << "This version of onnx-caffe2 targets ONNX operator set version " << kKnownOpsetVersion << ", but the model we are trying to import uses version " << opset_version << ". We will try to import it anyway, " << "but if the model uses operators which had BC-breaking changes " "in the intervening versions, import will fail." << std::endl; } } else { std::cout << "Unrecognized operator set " << opset_version << std::endl; } } if (opset_version< 0) { if (onnx_model.ir_version() >= 0x00000003) { throw std::runtime_error( "Model with IR version >= 3 did not specify ONNX operator set " "version (onnx-caffe2 requires it)"); } else { opset_version = 1; } } //TODO: avoid extra copy by directly feed initialiers to backend blobs OnnxToCaffe2(&rep->init_net(), &rep->pred_net(), onnx_model, device, opset_version, true, extras); // Get a list of uninitialized inputs to help with the inference setup auto& uninitialized_inputs = rep->uninitialized_inputs(); std::unordered_set<std::string> initialized_inputs; for (const auto& tp: onnx_model.graph().initializer()) { initialized_inputs.emplace(tp.name()); } for (const auto& input: onnx_model.graph().input()) { if (!initialized_inputs.count(input.name())) { uninitialized_inputs.emplace_back(input.name()); } } return rep; } void Caffe2Backend::BuildTensorFillingOp(caffe2::OperatorDef *c2_op, const TensorProto &onnx_tensor, const std::string &name) { auto fill_name = name.empty() ? onnx_tensor.name() : name; CAFFE_ENFORCE(!fill_name.empty()); if (onnx_tensor.has_segment()) { throw std::runtime_error("Currently not supporting loading segments."); } auto* c2_values = c2_op->add_arg(); c2_values->set_name("values"); if (onnx_tensor.data_type() == TensorProto::FLOAT) { c2_op->set_type("GivenTensorFill"); auto* floats = c2_values->mutable_floats(); if (!TryConvertingTensorRawValues<float>(onnx_tensor, floats)) { floats->CopyFrom(onnx_tensor.float_data()); } } else if (onnx_tensor.data_type() == TensorProto::DOUBLE) { c2_op->set_type("GivenTensorDoubleFill"); ::google::protobuf::RepeatedField<double> tmp; const ::google::protobuf::RepeatedField<double>* src = &tmp; if (!TryConvertingTensorRawValues<double>(onnx_tensor, &tmp)) { src = &onnx_tensor.double_data(); } else { for (const auto i: *src) { c2_values->add_floats(i); } } } else if (onnx_tensor.data_type() == TensorProto::INT64) { c2_op->set_type("GivenTensorInt64Fill"); auto *ints = c2_values->mutable_ints(); if (!TryConvertingTensorRawValues<::google::protobuf::int64>(onnx_tensor, ints)) { ints->CopyFrom(onnx_tensor.int64_data()); } } else if (onnx_tensor.data_type() == TensorProto::UINT32) { c2_op->set_type("GivenTensorInt64Fill"); ::google::protobuf::RepeatedField<::google::protobuf::uint64> tmp; const ::google::protobuf::RepeatedField<::google::protobuf::uint64>* src = &tmp; if (!TryConvertingTensorRawValues<::google::protobuf::uint64>(onnx_tensor, &tmp)) { src = &onnx_tensor.uint64_data(); } else { for (const auto i: *src) { c2_values->add_ints(i); } } } else if (onnx_tensor.data_type() == TensorProto::BOOL || onnx_tensor.data_type() == TensorProto::UINT8 || onnx_tensor.data_type() == TensorProto::INT8 || onnx_tensor.data_type() == TensorProto::UINT16 || onnx_tensor.data_type() == TensorProto::INT16 || onnx_tensor.data_type() == TensorProto::INT32) { c2_op->set_type(onnx_tensor.data_type() == TensorProto::BOOL ? "GivenTensorBoolFill" : "GivenTensorIntFill"); ::google::protobuf::RepeatedField<::google::protobuf::int32> tmp; const ::google::protobuf::RepeatedField<::google::protobuf::int32>* src = &tmp; if (!TryConvertingTensorRawValues<::google::protobuf::int32>(onnx_tensor, &tmp)) { src = &onnx_tensor.int32_data(); } else { for (const auto i: *src) { c2_values->add_ints(i); } } } else if (onnx_tensor.data_type() == TensorProto::STRING) { c2_op->set_type("GivenTensorStringFill"); auto * strings = c2_values->mutable_strings(); strings->CopyFrom(onnx_tensor.string_data()); } else { throw std::runtime_error( "unrecognized tensor type: " + TensorProto::DataType_Name(onnx_tensor.data_type())); } auto* c2_shape = c2_op->add_arg(); c2_shape->set_name("shape"); for(const auto d: onnx_tensor.dims()) { c2_shape->add_ints(d); } c2_op->add_output(fill_name); } }}
35.237398
95
0.640626
[ "shape", "vector", "model" ]
8b21bfc82b7b0683d060c9a0383220dcff678572
1,414
cpp
C++
106-construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp
nagestx/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
3
2018-12-15T14:07:12.000Z
2020-07-19T23:18:09.000Z
106-construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp
yangyangu/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
null
null
null
106-construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.cpp
yangyangu/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
null
null
null
// Given inorder and postorder traversal of a tree, construct the binary tree. // // Note: // You may assume that duplicates do not exist in the tree. // // For example, given // // // inorder = [9,3,15,20,7] // postorder = [9,15,7,20,3] // // Return the following binary tree: // // // 3 // / \ // 9 20 // / \ // 15 7 // // /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* buildTreeWithIP(vector<int>& inorder, vector<int>& postorder, int istart, int iend, int postart, int poend){ if(istart > iend || postart > poend) return nullptr; auto root = new TreeNode(postorder[poend]); int index = 0; for(index = istart; index <= iend; ++ index){ if(inorder[index] == postorder[poend]) break; } root->left = buildTreeWithIP(inorder, postorder, istart, index - 1, postart, postart + index - istart - 1); root->right = buildTreeWithIP(inorder, postorder, index + 1, iend, postart + index - istart, poend - 1); return root; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return buildTreeWithIP(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); } };
27.72549
122
0.582744
[ "vector" ]
8b24bcb6e582d2b53104bbb4e56368cf903dc5cb
350
cpp
C++
leetcode/66. Plus One/s1.cpp
contacttoakhil/LeetCode-1
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
[ "Fair" ]
1
2021-02-09T11:38:51.000Z
2021-02-09T11:38:51.000Z
leetcode/66. Plus One/s1.cpp
contacttoakhil/LeetCode-1
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
[ "Fair" ]
null
null
null
leetcode/66. Plus One/s1.cpp
contacttoakhil/LeetCode-1
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
[ "Fair" ]
null
null
null
class Solution { public: vector<int> plusOne(vector<int>& digits) { int carry = 1; for (int i = digits.size() - 1; i >= 0 && carry; --i) { carry += digits[i]; digits[i] = carry % 10; carry /= 10; } if (carry) digits.insert(digits.begin(), carry); return digits; } };
26.923077
63
0.471429
[ "vector" ]
8b2a2b076ff73d49f37be7355a2176943e9d5cb5
1,761
cc
C++
DataFormats/EcalDetId/src/EcalTriggerElectronicsId.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
DataFormats/EcalDetId/src/EcalTriggerElectronicsId.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
DataFormats/EcalDetId/src/EcalTriggerElectronicsId.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-04-03T19:23:27.000Z
2019-04-03T19:23:27.000Z
#include "DataFormats/EcalDetId/interface/EcalTriggerElectronicsId.h" #include "FWCore/Utilities/interface/Exception.h" #include <ostream> EcalTriggerElectronicsId::EcalTriggerElectronicsId() { EcalTriggerElectronicsId_=0xFFFFFFFFu; } EcalTriggerElectronicsId::EcalTriggerElectronicsId(uint32_t id) { EcalTriggerElectronicsId_=id; } EcalTriggerElectronicsId::EcalTriggerElectronicsId(int tccid, int ttid, int pseudostripid, int channelid){ if ( (tccid < MIN_TCCID) || (tccid > MAX_TCCID) || (ttid < MIN_TTID) || (ttid > MAX_TTID) || (pseudostripid < MIN_PSEUDOSTRIPID) || (pseudostripid > MAX_PSEUDOSTRIPID) || (channelid < MIN_CHANNELID) || (channelid > MAX_CHANNELID) ) throw cms::Exception("InvalidDetId") << "EcalTriggerElectronicsId: Cannot create object. Indexes out of bounds."; EcalTriggerElectronicsId_= (channelid&0x7) | ( (pseudostripid&0x7) << 3) | ( (ttid&0x7F) << 6) | ((tccid&0x7F) << 13); } int EcalTriggerElectronicsId::zside() const { int tcc = tccId(); if ( (tcc >= MIN_TCCID_EEM && tcc <= MAX_TCCID_EEM)) return -1; if ( (tcc >= MIN_TCCID_EBM && tcc <= MAX_TCCID_EBM)) return -1; if ( (tcc >= MIN_TCCID_EEP && tcc <= MAX_TCCID_EEP)) return +1; if ( (tcc >= MIN_TCCID_EBP && tcc <= MAX_TCCID_EBP)) return +1; return 0; } EcalSubdetector EcalTriggerElectronicsId::subdet() const { int tcc = tccId(); if ( (tcc >= MIN_TCCID_EBM && tcc <= MAX_TCCID_EBM) || (tcc >= MIN_TCCID_EBP && tcc <= MAX_TCCID_EBP) ) return EcalBarrel; else return EcalEndcap; } std::ostream& operator<<(std::ostream& os,const EcalTriggerElectronicsId& id) { return os << id.tccId() << ',' << id.ttId() << ',' << id.pseudoStripId() << ',' << id.channelId() ; }
38.282609
120
0.674049
[ "object" ]
8b2be6c887ac4ac85604ba849cbf8adaeb88398b
12,941
cc
C++
annotate_rsids_from_linker/main.cc
NCI-CGR/annotate_rsids_from_linker
ab919232895b8d5034ab99e6ec28effb8efb0a9e
[ "MIT" ]
null
null
null
annotate_rsids_from_linker/main.cc
NCI-CGR/annotate_rsids_from_linker
ab919232895b8d5034ab99e6ec28effb8efb0a9e
[ "MIT" ]
3
2021-06-10T19:00:02.000Z
2022-01-16T17:46:39.000Z
annotate_rsids_from_linker/main.cc
NCI-CGR/annotate_rsids_from_linker
ab919232895b8d5034ab99e6ec28effb8efb0a9e
[ "MIT" ]
null
null
null
/*! \file annotate_rsids_from_linker.cc \brief approximately convert chr:pos ids to rsids \copyright Released under the MIT License. Copyright 2020 Cameron Palmer. */ #include <fstream> #include <iostream> #include <map> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include <vector> #include "finter/finter.h" template <class value_type> value_type from_string(const std::string &str) { std::istringstream strm1(str); value_type res; if (!(strm1 >> res)) throw std::domain_error("cannot convert string to object: \"" + str + "\""); return res; } void splitline(const std::string &line, std::vector<std::string> *vec, const std::string &sep) { if (!vec) throw std::domain_error("splitline: called with null pointer"); vec->clear(); std::string::size_type loc = 0, cur = 0; while (true) { loc = line.find(sep, cur); if (loc == std::string::npos) { vec->push_back(line.substr(cur)); break; } vec->push_back(line.substr(cur, loc - cur)); cur = loc + sep.size(); } } class rescue_annotation { public: rescue_annotation() : _input_index(0), _ref(""), _alt(""), _updated_id("") {} rescue_annotation(const rescue_annotation &obj) : _input_index(obj._input_index), _ref(obj._ref), _alt(obj._alt), _updated_id(obj._updated_id) {} ~rescue_annotation() throw() {} void set_index(unsigned u) { _input_index = u; } unsigned get_index() const { return _input_index; } void set_ref(const std::string &s) { _ref = s; } const std::string &get_ref() const { return _ref; } void set_alt(const std::string &s) { _alt = s; } const std::string &get_alt() const { return _alt; } void set_updated_id(const std::string &s) { _updated_id = s; } const std::string &get_updated_id() const { return _updated_id; } bool alleles_consistent(const std::string &ref, const std::string &alt) const; private: unsigned _input_index; std::string _ref; std::string _alt; std::string _updated_id; }; bool rescue_annotation::alleles_consistent(const std::string &ref, const std::string &alt) const { std::vector<std::string> split_alt; splitline(alt, &split_alt, ","); bool test_against_alt = !ref.compare(get_ref()); bool test_against_ref = !ref.compare(get_alt()); if (test_against_ref || test_against_alt) { for (std::vector<std::string>::const_iterator iter = split_alt.begin(); iter != split_alt.end(); ++iter) { if (!iter->compare( test_against_ref ? get_ref() : (test_against_alt ? get_alt() : std::string("")))) { return true; } } } return false; } void stream_update(const std::string &analysis_filename, const std::string &linker_filename, const std::string &output_filename, std::vector<std::string> *updated_ids, std::map<std::string, rescue_annotation> *rescue_chrpos) { finter::finter_reader *input_analysis = 0, *input_linker = 0; finter::finter_writer *output = 0; std::string linker_chr = "", analysis_chr = "", analysis_line = "", linker_line = "", chrpos_id = "", rsid = "", analysis_chrpos = "", catcher = "", refalt = ""; std::string::size_type loc = 0; unsigned total_updated = 0, valid_updated = 0, not_present_in_linker = 0, linker_pos = 0, analysis_pos = 0; try { input_analysis = finter::reconcile_reader(analysis_filename); input_linker = finter::reconcile_reader(linker_filename); input_analysis->getline(&analysis_line); if (!updated_ids) { output = finter::reconcile_writer(output_filename); output->writeline(analysis_line); } else { updated_ids->reserve(40000000); } while (input_analysis->getline(&analysis_line)) { std::istringstream strm1(analysis_line); if (!(strm1 >> analysis_chr >> analysis_pos >> analysis_chrpos)) throw std::domain_error("unable to parse analysis file \"" + analysis_filename + "\" line \"" + analysis_line + "\""); refalt = analysis_chrpos.substr( analysis_chrpos.find(":", analysis_chrpos.find(":") + 1) + 1); while (true) { if (linker_line.empty()) { if (!input_linker->getline(&linker_line)) break; } std::istringstream strm2(linker_line); if (!(strm2 >> chrpos_id >> rsid)) throw std::domain_error("unable to parse linker file \"" + linker_filename + "\" line \"" + linker_line + "\""); loc = chrpos_id.find(":") + 1; linker_chr = from_string<std::string>(chrpos_id.substr(3, loc - 4)); linker_pos = from_string<unsigned>( chrpos_id.substr(loc, chrpos_id.find(":", loc) - loc)); if (!chrpos_id.compare(analysis_chrpos)) { ++total_updated; // note: these two rsIDs are annotation failures in dbSNP // due to weird cross-chromosome homology in pseudogenes. // as these are the only variants I've found so far affected by // this issue, I'm just putting in a hard-coded fix. if I find // more, I'll improve the generalisability of the fix if (rsid.compare(".") && rsid.compare("rs1192281978") && rsid.compare("rs1160972848")) { ++valid_updated; rsid += ":" + refalt; } else { rsid = analysis_chrpos; } if (output) { std::ostringstream o; o << analysis_chr << '\t' << analysis_pos << '\t' << rsid; while (strm1 >> catcher) { o << '\t' << catcher; } output->writeline(o.str()); } else { // store information updated_ids->push_back(rsid); if (!rsid.compare(analysis_chrpos)) { rescue_annotation ra; ra.set_index(updated_ids->size() - 1); rescue_chrpos->insert(std::make_pair(analysis_chrpos, ra)); } } linker_line = ""; break; } else if ((linker_chr == analysis_chr && linker_pos > analysis_pos) || linker_chr > analysis_chr) { // something terrible has happened with the linker, flush the // analysis result without an ID ++not_present_in_linker; if (output) { std::ostringstream o; o << analysis_chr << '\t' << analysis_pos << "\t" << analysis_chrpos; while (strm1 >> catcher) o << '\t' << catcher; output->writeline(o.str()); } else { // store information updated_ids->push_back(analysis_chrpos); rescue_annotation ra; ra.set_index(updated_ids->size() - 1); rescue_chrpos->insert(std::make_pair(analysis_chrpos, ra)); } break; } else { linker_line = ""; } } } input_analysis->close(); delete input_analysis; input_linker->close(); delete input_linker; if (output) { output->close(); delete output; std::cout << output_filename << ": updated " << total_updated << ", of which " << valid_updated << " had nonmissing rsids; " << not_present_in_linker << " were either absent from the linker or unsorted and have " "been set to \".\"" << std::endl; } else { std::cout << "from first pass, updated " << valid_updated << ", didn't manage to update " << (total_updated - valid_updated + not_present_in_linker) << std::endl; } } catch (...) { if (input_analysis) delete input_analysis; if (input_linker) delete input_linker; if (output) delete output; throw; } } void dbsnp_rescue(const std::string &filename, std::map<std::string, rescue_annotation> *target) { if (!target) throw std::domain_error("dbsnp_rescue: called with null pointer"); finter::finter_reader *input = 0; std::string line = ""; unsigned n_updated = 0; std::map<std::string, rescue_annotation>::iterator finder; std::vector<std::string> vec; try { input = finter::reconcile_reader(filename); while (input->getline(&line) && n_updated != target->size()) { if (line.empty() || line.at(0) == '#') continue; splitline(line, &vec, "\t"); if (vec.size() < 5) throw std::domain_error("inadequate entries on dbsnp line \"" + line + "\""); if (vec.at(4).empty()) vec.at(4) = "."; if ((finder = target->find(vec.at(0) + ":" + vec.at(1))) != target->end()) { if (finder->second.alleles_consistent(vec.at(3), vec.at(4))) { finder->second.set_updated_id(vec.at(2)); ++n_updated; } } } input->close(); delete input; input = 0; std::cout << "of " << target->size() << " possible updates, updated " << n_updated << " (" << (static_cast<double>(n_updated) / target->size()) << ")" << std::endl; } catch (...) { if (input) delete input; throw; } } void update_from_memory( const std::string &input_filename, std::vector<std::string> *updated_ids, const std::map<std::string, rescue_annotation> &rescued_ids, const std::string &output_filename) { if (!updated_ids) throw std::domain_error("update_from_memory: called with null pointer"); finter::finter_reader *input = 0; finter::finter_writer *output = 0; std::string line = "", catcher = "", refalt = ""; try { input = finter::reconcile_reader(input_filename); output = finter::reconcile_writer(output_filename); for (std::map<std::string, rescue_annotation>::const_iterator iter = rescued_ids.begin(); iter != rescued_ids.end(); ++iter) { if (!iter->second.get_updated_id().empty()) { updated_ids->at(iter->second.get_index()) = iter->second.get_updated_id(); } } input->getline(&line); output->writeline(line); unsigned counter = 0; while (input->getline(&line)) { std::istringstream strm1(line); std::ostringstream o; for (unsigned i = 0; i < 2; ++i) { strm1 >> catcher; if (i) o << '\t'; o << catcher; } strm1 >> catcher; refalt = catcher.substr(catcher.find(":", catcher.find(":") + 1) + 1); o << '\t' << updated_ids->at(counter) << ":" << refalt; while (strm1 >> catcher) o << '\t' << catcher; output->writeline(o.str()); ++counter; } input->close(); delete input; input = 0; output->close(); delete output; output = 0; } catch (...) { if (input) delete input; if (output) delete output; throw; } } int main(int argc, char **argv) { if (argc < 4) throw std::domain_error("usage: \"" + std::string(argv[0]) + " input_analysis_filename linker_filename " "[dbsnp_vcf_filename] output_filename\""); std::string analysis_filename = std::string(argv[1]); std::string linker_filename = std::string(argv[2]); std::string dbsnp_filename = ""; if (argc > 4) dbsnp_filename = std::string(argv[3]); std::string output_filename = std::string(argv[argc == 4 ? 3 : 4]); std::vector<std::string> updated_ids; std::map<std::string, rescue_annotation> rescue_chrpos; std::cout << "starting run for output " << output_filename << std::endl; if (dbsnp_filename.empty()) { std::cout << "running one-shot against prepared linker file " << linker_filename << std::endl; } else { std::cout << "running multipass run against dbSNP " << dbsnp_filename << " with a preprocessing step against the linker " << linker_filename << std::endl; } std::cout << "running stream_update against linker" << std::endl; stream_update(analysis_filename, linker_filename, dbsnp_filename.empty() ? output_filename : std::string(""), dbsnp_filename.empty() ? NULL : &updated_ids, dbsnp_filename.empty() ? NULL : &rescue_chrpos); if (!rescue_chrpos.empty()) { std::cout << "running rescue pass against dbSNP for " << rescue_chrpos.size() << " variants" << std::endl; dbsnp_rescue(dbsnp_filename, &rescue_chrpos); } if (!updated_ids.empty()) { std::cout << "emitting consensus results from both passes to " << output_filename << std::endl; update_from_memory(analysis_filename, &updated_ids, rescue_chrpos, output_filename); } return 0; }
37.186782
80
0.578472
[ "object", "vector" ]
8b2f100e07c7c775ff15a153279f8ac3b3ff2868
65,771
cpp
C++
physx/source/lowleveldynamics/src/DyContactPrep4.cpp
seimei0083/PhysX
38c2d8f6cf104437cc6cb4a53f774ce5bbeb5acd
[ "Unlicense" ]
null
null
null
physx/source/lowleveldynamics/src/DyContactPrep4.cpp
seimei0083/PhysX
38c2d8f6cf104437cc6cb4a53f774ce5bbeb5acd
[ "Unlicense" ]
null
null
null
physx/source/lowleveldynamics/src/DyContactPrep4.cpp
seimei0083/PhysX
38c2d8f6cf104437cc6cb4a53f774ce5bbeb5acd
[ "Unlicense" ]
null
null
null
// // 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 NVIDIA CORPORATION 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 ``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. // // Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "foundation/PxPreprocessor.h" #include "PxSceneDesc.h" #include "PsVecMath.h" #include "PsMathUtils.h" #include "DySolverContact.h" #include "DySolverContact4.h" #include "DySolverConstraintTypes.h" #include "PxcNpWorkUnit.h" #include "DyThreadContext.h" #include "DyContactPrep.h" #include "PxcNpContactPrepShared.h" #include "PxvDynamics.h" #include "DyCorrelationBuffer.h" #include "DyDynamics.h" #include "DyArticulationContactPrep.h" #include "PxsContactManager.h" #include "PsFoundation.h" using namespace physx; using namespace Gu; #include "PsVecMath.h" #include "PxContactModifyCallback.h" #include "PxsMaterialManager.h" #include "PxsMaterialCombiner.h" #include "DyContactPrepShared.h" using namespace Ps::aos; namespace physx { namespace Dy { PxcCreateFinalizeSolverContactMethod4 createFinalizeMethods4[3] = { createFinalizeSolverContacts4, createFinalizeSolverContacts4Coulomb1D, createFinalizeSolverContacts4Coulomb2D }; inline bool ValidateVec4(const Vec4V v) { PX_ALIGN(16, PxVec4 vF); Ps::aos::V4StoreA(v, &vF.x); return vF.isFinite(); } static void setupFinalizeSolverConstraints4(PxSolverContactDesc* PX_RESTRICT descs, CorrelationBuffer& c, PxU8* PX_RESTRICT workspace, const PxReal invDtF32, PxReal bounceThresholdF32, const PxReal solverOffsetSlopF32, const Ps::aos::Vec4VArg invMassScale0, const Ps::aos::Vec4VArg invInertiaScale0, const Ps::aos::Vec4VArg invMassScale1, const Ps::aos::Vec4VArg invInertiaScale1) { //OK, we have a workspace of pre-allocated space to store all 4 descs in. We now need to create the constraints in it const Vec4V ccdMaxSeparation = Ps::aos::V4LoadXYZW(descs[0].maxCCDSeparation, descs[1].maxCCDSeparation, descs[2].maxCCDSeparation, descs[3].maxCCDSeparation); const Vec4V solverOffsetSlop = V4Load(solverOffsetSlopF32); const Vec4V zero = V4Zero(); const BoolV bFalse = BFFFF(); const FloatV fZero = FZero(); PxU8 flags[4] = { PxU8(descs[0].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0), PxU8(descs[1].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0), PxU8(descs[2].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0), PxU8(descs[3].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0) }; bool hasMaxImpulse = descs[0].hasMaxImpulse || descs[1].hasMaxImpulse || descs[2].hasMaxImpulse || descs[3].hasMaxImpulse; //The block is dynamic if **any** of the constraints have a non-static body B. This allows us to batch static and non-static constraints but we only get a memory/perf //saving if all 4 are static. This simplifies the constraint partitioning such that it only needs to care about separating contacts and 1D constraints (which it already does) bool isDynamic = false; bool hasKinematic = false; for(PxU32 a = 0; a < 4; ++a) { isDynamic = isDynamic || (descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY); hasKinematic = hasKinematic || descs[a].bodyState1 == PxSolverContactDesc::eKINEMATIC_BODY; } const PxU32 constraintSize = isDynamic ? sizeof(SolverContactBatchPointDynamic4) : sizeof(SolverContactBatchPointBase4); const PxU32 frictionSize = isDynamic ? sizeof(SolverContactFrictionDynamic4) : sizeof(SolverContactFrictionBase4); PxU8* PX_RESTRICT ptr = workspace; const Vec4V dom0 = invMassScale0; const Vec4V dom1 = invMassScale1; const Vec4V angDom0 = invInertiaScale0; const Vec4V angDom1 = invInertiaScale1; const Vec4V maxPenBias = V4Max(V4LoadXYZW(descs[0].data0->penBiasClamp, descs[1].data0->penBiasClamp, descs[2].data0->penBiasClamp, descs[3].data0->penBiasClamp), V4LoadXYZW(descs[0].data1->penBiasClamp, descs[1].data1->penBiasClamp, descs[2].data1->penBiasClamp, descs[3].data1->penBiasClamp)); const Vec4V restDistance = V4LoadXYZW(descs[0].restDistance, descs[1].restDistance, descs[2].restDistance, descs[3].restDistance); //load up velocities Vec4V linVel00 = V4LoadA(&descs[0].data0->linearVelocity.x); Vec4V linVel10 = V4LoadA(&descs[1].data0->linearVelocity.x); Vec4V linVel20 = V4LoadA(&descs[2].data0->linearVelocity.x); Vec4V linVel30 = V4LoadA(&descs[3].data0->linearVelocity.x); Vec4V linVel01 = V4LoadA(&descs[0].data1->linearVelocity.x); Vec4V linVel11 = V4LoadA(&descs[1].data1->linearVelocity.x); Vec4V linVel21 = V4LoadA(&descs[2].data1->linearVelocity.x); Vec4V linVel31 = V4LoadA(&descs[3].data1->linearVelocity.x); Vec4V angVel00 = V4LoadA(&descs[0].data0->angularVelocity.x); Vec4V angVel10 = V4LoadA(&descs[1].data0->angularVelocity.x); Vec4V angVel20 = V4LoadA(&descs[2].data0->angularVelocity.x); Vec4V angVel30 = V4LoadA(&descs[3].data0->angularVelocity.x); Vec4V angVel01 = V4LoadA(&descs[0].data1->angularVelocity.x); Vec4V angVel11 = V4LoadA(&descs[1].data1->angularVelocity.x); Vec4V angVel21 = V4LoadA(&descs[2].data1->angularVelocity.x); Vec4V angVel31 = V4LoadA(&descs[3].data1->angularVelocity.x); Vec4V linVelT00, linVelT10, linVelT20; Vec4V linVelT01, linVelT11, linVelT21; Vec4V angVelT00, angVelT10, angVelT20; Vec4V angVelT01, angVelT11, angVelT21; PX_TRANSPOSE_44_34(linVel00, linVel10, linVel20, linVel30, linVelT00, linVelT10, linVelT20); PX_TRANSPOSE_44_34(linVel01, linVel11, linVel21, linVel31, linVelT01, linVelT11, linVelT21); PX_TRANSPOSE_44_34(angVel00, angVel10, angVel20, angVel30, angVelT00, angVelT10, angVelT20); PX_TRANSPOSE_44_34(angVel01, angVel11, angVel21, angVel31, angVelT01, angVelT11, angVelT21); const Vec4V vrelX = V4Sub(linVelT00, linVelT01); const Vec4V vrelY = V4Sub(linVelT10, linVelT11); const Vec4V vrelZ = V4Sub(linVelT20, linVelT21); //Load up masses and invInertia /*const Vec4V sqrtInvMass0 = V4Merge(FLoad(descs[0].data0->sqrtInvMass), FLoad(descs[1].data0->sqrtInvMass), FLoad(descs[2].data0->sqrtInvMass), FLoad(descs[3].data0->sqrtInvMass)); const Vec4V sqrtInvMass1 = V4Merge(FLoad(descs[0].data1->sqrtInvMass), FLoad(descs[1].data1->sqrtInvMass), FLoad(descs[2].data1->sqrtInvMass), FLoad(descs[3].data1->sqrtInvMass));*/ const Vec4V invMass0 = V4LoadXYZW(descs[0].data0->invMass, descs[1].data0->invMass, descs[2].data0->invMass, descs[3].data0->invMass); const Vec4V invMass1 = V4LoadXYZW(descs[0].data1->invMass, descs[1].data1->invMass, descs[2].data1->invMass, descs[3].data1->invMass); const Vec4V invMass0D0 = V4Mul(dom0, invMass0); const Vec4V invMass1D1 = V4Mul(dom1, invMass1); Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column2)); Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column2)); Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column2)); Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column2)); Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column2)); Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column2)); Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column2)); Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia31Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data1->sqrtInvInertia.column2)); Vec4V invInertia0X0, invInertia0X1, invInertia0X2; Vec4V invInertia0Y0, invInertia0Y1, invInertia0Y2; Vec4V invInertia0Z0, invInertia0Z1, invInertia0Z2; Vec4V invInertia1X0, invInertia1X1, invInertia1X2; Vec4V invInertia1Y0, invInertia1Y1, invInertia1Y2; Vec4V invInertia1Z0, invInertia1Z1, invInertia1Z2; PX_TRANSPOSE_44_34(invInertia00X, invInertia10X, invInertia20X, invInertia30X, invInertia0X0, invInertia0Y0, invInertia0Z0); PX_TRANSPOSE_44_34(invInertia00Y, invInertia10Y, invInertia20Y, invInertia30Y, invInertia0X1, invInertia0Y1, invInertia0Z1); PX_TRANSPOSE_44_34(invInertia00Z, invInertia10Z, invInertia20Z, invInertia30Z, invInertia0X2, invInertia0Y2, invInertia0Z2); PX_TRANSPOSE_44_34(invInertia01X, invInertia11X, invInertia21X, invInertia31X, invInertia1X0, invInertia1Y0, invInertia1Z0); PX_TRANSPOSE_44_34(invInertia01Y, invInertia11Y, invInertia21Y, invInertia31Y, invInertia1X1, invInertia1Y1, invInertia1Z1); PX_TRANSPOSE_44_34(invInertia01Z, invInertia11Z, invInertia21Z, invInertia31Z, invInertia1X2, invInertia1Y2, invInertia1Z2); const FloatV invDt = FLoad(invDtF32); const FloatV p8 = FLoad(0.8f); const Vec4V p84 = V4Splat(p8); const Vec4V bounceThreshold = V4Splat(FLoad(bounceThresholdF32)); const FloatV invDtp8 = FMul(invDt, p8); const Vec3V bodyFrame00p = V3LoadU(descs[0].bodyFrame0.p); const Vec3V bodyFrame01p = V3LoadU(descs[1].bodyFrame0.p); const Vec3V bodyFrame02p = V3LoadU(descs[2].bodyFrame0.p); const Vec3V bodyFrame03p = V3LoadU(descs[3].bodyFrame0.p); Vec4V bodyFrame00p4 = Vec4V_From_Vec3V(bodyFrame00p); Vec4V bodyFrame01p4 = Vec4V_From_Vec3V(bodyFrame01p); Vec4V bodyFrame02p4 = Vec4V_From_Vec3V(bodyFrame02p); Vec4V bodyFrame03p4 = Vec4V_From_Vec3V(bodyFrame03p); Vec4V bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ; PX_TRANSPOSE_44_34(bodyFrame00p4, bodyFrame01p4, bodyFrame02p4, bodyFrame03p4, bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ); const Vec3V bodyFrame10p = V3LoadU(descs[0].bodyFrame1.p); const Vec3V bodyFrame11p = V3LoadU(descs[1].bodyFrame1.p); const Vec3V bodyFrame12p = V3LoadU(descs[2].bodyFrame1.p); const Vec3V bodyFrame13p = V3LoadU(descs[3].bodyFrame1.p); Vec4V bodyFrame10p4 = Vec4V_From_Vec3V(bodyFrame10p); Vec4V bodyFrame11p4 = Vec4V_From_Vec3V(bodyFrame11p); Vec4V bodyFrame12p4 = Vec4V_From_Vec3V(bodyFrame12p); Vec4V bodyFrame13p4 = Vec4V_From_Vec3V(bodyFrame13p); Vec4V bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ; PX_TRANSPOSE_44_34(bodyFrame10p4, bodyFrame11p4, bodyFrame12p4, bodyFrame13p4, bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ); const QuatV bodyFrame00q = QuatVLoadU(&descs[0].bodyFrame0.q.x); const QuatV bodyFrame01q = QuatVLoadU(&descs[1].bodyFrame0.q.x); const QuatV bodyFrame02q = QuatVLoadU(&descs[2].bodyFrame0.q.x); const QuatV bodyFrame03q = QuatVLoadU(&descs[3].bodyFrame0.q.x); const QuatV bodyFrame10q = QuatVLoadU(&descs[0].bodyFrame1.q.x); const QuatV bodyFrame11q = QuatVLoadU(&descs[1].bodyFrame1.q.x); const QuatV bodyFrame12q = QuatVLoadU(&descs[2].bodyFrame1.q.x); const QuatV bodyFrame13q = QuatVLoadU(&descs[3].bodyFrame1.q.x); PxU32 frictionPatchWritebackAddrIndex0 = 0; PxU32 frictionPatchWritebackAddrIndex1 = 0; PxU32 frictionPatchWritebackAddrIndex2 = 0; PxU32 frictionPatchWritebackAddrIndex3 = 0; Ps::prefetchLine(c.contactID); Ps::prefetchLine(c.contactID, 128); PxU32 frictionIndex0 = 0, frictionIndex1 = 0, frictionIndex2 = 0, frictionIndex3 = 0; //PxU32 contactIndex0 = 0, contactIndex1 = 0, contactIndex2 = 0, contactIndex3 = 0; //OK, we iterate through all friction patch counts in the constraint patch, building up the constraint list etc. PxU32 maxPatches = PxMax(descs[0].numFrictionPatches, PxMax(descs[1].numFrictionPatches, PxMax(descs[2].numFrictionPatches, descs[3].numFrictionPatches))); const Vec4V p1 = V4Splat(FLoad(0.0001f)); const Vec4V orthoThreshold = V4Splat(FLoad(0.70710678f)); PxU32 contact0 = 0, contact1 = 0, contact2 = 0, contact3 = 0; PxU32 patch0 = 0, patch1 = 0, patch2 = 0, patch3 = 0; PxU8 flag = 0; if(hasMaxImpulse) flag |= SolverContactHeader4::eHAS_MAX_IMPULSE; for(PxU32 i=0;i<maxPatches;i++) { const bool hasFinished0 = i >= descs[0].numFrictionPatches; const bool hasFinished1 = i >= descs[1].numFrictionPatches; const bool hasFinished2 = i >= descs[2].numFrictionPatches; const bool hasFinished3 = i >= descs[3].numFrictionPatches; frictionIndex0 = hasFinished0 ? frictionIndex0 : descs[0].startFrictionPatchIndex + i; frictionIndex1 = hasFinished1 ? frictionIndex1 : descs[1].startFrictionPatchIndex + i; frictionIndex2 = hasFinished2 ? frictionIndex2 : descs[2].startFrictionPatchIndex + i; frictionIndex3 = hasFinished3 ? frictionIndex3 : descs[3].startFrictionPatchIndex + i; PxU32 clampedContacts0 = hasFinished0 ? 0 : c.frictionPatchContactCounts[frictionIndex0]; PxU32 clampedContacts1 = hasFinished1 ? 0 : c.frictionPatchContactCounts[frictionIndex1]; PxU32 clampedContacts2 = hasFinished2 ? 0 : c.frictionPatchContactCounts[frictionIndex2]; PxU32 clampedContacts3 = hasFinished3 ? 0 : c.frictionPatchContactCounts[frictionIndex3]; PxU32 firstPatch0 = c.correlationListHeads[frictionIndex0]; PxU32 firstPatch1 = c.correlationListHeads[frictionIndex1]; PxU32 firstPatch2 = c.correlationListHeads[frictionIndex2]; PxU32 firstPatch3 = c.correlationListHeads[frictionIndex3]; const Gu::ContactPoint* contactBase0 = descs[0].contacts + c.contactPatches[firstPatch0].start; const Gu::ContactPoint* contactBase1 = descs[1].contacts + c.contactPatches[firstPatch1].start; const Gu::ContactPoint* contactBase2 = descs[2].contacts + c.contactPatches[firstPatch2].start; const Gu::ContactPoint* contactBase3 = descs[3].contacts + c.contactPatches[firstPatch3].start; const Vec4V restitution = V4Neg(V4LoadXYZW(contactBase0->restitution, contactBase1->restitution, contactBase2->restitution, contactBase3->restitution)); SolverContactHeader4* PX_RESTRICT header = reinterpret_cast<SolverContactHeader4*>(ptr); ptr += sizeof(SolverContactHeader4); header->flags[0] = flags[0]; header->flags[1] = flags[1]; header->flags[2] = flags[2]; header->flags[3] = flags[3]; header->flag = flag; PxU32 totalContacts = PxMax(clampedContacts0, PxMax(clampedContacts1, PxMax(clampedContacts2, clampedContacts3))); Vec4V* PX_RESTRICT appliedNormalForces = reinterpret_cast<Vec4V*>(ptr); ptr += sizeof(Vec4V)*totalContacts; PxMemZero(appliedNormalForces, sizeof(Vec4V) * totalContacts); header->numNormalConstr = Ps::to8(totalContacts); header->numNormalConstr0 = Ps::to8(clampedContacts0); header->numNormalConstr1 = Ps::to8(clampedContacts1); header->numNormalConstr2 = Ps::to8(clampedContacts2); header->numNormalConstr3 = Ps::to8(clampedContacts3); //header->sqrtInvMassA = sqrtInvMass0; //header->sqrtInvMassB = sqrtInvMass1; header->invMass0D0 = invMass0D0; header->invMass1D1 = invMass1D1; header->angDom0 = angDom0; header->angDom1 = angDom1; header->shapeInteraction[0] = descs[0].shapeInteraction; header->shapeInteraction[1] = descs[1].shapeInteraction; header->shapeInteraction[2] = descs[2].shapeInteraction; header->shapeInteraction[3] = descs[3].shapeInteraction; Vec4V* maxImpulse = reinterpret_cast<Vec4V*>(ptr + constraintSize * totalContacts); header->restitution = restitution; Vec4V normal0 = V4LoadA(&contactBase0->normal.x); Vec4V normal1 = V4LoadA(&contactBase1->normal.x); Vec4V normal2 = V4LoadA(&contactBase2->normal.x); Vec4V normal3 = V4LoadA(&contactBase3->normal.x); Vec4V normalX, normalY, normalZ; PX_TRANSPOSE_44_34(normal0, normal1, normal2, normal3, normalX, normalY, normalZ); PX_ASSERT(ValidateVec4(normalX)); PX_ASSERT(ValidateVec4(normalY)); PX_ASSERT(ValidateVec4(normalZ)); header->normalX = normalX; header->normalY = normalY; header->normalZ = normalZ; const Vec4V norVel0 = V4MulAdd(normalZ, linVelT20, V4MulAdd(normalY, linVelT10, V4Mul(normalX, linVelT00))); const Vec4V norVel1 = V4MulAdd(normalZ, linVelT21, V4MulAdd(normalY, linVelT11, V4Mul(normalX, linVelT01))); const Vec4V relNorVel = V4Sub(norVel0, norVel1); //For all correlation heads - need to pull this out I think //OK, we have a counter for all our patches... PxU32 finished = (PxU32(hasFinished0)) | ((PxU32(hasFinished1)) << 1) | ((PxU32(hasFinished2)) << 2) | ((PxU32(hasFinished3)) << 3); CorrelationListIterator iter0(c, firstPatch0); CorrelationListIterator iter1(c, firstPatch1); CorrelationListIterator iter2(c, firstPatch2); CorrelationListIterator iter3(c, firstPatch3); //PxU32 contact0, contact1, contact2, contact3; //PxU32 patch0, patch1, patch2, patch3; if(!hasFinished0) iter0.nextContact(patch0, contact0); if(!hasFinished1) iter1.nextContact(patch1, contact1); if(!hasFinished2) iter2.nextContact(patch2, contact2); if(!hasFinished3) iter3.nextContact(patch3, contact3); PxU8* p = ptr; PxU32 contactCount = 0; PxU32 newFinished = (PxU32(hasFinished0 || !iter0.hasNextContact())) | ((PxU32(hasFinished1 || !iter1.hasNextContact())) << 1) | ((PxU32(hasFinished2 || !iter2.hasNextContact())) << 2) | ((PxU32(hasFinished3 || !iter3.hasNextContact())) << 3); while(finished != 0xf) { finished = newFinished; ++contactCount; Ps::prefetchLine(p, 384); Ps::prefetchLine(p, 512); Ps::prefetchLine(p, 640); SolverContactBatchPointBase4* PX_RESTRICT solverContact = reinterpret_cast<SolverContactBatchPointBase4*>(p); p += constraintSize; const Gu::ContactPoint& con0 = descs[0].contacts[c.contactPatches[patch0].start + contact0]; const Gu::ContactPoint& con1 = descs[1].contacts[c.contactPatches[patch1].start + contact1]; const Gu::ContactPoint& con2 = descs[2].contacts[c.contactPatches[patch2].start + contact2]; const Gu::ContactPoint& con3 = descs[3].contacts[c.contactPatches[patch3].start + contact3]; //Now we need to splice these 4 contacts into a single structure { Vec4V point0 = V4LoadA(&con0.point.x); Vec4V point1 = V4LoadA(&con1.point.x); Vec4V point2 = V4LoadA(&con2.point.x); Vec4V point3 = V4LoadA(&con3.point.x); Vec4V pointX, pointY, pointZ; PX_TRANSPOSE_44_34(point0, point1, point2, point3, pointX, pointY, pointZ); PX_ASSERT(ValidateVec4(pointX)); PX_ASSERT(ValidateVec4(pointY)); PX_ASSERT(ValidateVec4(pointZ)); Vec4V cTargetVel0 = V4LoadA(&con0.targetVel.x); Vec4V cTargetVel1 = V4LoadA(&con1.targetVel.x); Vec4V cTargetVel2 = V4LoadA(&con2.targetVel.x); Vec4V cTargetVel3 = V4LoadA(&con3.targetVel.x); Vec4V cTargetVelX, cTargetVelY, cTargetVelZ; PX_TRANSPOSE_44_34(cTargetVel0, cTargetVel1, cTargetVel2, cTargetVel3, cTargetVelX, cTargetVelY, cTargetVelZ); const Vec4V separation = V4LoadXYZW(con0.separation, con1.separation, con2.separation, con3.separation); const Vec4V cTargetNorVel = V4MulAdd(cTargetVelX, normalX, V4MulAdd(cTargetVelY, normalY, V4Mul(cTargetVelZ, normalZ))); const Vec4V raX = V4Sub(pointX, bodyFrame0pX); const Vec4V raY = V4Sub(pointY, bodyFrame0pY); const Vec4V raZ = V4Sub(pointZ, bodyFrame0pZ); const Vec4V rbX = V4Sub(pointX, bodyFrame1pX); const Vec4V rbY = V4Sub(pointY, bodyFrame1pY); const Vec4V rbZ = V4Sub(pointZ, bodyFrame1pZ); /*raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX); raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY); raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ); rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX); rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY); rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);*/ PX_ASSERT(ValidateVec4(raX)); PX_ASSERT(ValidateVec4(raY)); PX_ASSERT(ValidateVec4(raZ)); PX_ASSERT(ValidateVec4(rbX)); PX_ASSERT(ValidateVec4(rbY)); PX_ASSERT(ValidateVec4(rbZ)); //raXn = cross(ra, normal) which = Vec3V( a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x); Vec4V raXnX = V4NegMulSub(raZ, normalY, V4Mul(raY, normalZ)); Vec4V raXnY = V4NegMulSub(raX, normalZ, V4Mul(raZ, normalX)); Vec4V raXnZ = V4NegMulSub(raY, normalX, V4Mul(raX, normalY)); raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX); raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY); raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ); Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX); Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX); Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX); delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X); delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y); delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z); delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X); delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y); delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z); PX_ASSERT(ValidateVec4(delAngVel0X)); PX_ASSERT(ValidateVec4(delAngVel0Y)); PX_ASSERT(ValidateVec4(delAngVel0Z)); const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0X, delAngVel0X, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0Z, delAngVel0Z))); const Vec4V dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00))); Vec4V unitResponse = V4MulAdd(invMass0D0, angDom0, dotDelAngVel0); Vec4V vrel = V4Add(relNorVel, dotRaXnAngVel0); //The dynamic-only parts - need to if-statement these up. A branch here shouldn't cost us too much if(isDynamic) { SolverContactBatchPointDynamic4* PX_RESTRICT dynamicContact = static_cast<SolverContactBatchPointDynamic4*>(solverContact); Vec4V rbXnX = V4NegMulSub(rbZ, normalY, V4Mul(rbY, normalZ)); Vec4V rbXnY = V4NegMulSub(rbX, normalZ, V4Mul(rbZ, normalX)); Vec4V rbXnZ = V4NegMulSub(rbY, normalX, V4Mul(rbX, normalY)); rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX); rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY); rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ); Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX); Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX); Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX); delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X); delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y); delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z); delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X); delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y); delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z); PX_ASSERT(ValidateVec4(delAngVel1X)); PX_ASSERT(ValidateVec4(delAngVel1Y)); PX_ASSERT(ValidateVec4(delAngVel1Z)); const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1X, delAngVel1X, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1Z, delAngVel1Z))); const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01))); const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1); unitResponse = V4Add(unitResponse, resp1); vrel = V4Sub(vrel, dotRbXnAngVel1); //These are for dynamic-only contacts. dynamicContact->rbXnX = delAngVel1X; dynamicContact->rbXnY = delAngVel1Y; dynamicContact->rbXnZ = delAngVel1Z; } else if(hasKinematic) { const Vec4V rbXnX = V4NegMulSub(rbZ, normalY, V4Mul(rbY, normalZ)); const Vec4V rbXnY = V4NegMulSub(rbX, normalZ, V4Mul(rbZ, normalX)); const Vec4V rbXnZ = V4NegMulSub(rbY, normalX, V4Mul(rbX, normalY)); const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01))); vrel = V4Sub(vrel, dotRbXnAngVel1); } const Vec4V velMultiplier = V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero); const Vec4V penetration = V4Sub(separation, restDistance); const Vec4V penInvDtPt8 = V4Max(maxPenBias, V4Scale(penetration, invDtp8)); Vec4V scaledBias = V4Mul(penInvDtPt8, velMultiplier); const Vec4V penetrationInvDt = V4Scale(penetration, invDt); const BoolV isGreater2 = BAnd(BAnd(V4IsGrtr(zero, restitution), V4IsGrtr(bounceThreshold, vrel)), V4IsGrtr(V4Neg(vrel), penetrationInvDt)); const BoolV ccdSeparationCondition = V4IsGrtrOrEq(ccdMaxSeparation, penetration); scaledBias = V4Sel(BAnd(ccdSeparationCondition, isGreater2), zero, V4Neg(scaledBias)); const Vec4V targetVelocity = V4Sel(isGreater2, V4Mul(velMultiplier, V4Mul(vrel, restitution)), zero); //Vec4V biasedErr = V4Sel(isGreater2, targetVelocity, scaledBias); Vec4V biasedErr = V4Add(targetVelocity, scaledBias); biasedErr = V4NegMulSub(V4Sub(vrel, cTargetNorVel), velMultiplier, biasedErr); //These values are present for static and dynamic contacts solverContact->raXnX = delAngVel0X; solverContact->raXnY = delAngVel0Y; solverContact->raXnZ = delAngVel0Z; solverContact->velMultiplier = velMultiplier; solverContact->biasedErr = biasedErr; //solverContact->scaledBias = V4Max(zero, scaledBias); solverContact->scaledBias = V4Sel(isGreater2, scaledBias, V4Max(zero, scaledBias)); if(hasMaxImpulse) { maxImpulse[contactCount-1] = V4Merge(FLoad(con0.maxImpulse), FLoad(con1.maxImpulse), FLoad(con2.maxImpulse), FLoad(con3.maxImpulse)); } } if(!(finished & 0x1)) { iter0.nextContact(patch0, contact0); newFinished |= PxU32(!iter0.hasNextContact()); } if(!(finished & 0x2)) { iter1.nextContact(patch1, contact1); newFinished |= (PxU32(!iter1.hasNextContact()) << 1); } if(!(finished & 0x4)) { iter2.nextContact(patch2, contact2); newFinished |= (PxU32(!iter2.hasNextContact()) << 2); } if(!(finished & 0x8)) { iter3.nextContact(patch3, contact3); newFinished |= (PxU32(!iter3.hasNextContact()) << 3); } } ptr = p; if(hasMaxImpulse) { ptr += sizeof(Vec4V) * totalContacts; } //OK...friction time :-) Vec4V maxImpulseScale = V4One(); { const FrictionPatch& frictionPatch0 = c.frictionPatches[frictionIndex0]; const FrictionPatch& frictionPatch1 = c.frictionPatches[frictionIndex1]; const FrictionPatch& frictionPatch2 = c.frictionPatches[frictionIndex2]; const FrictionPatch& frictionPatch3 = c.frictionPatches[frictionIndex3]; PxU32 anchorCount0 = frictionPatch0.anchorCount; PxU32 anchorCount1 = frictionPatch1.anchorCount; PxU32 anchorCount2 = frictionPatch2.anchorCount; PxU32 anchorCount3 = frictionPatch3.anchorCount; PxU32 clampedAnchorCount0 = hasFinished0 || (contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount0; PxU32 clampedAnchorCount1 = hasFinished1 || (contactBase1->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount1; PxU32 clampedAnchorCount2 = hasFinished2 || (contactBase2->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount2; PxU32 clampedAnchorCount3 = hasFinished3 || (contactBase3->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount3; const PxU32 maxAnchorCount = PxMax(clampedAnchorCount0, PxMax(clampedAnchorCount1, PxMax(clampedAnchorCount2, clampedAnchorCount3))); PxReal coefficient0 = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount0 == 2) ? 0.5f : 1.f; PxReal coefficient1 = (contactBase1->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount1 == 2) ? 0.5f : 1.f; PxReal coefficient2 = (contactBase2->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount2 == 2) ? 0.5f : 1.f; PxReal coefficient3 = (contactBase3->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount3 == 2) ? 0.5f : 1.f; const Vec4V staticFriction = V4LoadXYZW(contactBase0->staticFriction*coefficient0, contactBase1->staticFriction*coefficient1, contactBase2->staticFriction*coefficient2, contactBase3->staticFriction*coefficient3); const Vec4V dynamicFriction = V4LoadXYZW(contactBase0->dynamicFriction*coefficient0, contactBase1->dynamicFriction*coefficient1, contactBase2->dynamicFriction*coefficient2, contactBase3->dynamicFriction*coefficient3); PX_ASSERT(totalContacts == contactCount); header->dynamicFriction = dynamicFriction; header->staticFriction = staticFriction; //if(clampedAnchorCount0 != clampedAnchorCount1 || clampedAnchorCount0 != clampedAnchorCount2 || clampedAnchorCount0 != clampedAnchorCount3) // Ps::debugBreak(); //const bool haveFriction = maxAnchorCount != 0; header->numFrictionConstr = Ps::to8(maxAnchorCount*2); header->numFrictionConstr0 = Ps::to8(clampedAnchorCount0*2); header->numFrictionConstr1 = Ps::to8(clampedAnchorCount1*2); header->numFrictionConstr2 = Ps::to8(clampedAnchorCount2*2); header->numFrictionConstr3 = Ps::to8(clampedAnchorCount3*2); //KS - TODO - extend this if needed header->type = Ps::to8(isDynamic ? DY_SC_TYPE_BLOCK_RB_CONTACT : DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT); if(maxAnchorCount) { //Allocate the shared friction data... SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(ptr); ptr += sizeof(SolverFrictionSharedData4); PX_UNUSED(fd); const BoolV cond =V4IsGrtr(orthoThreshold, V4Abs(normalX)); const Vec4V t0FallbackX = V4Sel(cond, zero, V4Neg(normalY)); const Vec4V t0FallbackY = V4Sel(cond, V4Neg(normalZ), normalX); const Vec4V t0FallbackZ = V4Sel(cond, normalY, zero); //const Vec4V dotNormalVrel = V4MulAdd(normalZ, vrelZ, V4MulAdd(normalY, vrelY, V4Mul(normalX, vrelX))); const Vec4V vrelSubNorVelX = V4NegMulSub(normalX, relNorVel, vrelX); const Vec4V vrelSubNorVelY = V4NegMulSub(normalY, relNorVel, vrelY); const Vec4V vrelSubNorVelZ = V4NegMulSub(normalZ, relNorVel, vrelZ); const Vec4V lenSqvrelSubNorVelZ = V4MulAdd(vrelSubNorVelX, vrelSubNorVelX, V4MulAdd(vrelSubNorVelY, vrelSubNorVelY, V4Mul(vrelSubNorVelZ, vrelSubNorVelZ))); const BoolV bcon2 = V4IsGrtr(lenSqvrelSubNorVelZ, p1); Vec4V t0X = V4Sel(bcon2, vrelSubNorVelX, t0FallbackX); Vec4V t0Y = V4Sel(bcon2, vrelSubNorVelY, t0FallbackY); Vec4V t0Z = V4Sel(bcon2, vrelSubNorVelZ, t0FallbackZ); //Now normalize this... const Vec4V recipLen = V4Rsqrt(V4MulAdd(t0Z, t0Z, V4MulAdd(t0Y, t0Y, V4Mul(t0X, t0X)))); t0X = V4Mul(t0X, recipLen); t0Y = V4Mul(t0Y, recipLen); t0Z = V4Mul(t0Z, recipLen); Vec4V t1X = V4NegMulSub(normalZ, t0Y, V4Mul(normalY, t0Z)); Vec4V t1Y = V4NegMulSub(normalX, t0Z, V4Mul(normalZ, t0X)); Vec4V t1Z = V4NegMulSub(normalY, t0X, V4Mul(normalX, t0Y)); PX_ASSERT((uintptr_t(descs[0].frictionPtr) & 0xF) == 0); PX_ASSERT((uintptr_t(descs[1].frictionPtr) & 0xF) == 0); PX_ASSERT((uintptr_t(descs[2].frictionPtr) & 0xF) == 0); PX_ASSERT((uintptr_t(descs[3].frictionPtr) & 0xF) == 0); PxU8* PX_RESTRICT writeback0 = descs[0].frictionPtr + frictionPatchWritebackAddrIndex0*sizeof(FrictionPatch); PxU8* PX_RESTRICT writeback1 = descs[1].frictionPtr + frictionPatchWritebackAddrIndex1*sizeof(FrictionPatch); PxU8* PX_RESTRICT writeback2 = descs[2].frictionPtr + frictionPatchWritebackAddrIndex2*sizeof(FrictionPatch); PxU8* PX_RESTRICT writeback3 = descs[3].frictionPtr + frictionPatchWritebackAddrIndex3*sizeof(FrictionPatch); PxU32 index0 = 0, index1 = 0, index2 = 0, index3 = 0; fd->broken = bFalse; fd->frictionBrokenWritebackByte[0] = writeback0; fd->frictionBrokenWritebackByte[1] = writeback1; fd->frictionBrokenWritebackByte[2] = writeback2; fd->frictionBrokenWritebackByte[3] = writeback3; fd->normalX[0] = t0X; fd->normalY[0] = t0Y; fd->normalZ[0] = t0Z; fd->normalX[1] = t1X; fd->normalY[1] = t1Y; fd->normalZ[1] = t1Z; Vec4V* PX_RESTRICT appliedForces = reinterpret_cast<Vec4V*>(ptr); ptr += sizeof(Vec4V)*header->numFrictionConstr; PxMemZero(appliedForces, sizeof(Vec4V) * header->numFrictionConstr); for(PxU32 j = 0; j < maxAnchorCount; j++) { Ps::prefetchLine(ptr, 384); Ps::prefetchLine(ptr, 512); Ps::prefetchLine(ptr, 640); SolverContactFrictionBase4* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionBase4*>(ptr); ptr += frictionSize; SolverContactFrictionBase4* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionBase4*>(ptr); ptr += frictionSize; index0 = j < clampedAnchorCount0 ? j : index0; index1 = j < clampedAnchorCount1 ? j : index1; index2 = j < clampedAnchorCount2 ? j : index2; index3 = j < clampedAnchorCount3 ? j : index3; if(j >= clampedAnchorCount0) maxImpulseScale = V4SetX(maxImpulseScale, fZero); if(j >= clampedAnchorCount1) maxImpulseScale = V4SetY(maxImpulseScale, fZero); if(j >= clampedAnchorCount2) maxImpulseScale = V4SetZ(maxImpulseScale, fZero); if(j >= clampedAnchorCount3) maxImpulseScale = V4SetW(maxImpulseScale, fZero); t0X = V4Mul(maxImpulseScale, t0X); t0Y = V4Mul(maxImpulseScale, t0Y); t0Z = V4Mul(maxImpulseScale, t0Z); t1X = V4Mul(maxImpulseScale, t1X); t1Y = V4Mul(maxImpulseScale, t1Y); t1Z = V4Mul(maxImpulseScale, t1Z); Vec3V body0Anchor0 = V3LoadU(frictionPatch0.body0Anchors[index0]); Vec3V body0Anchor1 = V3LoadU(frictionPatch1.body0Anchors[index1]); Vec3V body0Anchor2 = V3LoadU(frictionPatch2.body0Anchors[index2]); Vec3V body0Anchor3 = V3LoadU(frictionPatch3.body0Anchors[index3]); Vec4V ra0 = Vec4V_From_Vec3V(QuatRotate(bodyFrame00q, body0Anchor0)); Vec4V ra1 = Vec4V_From_Vec3V(QuatRotate(bodyFrame01q, body0Anchor1)); Vec4V ra2 = Vec4V_From_Vec3V(QuatRotate(bodyFrame02q, body0Anchor2)); Vec4V ra3 = Vec4V_From_Vec3V(QuatRotate(bodyFrame03q, body0Anchor3)); Vec4V raX, raY, raZ; PX_TRANSPOSE_44_34(ra0, ra1, ra2, ra3, raX, raY, raZ); /*raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX); raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY); raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ);*/ const Vec4V raWorldX = V4Add(raX, bodyFrame0pX); const Vec4V raWorldY = V4Add(raY, bodyFrame0pY); const Vec4V raWorldZ = V4Add(raZ, bodyFrame0pZ); Vec3V body1Anchor0 = V3LoadU(frictionPatch0.body1Anchors[index0]); Vec3V body1Anchor1 = V3LoadU(frictionPatch1.body1Anchors[index1]); Vec3V body1Anchor2 = V3LoadU(frictionPatch2.body1Anchors[index2]); Vec3V body1Anchor3 = V3LoadU(frictionPatch3.body1Anchors[index3]); Vec4V rb0 = Vec4V_From_Vec3V(QuatRotate(bodyFrame10q, body1Anchor0)); Vec4V rb1 = Vec4V_From_Vec3V(QuatRotate(bodyFrame11q, body1Anchor1)); Vec4V rb2 = Vec4V_From_Vec3V(QuatRotate(bodyFrame12q, body1Anchor2)); Vec4V rb3 = Vec4V_From_Vec3V(QuatRotate(bodyFrame13q, body1Anchor3)); Vec4V rbX, rbY, rbZ; PX_TRANSPOSE_44_34(rb0, rb1, rb2, rb3, rbX, rbY, rbZ); /*rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX); rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY); rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);*/ const Vec4V rbWorldX = V4Add(rbX, bodyFrame1pX); const Vec4V rbWorldY = V4Add(rbY, bodyFrame1pY); const Vec4V rbWorldZ = V4Add(rbZ, bodyFrame1pZ); Vec4V errorX = V4Sub(raWorldX, rbWorldX); Vec4V errorY = V4Sub(raWorldY, rbWorldY); Vec4V errorZ = V4Sub(raWorldZ, rbWorldZ); /*errorX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorX)), zero, errorX); errorY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorY)), zero, errorY); errorZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorZ)), zero, errorZ);*/ //KS - todo - get this working with per-point friction PxU32 contactIndex0 = c.contactID[frictionIndex0][index0]; PxU32 contactIndex1 = c.contactID[frictionIndex1][index1]; PxU32 contactIndex2 = c.contactID[frictionIndex2][index2]; PxU32 contactIndex3 = c.contactID[frictionIndex3][index3]; //Ensure that the ocntact indices are valid PX_ASSERT(contactIndex0 == 0xffff || contactIndex0 < descs[0].numContacts); PX_ASSERT(contactIndex1 == 0xffff || contactIndex1 < descs[1].numContacts); PX_ASSERT(contactIndex2 == 0xffff || contactIndex2 < descs[2].numContacts); PX_ASSERT(contactIndex3 == 0xffff || contactIndex3 < descs[3].numContacts); Vec4V targetVel0 = V4LoadA(contactIndex0 == 0xFFFF ? &contactBase0->targetVel.x : &descs[0].contacts[contactIndex0].targetVel.x); Vec4V targetVel1 = V4LoadA(contactIndex1 == 0xFFFF ? &contactBase0->targetVel.x : &descs[1].contacts[contactIndex1].targetVel.x); Vec4V targetVel2 = V4LoadA(contactIndex2 == 0xFFFF ? &contactBase0->targetVel.x : &descs[2].contacts[contactIndex2].targetVel.x); Vec4V targetVel3 = V4LoadA(contactIndex3 == 0xFFFF ? &contactBase0->targetVel.x : &descs[3].contacts[contactIndex3].targetVel.x); Vec4V targetVelX, targetVelY, targetVelZ; PX_TRANSPOSE_44_34(targetVel0, targetVel1, targetVel2, targetVel3, targetVelX, targetVelY, targetVelZ); { Vec4V raXnX = V4NegMulSub(raZ, t0Y, V4Mul(raY, t0Z)); Vec4V raXnY = V4NegMulSub(raX, t0Z, V4Mul(raZ, t0X)); Vec4V raXnZ = V4NegMulSub(raY, t0X, V4Mul(raX, t0Y)); raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX); raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY); raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ); Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX); Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX); Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX); delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X); delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y); delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z); delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X); delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y); delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z); const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X))); Vec4V resp = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0); const Vec4V tVel0 = V4MulAdd(t0Z, linVelT20, V4MulAdd(t0Y, linVelT10, V4Mul(t0X, linVelT00))); Vec4V vrel = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0))); if(isDynamic) { SolverContactFrictionDynamic4* PX_RESTRICT dynamicF0 = static_cast<SolverContactFrictionDynamic4*>(f0); Vec4V rbXnX = V4NegMulSub(rbZ, t0Y, V4Mul(rbY, t0Z)); Vec4V rbXnY = V4NegMulSub(rbX, t0Z, V4Mul(rbZ, t0X)); Vec4V rbXnZ = V4NegMulSub(rbY, t0X, V4Mul(rbX, t0Y)); rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX); rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY); rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ); Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX); Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX); Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX); delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X); delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y); delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z); delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X); delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y); delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z); const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X))); const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1); resp = V4Add(resp, resp1); dynamicF0->rbXnX = delAngVel1X; dynamicF0->rbXnY = delAngVel1Y; dynamicF0->rbXnZ = delAngVel1Z; const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01))); const Vec4V vel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1))); vrel = V4Sub(vrel, vel1); } else if(hasKinematic) { const Vec4V rbXnX = V4NegMulSub(rbZ, t0Y, V4Mul(rbY, t0Z)); const Vec4V rbXnY = V4NegMulSub(rbX, t0Z, V4Mul(rbZ, t0X)); const Vec4V rbXnZ = V4NegMulSub(rbY, t0X, V4Mul(rbX, t0Y)); const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01))); const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1))); vrel = V4Sub(vrel, dotRbXnAngVel1); } const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero)); Vec4V bias = V4Scale(V4MulAdd(t0Z, errorZ, V4MulAdd(t0Y, errorY, V4Mul(t0X, errorX))), invDt); Vec4V targetVel = V4MulAdd(t0Z, targetVelZ,V4MulAdd(t0Y, targetVelY, V4Mul(t0X, targetVelX))); targetVel = V4Sub(targetVel, vrel); f0->targetVelocity = V4Neg(V4Mul(targetVel, velMultiplier)); bias = V4Sub(bias, targetVel); f0->raXnX = delAngVel0X; f0->raXnY = delAngVel0Y; f0->raXnZ = delAngVel0Z; f0->scaledBias = V4Mul(bias, velMultiplier); f0->velMultiplier = velMultiplier; } { Vec4V raXnX = V4NegMulSub(raZ, t1Y, V4Mul(raY, t1Z)); Vec4V raXnY = V4NegMulSub(raX, t1Z, V4Mul(raZ, t1X)); Vec4V raXnZ = V4NegMulSub(raY, t1X, V4Mul(raX, t1Y)); raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX); raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY); raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ); Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX); Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX); Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX); delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X); delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y); delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z); delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X); delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y); delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z); const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X))); Vec4V resp = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0); const Vec4V tVel0 = V4MulAdd(t1Z, linVelT20, V4MulAdd(t1Y, linVelT10, V4Mul(t1X, linVelT00))); Vec4V vrel = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0))); if(isDynamic) { SolverContactFrictionDynamic4* PX_RESTRICT dynamicF1 = static_cast<SolverContactFrictionDynamic4*>(f1); Vec4V rbXnX = V4NegMulSub(rbZ, t1Y, V4Mul(rbY, t1Z)); Vec4V rbXnY = V4NegMulSub(rbX, t1Z, V4Mul(rbZ, t1X)); Vec4V rbXnZ = V4NegMulSub(rbY, t1X, V4Mul(rbX, t1Y)); rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX); rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY); rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ); Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX); Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX); Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX); delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X); delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y); delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z); delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X); delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y); delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z); const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X))); const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1); resp = V4Add(resp, resp1); dynamicF1->rbXnX = delAngVel1X; dynamicF1->rbXnY = delAngVel1Y; dynamicF1->rbXnZ = delAngVel1Z; const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01))); const Vec4V vel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1))); vrel = V4Sub(vrel, vel1); } else if(hasKinematic) { const Vec4V rbXnX = V4NegMulSub(rbZ, t1Y, V4Mul(rbY, t1Z)); const Vec4V rbXnY = V4NegMulSub(rbX, t1Z, V4Mul(rbZ, t1X)); const Vec4V rbXnZ = V4NegMulSub(rbY, t1X, V4Mul(rbX, t1Y)); const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01))); const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1))); vrel = V4Sub(vrel, dotRbXnAngVel1); } const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero)); Vec4V bias = V4Scale(V4MulAdd(t1Z, errorZ, V4MulAdd(t1Y, errorY, V4Mul(t1X, errorX))), invDt); Vec4V targetVel = V4MulAdd(t1Z, targetVelZ,V4MulAdd(t1Y, targetVelY, V4Mul(t1X, targetVelX))); targetVel = V4Sub(targetVel, vrel); f1->targetVelocity = V4Neg(V4Mul(targetVel, velMultiplier)); bias = V4Sub(bias, targetVel); f1->raXnX = delAngVel0X; f1->raXnY = delAngVel0Y; f1->raXnZ = delAngVel0Z; f1->scaledBias = V4Mul(bias, velMultiplier); f1->velMultiplier = velMultiplier; } } frictionPatchWritebackAddrIndex0++; frictionPatchWritebackAddrIndex1++; frictionPatchWritebackAddrIndex2++; frictionPatchWritebackAddrIndex3++; } } } } PX_FORCE_INLINE void computeBlockStreamFrictionByteSizes(const CorrelationBuffer& c, PxU32& _frictionPatchByteSize, PxU32& _numFrictionPatches, PxU32 frictionPatchStartIndex, PxU32 frictionPatchEndIndex) { // PT: use local vars to remove LHS PxU32 numFrictionPatches = 0; for(PxU32 i = frictionPatchStartIndex; i < frictionPatchEndIndex; i++) { //Friction patches. if(c.correlationListHeads[i] != CorrelationBuffer::LIST_END) numFrictionPatches++; } PxU32 frictionPatchByteSize = numFrictionPatches*sizeof(FrictionPatch); _numFrictionPatches = numFrictionPatches; //16-byte alignment. _frictionPatchByteSize = ((frictionPatchByteSize + 0x0f) & ~0x0f); PX_ASSERT(0 == (_frictionPatchByteSize & 0x0f)); } static bool reserveFrictionBlockStreams(const CorrelationBuffer& c, PxConstraintAllocator& constraintAllocator, PxU32 frictionPatchStartIndex, PxU32 frictionPatchEndIndex, FrictionPatch*& _frictionPatches, PxU32& numFrictionPatches) { //From frictionPatchStream we just need to reserve a single buffer. PxU32 frictionPatchByteSize = 0; //Compute the sizes of all the buffers. computeBlockStreamFrictionByteSizes(c, frictionPatchByteSize, numFrictionPatches, frictionPatchStartIndex, frictionPatchEndIndex); FrictionPatch* frictionPatches = NULL; //If the constraint block reservation didn't fail then reserve the friction buffer too. if(frictionPatchByteSize > 0) { frictionPatches = reinterpret_cast<FrictionPatch*>(constraintAllocator.reserveFrictionData(frictionPatchByteSize)); if(0==frictionPatches || (reinterpret_cast<FrictionPatch*>(-1))==frictionPatches) { if(0==frictionPatches) { PX_WARN_ONCE( "Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. " "Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks."); } else { PX_WARN_ONCE( "Attempting to allocate more than 16K of friction data for a single contact pair in constraint prep. " "Either accept dropped contacts or simplify collision geometry."); frictionPatches=NULL; } } } _frictionPatches = frictionPatches; //Return true if neither of the two block reservations failed. return (0==frictionPatchByteSize || frictionPatches); } //The persistent friction patch correlation/allocation will already have happenned as this is per-pair. //This function just computes the size of the combined solve data. void computeBlockStreamByteSizes4(PxSolverContactDesc* descs, PxU32& _solverConstraintByteSize, PxU32* _axisConstraintCount, const CorrelationBuffer& c) { PX_ASSERT(0 == _solverConstraintByteSize); PxU32 maxPatches = 0; PxU32 maxFrictionPatches = 0; PxU32 maxContactCount[CorrelationBuffer::MAX_FRICTION_PATCHES]; PxU32 maxFrictionCount[CorrelationBuffer::MAX_FRICTION_PATCHES]; PxMemZero(maxContactCount, sizeof(maxContactCount)); PxMemZero(maxFrictionCount, sizeof(maxFrictionCount)); bool hasMaxImpulse = false; for(PxU32 a = 0; a < 4; ++a) { PxU32 axisConstraintCount = 0; hasMaxImpulse = hasMaxImpulse || descs[a].hasMaxImpulse; for(PxU32 i = 0; i < descs[a].numFrictionPatches; i++) { PxU32 ind = i + descs[a].startFrictionPatchIndex; const FrictionPatch& frictionPatch = c.frictionPatches[ind]; const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0 && frictionPatch.anchorCount != 0; //Solver constraint data. if(c.frictionPatchContactCounts[ind]!=0) { maxContactCount[i] = PxMax(c.frictionPatchContactCounts[ind], maxContactCount[i]); axisConstraintCount += c.frictionPatchContactCounts[ind]; if(haveFriction) { const PxU32 fricCount = PxU32(c.frictionPatches[ind].anchorCount) * 2; maxFrictionCount[i] = PxMax(fricCount, maxFrictionCount[i]); axisConstraintCount += fricCount; } } } maxPatches = PxMax(descs[a].numFrictionPatches, maxPatches); _axisConstraintCount[a] = axisConstraintCount; } for(PxU32 a = 0; a < maxPatches; ++a) { if(maxFrictionCount[a] > 0) maxFrictionPatches++; } PxU32 totalContacts = 0, totalFriction = 0; for(PxU32 a = 0; a < maxPatches; ++a) { totalContacts += maxContactCount[a]; totalFriction += maxFrictionCount[a]; } //OK, we have a given number of friction patches, contact points and friction constraints so we can calculate how much memory we need //Body 2 is considered static if it is either *not dynamic* or *kinematic* bool hasDynamicBody = false; for(PxU32 a = 0; a < 4; ++a) { hasDynamicBody = hasDynamicBody || ((descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY)); } const bool isStatic = !hasDynamicBody; const PxU32 headerSize = sizeof(SolverContactHeader4) * maxPatches + sizeof(SolverFrictionSharedData4) * maxFrictionPatches; PxU32 constraintSize = isStatic ? (sizeof(SolverContactBatchPointBase4) * totalContacts) + ( sizeof(SolverContactFrictionBase4) * totalFriction) : (sizeof(SolverContactBatchPointDynamic4) * totalContacts) + (sizeof(SolverContactFrictionDynamic4) * totalFriction); //Space for the appliedForce buffer constraintSize += sizeof(Vec4V)*(totalContacts+totalFriction); //If we have max impulse, reserve a buffer for it if(hasMaxImpulse) constraintSize += sizeof(Ps::aos::Vec4V) * totalContacts; _solverConstraintByteSize = ((constraintSize + headerSize + 0x0f) & ~0x0f); PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f)); } static SolverConstraintPrepState::Enum reserveBlockStreams4(PxSolverContactDesc* descs, Dy::CorrelationBuffer& c, PxU8*& solverConstraint, PxU32* axisConstraintCount, PxU32& solverConstraintByteSize, PxConstraintAllocator& constraintAllocator) { PX_ASSERT(NULL == solverConstraint); PX_ASSERT(0 == solverConstraintByteSize); //Compute the sizes of all the buffers. computeBlockStreamByteSizes4(descs, solverConstraintByteSize, axisConstraintCount, c); //Reserve the buffers. //First reserve the accumulated buffer size for the constraint block. PxU8* constraintBlock = NULL; const PxU32 constraintBlockByteSize = solverConstraintByteSize; if(constraintBlockByteSize > 0) { if((constraintBlockByteSize + 16u) > 16384) return SolverConstraintPrepState::eUNBATCHABLE; constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u); if(0==constraintBlock || (reinterpret_cast<PxU8*>(-1))==constraintBlock) { if(0==constraintBlock) { PX_WARN_ONCE( "Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. " "Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks."); } else { PX_WARN_ONCE( "Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. " "Either accept dropped contacts or simplify collision geometry."); constraintBlock=NULL; } } } //Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail). if(0==constraintBlockByteSize || constraintBlock) { if(solverConstraintByteSize) { solverConstraint = constraintBlock; PX_ASSERT(0==(uintptr_t(solverConstraint) & 0x0f)); } } return ((0==constraintBlockByteSize || constraintBlock)) ? SolverConstraintPrepState::eSUCCESS : SolverConstraintPrepState::eOUT_OF_MEMORY; } SolverConstraintPrepState::Enum createFinalizeSolverContacts4( Dy::CorrelationBuffer& c, PxSolverContactDesc* blockDescs, const PxReal invDtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxReal solverOffsetSlop, PxConstraintAllocator& constraintAllocator) { PX_ALIGN(16, PxReal invMassScale0[4]); PX_ALIGN(16, PxReal invMassScale1[4]); PX_ALIGN(16, PxReal invInertiaScale0[4]); PX_ALIGN(16, PxReal invInertiaScale1[4]); c.frictionPatchCount = 0; c.contactPatchCount = 0; for (PxU32 a = 0; a < 4; ++a) { PxSolverContactDesc& blockDesc = blockDescs[a]; invMassScale0[a] = blockDesc.mInvMassScales.linear0; invMassScale1[a] = blockDesc.mInvMassScales.linear1; invInertiaScale0[a] = blockDesc.mInvMassScales.angular0; invInertiaScale1[a] = blockDesc.mInvMassScales.angular1; blockDesc.startFrictionPatchIndex = c.frictionPatchCount; if (!(blockDesc.disableStrongFriction)) { bool valid = getFrictionPatches(c, blockDesc.frictionPtr, blockDesc.frictionCount, blockDesc.bodyFrame0, blockDesc.bodyFrame1, correlationDistance); if (!valid) return SolverConstraintPrepState::eUNBATCHABLE; } //Create the contact patches blockDesc.startContactPatchIndex = c.contactPatchCount; if (!createContactPatches(c, blockDesc.contacts, blockDesc.numContacts, PXC_SAME_NORMAL)) return SolverConstraintPrepState::eUNBATCHABLE; blockDesc.numContactPatches = PxU16(c.contactPatchCount - blockDesc.startContactPatchIndex); bool overflow = correlatePatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, PXC_SAME_NORMAL, blockDesc.startContactPatchIndex, blockDesc.startFrictionPatchIndex); if (overflow) return SolverConstraintPrepState::eUNBATCHABLE; growPatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, correlationDistance, blockDesc.startFrictionPatchIndex, frictionOffsetThreshold + blockDescs[a].restDistance); //Remove the empty friction patches - do we actually need to do this? for (PxU32 p = c.frictionPatchCount; p > blockDesc.startFrictionPatchIndex; --p) { if (c.correlationListHeads[p - 1] == 0xffff) { //We have an empty patch...need to bin this one... for (PxU32 p2 = p; p2 < c.frictionPatchCount; ++p2) { c.correlationListHeads[p2 - 1] = c.correlationListHeads[p2]; c.frictionPatchContactCounts[p2 - 1] = c.frictionPatchContactCounts[p2]; } c.frictionPatchCount--; } } PxU32 numFricPatches = c.frictionPatchCount - blockDesc.startFrictionPatchIndex; blockDesc.numFrictionPatches = numFricPatches; } FrictionPatch* frictionPatchArray[4]; PxU32 frictionPatchCounts[4]; for (PxU32 a = 0; a < 4; ++a) { PxSolverContactDesc& blockDesc = blockDescs[a]; const bool successfulReserve = reserveFrictionBlockStreams(c, constraintAllocator, blockDesc.startFrictionPatchIndex, blockDesc.numFrictionPatches + blockDesc.startFrictionPatchIndex, frictionPatchArray[a], frictionPatchCounts[a]); //KS - TODO - how can we recover if we failed to allocate this memory? if (!successfulReserve) { return SolverConstraintPrepState::eOUT_OF_MEMORY; } } //At this point, all the friction data has been calculated, the correlation has been done. Provided this was all successful, //we are ready to create the batched constraints PxU8* solverConstraint = NULL; PxU32 solverConstraintByteSize = 0; { PxU32 axisConstraintCount[4]; SolverConstraintPrepState::Enum state = reserveBlockStreams4(blockDescs, c, solverConstraint, axisConstraintCount, solverConstraintByteSize, constraintAllocator); if (state != SolverConstraintPrepState::eSUCCESS) return state; for (PxU32 a = 0; a < 4; ++a) { FrictionPatch* frictionPatches = frictionPatchArray[a]; PxSolverContactDesc& blockDesc = blockDescs[a]; PxSolverConstraintDesc& desc = *blockDesc.desc; blockDesc.frictionPtr = reinterpret_cast<PxU8*>(frictionPatches); blockDesc.frictionCount = Ps::to8(frictionPatchCounts[a]); //Initialise friction buffer. if (frictionPatches) { // PT: TODO: revisit this... not very satisfying //const PxU32 maxSize = numFrictionPatches*sizeof(FrictionPatch); Ps::prefetchLine(frictionPatches); Ps::prefetchLine(frictionPatches, 128); Ps::prefetchLine(frictionPatches, 256); for (PxU32 i = 0; i<blockDesc.numFrictionPatches; i++) { if (c.correlationListHeads[blockDesc.startFrictionPatchIndex + i] != CorrelationBuffer::LIST_END) { //*frictionPatches++ = c.frictionPatches[blockDesc.startFrictionPatchIndex + i]; PxMemCopy(frictionPatches++, &c.frictionPatches[blockDesc.startFrictionPatchIndex + i], sizeof(FrictionPatch)); //Ps::prefetchLine(frictionPatches, 256); } } } blockDesc.axisConstraintCount += Ps::to16(axisConstraintCount[a]); desc.constraint = solverConstraint; desc.constraintLengthOver16 = Ps::to16(solverConstraintByteSize / 16); desc.writeBackLengthOver4 = PxU16(blockDesc.numContacts); desc.writeBack = blockDesc.contactForces; } const Vec4V iMassScale0 = V4LoadA(invMassScale0); const Vec4V iInertiaScale0 = V4LoadA(invInertiaScale0); const Vec4V iMassScale1 = V4LoadA(invMassScale1); const Vec4V iInertiaScale1 = V4LoadA(invInertiaScale1); setupFinalizeSolverConstraints4(blockDescs, c, solverConstraint, invDtF32, bounceThresholdF32, solverOffsetSlop, iMassScale0, iInertiaScale0, iMassScale1, iInertiaScale1); PX_ASSERT((*solverConstraint == DY_SC_TYPE_BLOCK_RB_CONTACT) || (*solverConstraint == DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT)); *(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0; } return SolverConstraintPrepState::eSUCCESS; } //This returns 1 of 3 states: success, unbatchable or out-of-memory. If the constraint is unbatchable, we must fall back on 4 separate constraint //prep calls SolverConstraintPrepState::Enum createFinalizeSolverContacts4( PxsContactManagerOutput** cmOutputs, ThreadContext& threadContext, PxSolverContactDesc* blockDescs, const PxReal invDtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxReal solverOffsetSlop, PxConstraintAllocator& constraintAllocator) { for (PxU32 a = 0; a < 4; ++a) { blockDescs[a].desc->constraintLengthOver16 = 0; } PX_ASSERT(cmOutputs[0]->nbContacts && cmOutputs[1]->nbContacts && cmOutputs[2]->nbContacts && cmOutputs[3]->nbContacts); Gu::ContactBuffer& buffer = threadContext.mContactBuffer; buffer.count = 0; //PxTransform idt = PxTransform(PxIdentity); CorrelationBuffer& c = threadContext.mCorrelationBuffer; for (PxU32 a = 0; a < 4; ++a) { PxSolverContactDesc& blockDesc = blockDescs[a]; PxSolverConstraintDesc& desc = *blockDesc.desc; //blockDesc.startContactIndex = buffer.count; blockDesc.contacts = buffer.contacts + buffer.count; Ps::prefetchLine(desc.bodyA); Ps::prefetchLine(desc.bodyB); if ((buffer.count + cmOutputs[a]->nbContacts) > 64) { return SolverConstraintPrepState::eUNBATCHABLE; } bool hasMaxImpulse = false; bool hasTargetVelocity = false; //OK...do the correlation here as well... Ps::prefetchLine(blockDescs[a].frictionPtr); Ps::prefetchLine(blockDescs[a].frictionPtr, 64); Ps::prefetchLine(blockDescs[a].frictionPtr, 128); if (a < 3) { Ps::prefetchLine(cmOutputs[a]->contactPatches); Ps::prefetchLine(cmOutputs[a]->contactPoints); } PxReal invMassScale0, invMassScale1, invInertiaScale0, invInertiaScale1; const PxReal defaultMaxImpulse = PxMin(blockDesc.data0->maxContactImpulse, blockDesc.data1->maxContactImpulse); PxU32 contactCount = extractContacts(buffer, *cmOutputs[a], hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1, invInertiaScale0, invInertiaScale1, defaultMaxImpulse); if (contactCount == 0) return SolverConstraintPrepState::eUNBATCHABLE; blockDesc.numContacts = contactCount; blockDesc.hasMaxImpulse = hasMaxImpulse; blockDesc.disableStrongFriction = blockDesc.disableStrongFriction || hasTargetVelocity; blockDesc.mInvMassScales.linear0 *= invMassScale0; blockDesc.mInvMassScales.linear1 *= invMassScale1; blockDesc.mInvMassScales.angular0 *= invInertiaScale0; blockDesc.mInvMassScales.angular1 *= invInertiaScale1; //blockDesc.frictionPtr = &blockDescs[a].frictionPtr; //blockDesc.frictionCount = blockDescs[a].frictionCount; } return createFinalizeSolverContacts4(c, blockDescs, invDtF32, bounceThresholdF32, frictionOffsetThreshold, correlationDistance, solverOffsetSlop, constraintAllocator); } } }
42.597798
185
0.742151
[ "geometry" ]
8b31101b6c360c9301e1e7de08e58064bb8c496f
12,791
cpp
C++
AprilTagTrackers/Parameters.cpp
LosWheatleynDew/April-Tag-VR-FullBody-Tracker
033eb3bad014639f9fc1cc5c147dd2632499dc04
[ "MIT" ]
1
2022-03-11T08:50:27.000Z
2022-03-11T08:50:27.000Z
AprilTagTrackers/Parameters.cpp
LosWheatleynDew/April-Tag-VR-FullBody-Tracker
033eb3bad014639f9fc1cc5c147dd2632499dc04
[ "MIT" ]
null
null
null
AprilTagTrackers/Parameters.cpp
LosWheatleynDew/April-Tag-VR-FullBody-Tracker
033eb3bad014639f9fc1cc5c147dd2632499dc04
[ "MIT" ]
null
null
null
#define GET_VARIABLE_NAME(Variable) (#Variable) #include "Parameters.h" Parameters::Parameters() { Load(); } void Parameters::Load() { cv::FileStorage fs("params.yml", cv::FileStorage::READ); //open test.yml file to read parameters if (!fs["cameraAddr"].empty()) //if file exists, load all parameters from file into variables { fs["markersPerTracker"] >> markersPerTracker; if (markersPerTracker <= 0) markersPerTracker = 45; aruco_params = cv::aruco::DetectorParameters::create(); aruco_params->detectInvertedMarker = true; aruco_params->cornerRefinementMethod = 2; cv::FileNode fn = fs["arucoParams"]; if (!fn.empty()) //load all saved aruco params { fn["cornerRefinementMethod"] >> aruco_params->cornerRefinementMethod; fn["markerBorderBits"] >> aruco_params->markerBorderBits; fn["adaptiveThreshConstant"] >> aruco_params->adaptiveThreshConstant; fn["adaptiveThreshWinSizeMax"] >> aruco_params->adaptiveThreshWinSizeMax; fn["adaptiveThreshWinSizeMin"] >> aruco_params->adaptiveThreshWinSizeMin; fn["adaptiveThreshWinSizeStep"] >> aruco_params->adaptiveThreshWinSizeStep; fn["aprilTagCriticalRad"] >> aruco_params->aprilTagCriticalRad; fn["aprilTagDeglitch"] >> aruco_params->aprilTagDeglitch; fn["aprilTagMaxLineFitMse"] >> aruco_params->aprilTagMaxLineFitMse; fn["aprilTagMaxNmaxima"] >> aruco_params->aprilTagMaxNmaxima; fn["aprilTagMinClusterPixels"] >> aruco_params->aprilTagMinClusterPixels; fn["aprilTagMinWhiteBlackDiff"] >> aruco_params->aprilTagMinWhiteBlackDiff; fn["aprilTagQuadDecimate"] >> aruco_params->aprilTagQuadDecimate; fn["aprilTagQuadSigma"] >> aruco_params->aprilTagQuadSigma; fn["cornerRefinementMaxIterations"] >> aruco_params->cornerRefinementMaxIterations; fn["cornerRefinementMinAccuracy"] >> aruco_params->cornerRefinementMinAccuracy; fn["cornerRefinementWinSize"] >> aruco_params->cornerRefinementWinSize; fn["detectInvertedMarker"] >> aruco_params->detectInvertedMarker; fn["errorCorrectionRate"] >> aruco_params->errorCorrectionRate; fn["maxErroneousBitsInBorderRate"] >> aruco_params->maxErroneousBitsInBorderRate; fn["maxMarkerPerimeterRate"] >> aruco_params->maxMarkerPerimeterRate; fn["minCornerDistanceRate"] >> aruco_params->minCornerDistanceRate; fn["minDistanceToBorder"] >> aruco_params->minDistanceToBorder; fn["minMarkerDistanceRate"] >> aruco_params->minMarkerDistanceRate; fn["minMarkerPerimeterRate"] >> aruco_params->minMarkerPerimeterRate; fn["minOtsuStdDev"] >> aruco_params->minOtsuStdDev; fn["perspectiveRemoveIgnoredMarginPerCell"] >> aruco_params->perspectiveRemoveIgnoredMarginPerCell; fn["perspectiveRemovePixelPerCell"] >> aruco_params->perspectiveRemovePixelPerCell; fn["polygonalApproxAccuracyRate"] >> aruco_params->polygonalApproxAccuracyRate; } fs["cameraAddr"] >> cameraAddr; fs["cameraApiPreference"] >> cameraApiPreference; fs["camFps"] >> camFps; fs["camHeight"] >> camHeight; fs["camWidth"] >> camWidth; fs["cameraMatrix"] >> camMat; fs["distortionCoeffs"] >> distCoeffs; fs["stdDeviationsIntrinsics"] >> stdDeviationsIntrinsics; fs["perViewErrors"] >> perViewErrors; fs["allCharucoCorners"] >> allCharucoCorners; fs["allCharucoIds"] >> allCharucoIds; fs["trackerNum"] >> trackerNum; fs["markerSize"] >> markerSize; fs["numOfPrevValues"] >> numOfPrevValues; fs["quadDecimate"] >> quadDecimate; fs["searchWindow"] >> searchWindow; fs["octiuSah"] >> octiuSah; fs["usePredictive"] >> usePredictive; fs["calibrationTracker"] >> calibrationTracker; fs["rotateCl"] >> rotateCl; fs["rotateCounterCl"] >> rotateCounterCl; fs["coloredMarkers"] >> coloredMarkers; fs["calibOffsetX"] >> calibOffsetX; fs["calibOffsetY"] >> calibOffsetY; fs["calibOffsetZ"] >> calibOffsetZ; fs["calibOffsetA"] >> calibOffsetA; fs["calibOffsetB"] >> calibOffsetB; fs["calibOffsetC"] >> calibOffsetC; fs["circularWindow"] >> circularWindow; fs["smoothingFactor"] >> smoothingFactor; fs["ignoreTracker0"] >> ignoreTracker0; fs["wtranslation"] >> wtranslation; cv::Mat wrotmat; fs["wrotation"] >> wrotmat; fs["cameraSettings"] >> cameraSettings; fs["chessboardCalib"] >> chessboardCalib; fs["camLatency"] >> camLatency; fs["circularMarkers"] >> circularMarkers; fs["trackerCalibDistance"] >> trackerCalibDistance; if (trackerCalibDistance < 0.5) trackerCalibDistance = 0.5; fs["cameraCalibSamples"] >> cameraCalibSamples; if (cameraCalibSamples < 15) cameraCalibSamples = 15; fs["settingsParameters"] >> settingsParameters; fs["cameraAutoexposure"] >> cameraAutoexposure; fs["cameraExposure"] >> cameraExposure; fs["cameraGain"] >> cameraGain; fs["trackerCalibCenters"] >> trackerCalibCenters; fs["depthSmoothing"] >> depthSmoothing; fs["additionalSmoothing"] >> additionalSmoothing; fs["markerLibrary"] >> markerLibrary; fs["languageSelection"] >> languageSelection; fs["calibScale"] >> calibScale; if (calibScale < 0.5) calibScale = 1; if(!wrotmat.empty()) wrotation = Quaternion<double>(wrotmat.at<double>(0), wrotmat.at<double>(1), wrotmat.at<double>(2), wrotmat.at<double>(3)); fn = fs["trackers"]; if (!fn.empty()) //load all saved markers { cv::FileNodeIterator curMarker = fn.begin(), it_end = fn.end(); for (; curMarker != it_end; ++curMarker) { std::vector<std::vector<cv::Point3f>> boardCorners; std::vector<int> boardIds; cv::FileNode item = *curMarker; item["trackerIds"] >> boardIds; //data.push_back(tmp); cv::FileNode fnCorners = item["trackerCorners"]; if (!fnCorners.empty()) { cv::FileNodeIterator curCorners = fnCorners.begin(), itCorners_end = fnCorners.end(); for (; curCorners != itCorners_end; ++curCorners) { std::vector<cv::Point3f> corners; cv::FileNode item2 = *curCorners; item2 >> corners; boardCorners.push_back(corners); } } cv::Ptr<cv::aruco::Board> arBoard = cv::aruco::Board::create(boardCorners, cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_50), boardIds); trackers.push_back(arBoard); } } } fs.release(); if(languageSelection == 1) language = get_lang_chinese(); } void Parameters::Save() { cv::FileStorage fs("params.yml", cv::FileStorage::WRITE); fs << "markersPerTracker" << markersPerTracker; fs << "arucoParams"; fs << "{"; fs << "cornerRefinementMethod" << aruco_params->cornerRefinementMethod; fs << "markerBorderBits" << aruco_params->markerBorderBits; fs << "adaptiveThreshConstant" << aruco_params->adaptiveThreshConstant; fs << "adaptiveThreshWinSizeMax" << aruco_params->adaptiveThreshWinSizeMax; fs << "adaptiveThreshWinSizeMin" << aruco_params->adaptiveThreshWinSizeMin; fs << "adaptiveThreshWinSizeStep" << aruco_params->adaptiveThreshWinSizeStep; fs << "aprilTagCriticalRad" << aruco_params->aprilTagCriticalRad; fs << "aprilTagDeglitch" << aruco_params->aprilTagDeglitch; fs << "aprilTagMaxLineFitMse" << aruco_params->aprilTagMaxLineFitMse; fs << "aprilTagMaxNmaxima" << aruco_params->aprilTagMaxNmaxima; fs << "aprilTagMinClusterPixels" << aruco_params->aprilTagMinClusterPixels; fs << "aprilTagMinWhiteBlackDiff" << aruco_params->aprilTagMinWhiteBlackDiff; fs << "aprilTagQuadDecimate" << aruco_params->aprilTagQuadDecimate; fs << "aprilTagQuadSigma" << aruco_params->aprilTagQuadSigma; fs << "cornerRefinementMaxIterations" << aruco_params->cornerRefinementMaxIterations; fs << "cornerRefinementMinAccuracy" << aruco_params->cornerRefinementMinAccuracy; fs << "cornerRefinementWinSize" << aruco_params->cornerRefinementWinSize; fs << "detectInvertedMarker" << aruco_params->detectInvertedMarker; fs << "errorCorrectionRate" << aruco_params->errorCorrectionRate; fs << "maxErroneousBitsInBorderRate" << aruco_params->maxErroneousBitsInBorderRate; fs << "maxMarkerPerimeterRate" << aruco_params->maxMarkerPerimeterRate; fs << "minCornerDistanceRate" << aruco_params->minCornerDistanceRate; fs << "minDistanceToBorder" << aruco_params->minDistanceToBorder; fs << "minMarkerDistanceRate" << aruco_params->minMarkerDistanceRate; fs << "minMarkerPerimeterRate" << aruco_params->minMarkerPerimeterRate; fs << "minOtsuStdDev" << aruco_params->minOtsuStdDev; fs << "perspectiveRemoveIgnoredMarginPerCell" << aruco_params->perspectiveRemoveIgnoredMarginPerCell; fs << "perspectiveRemovePixelPerCell" << aruco_params->perspectiveRemovePixelPerCell; fs << "polygonalApproxAccuracyRate" << aruco_params->polygonalApproxAccuracyRate; fs << "}"; fs << "cameraAddr" << cameraAddr; fs << "cameraApiPreference" << cameraApiPreference; fs << "camFps" << camFps; fs << "camHeight" << camHeight; fs << "camWidth" << camWidth; fs << "cameraMatrix" << camMat; fs << "distortionCoeffs" << distCoeffs; fs << "stdDeviationsIntrinsics" << stdDeviationsIntrinsics; fs << "perViewErrors" << perViewErrors; fs << "allCharucoCorners" << allCharucoCorners; fs << "allCharucoIds" << allCharucoIds; fs << "trackerNum" << trackerNum; fs << "markerSize" << markerSize; fs << "numOfPrevValues" << numOfPrevValues; fs << "quadDecimate" << quadDecimate; fs << "searchWindow" << searchWindow; fs << "octiuSah" << octiuSah; //maru's fs << "usePredictive" << usePredictive; fs << "calibrationTracker" << calibrationTracker; fs << "rotateCl" << rotateCl; fs << "rotateCounterCl" << rotateCounterCl; fs << "coloredMarkers" << coloredMarkers; fs << "calibOffsetX" << calibOffsetX; fs << "calibOffsetY" << calibOffsetY; fs << "calibOffsetZ" << calibOffsetZ; fs << "calibOffsetA" << calibOffsetA; fs << "calibOffsetB" << calibOffsetB; fs << "calibOffsetC" << calibOffsetC; fs << "circularWindow" << circularWindow; fs << "smoothingFactor" << smoothingFactor; fs << "ignoreTracker0" << ignoreTracker0; fs << "wtranslation" << wtranslation; fs <<"wrotation" << (cv::Mat_<double>(4,1) << wrotation.w,wrotation.x,wrotation.y,wrotation.z); fs << "cameraSettings" << cameraSettings; fs << "chessboardCalib" << chessboardCalib; fs << "camLatency" << camLatency; fs << "circularMarkers" << circularMarkers; fs << "trackerCalibDistance" << trackerCalibDistance; fs << "cameraCalibSamples" << cameraCalibSamples; fs << "settingsParameters" << settingsParameters; fs << "cameraAutoexposure" << cameraAutoexposure; fs << "cameraExposure" << cameraExposure; fs << "cameraGain" << cameraGain; fs << "trackerCalibCenters" << trackerCalibCenters; fs << "depthSmoothing" << depthSmoothing; fs << "additionalSmoothing" << additionalSmoothing; fs << "markerLibrary" << markerLibrary; fs << "languageSelection" << languageSelection; fs << "calibScale" << calibScale; fs << "trackers"; fs << "{"; for (int i = 0; i < trackers.size(); i++) { fs << "tracker_" + std::to_string(i); fs << "{"; fs << "trackerIds"; fs << trackers[i]->ids; fs << "trackerCorners"; fs << "{"; for (int j = 0; j < trackers[i]->objPoints.size(); j++) { fs << "trackerCorners_" + std::to_string(j); fs << trackers[i]->objPoints[j]; } fs << "}"; fs << "}"; } fs << "}"; language = Lang(); if (languageSelection == 1) language = get_lang_chinese(); }
49.770428
162
0.626691
[ "vector" ]
8b3399850593ab4049abd5addcc72dc5c52c0f17
149,744
cpp
C++
Source/monster.cpp
vladtepesch/devilutionX
e1db9ba77b06500e43bc49f310323758e67ba743
[ "Unlicense" ]
null
null
null
Source/monster.cpp
vladtepesch/devilutionX
e1db9ba77b06500e43bc49f310323758e67ba743
[ "Unlicense" ]
null
null
null
Source/monster.cpp
vladtepesch/devilutionX
e1db9ba77b06500e43bc49f310323758e67ba743
[ "Unlicense" ]
null
null
null
/** * @file monster.cpp * * Implementation of monster functionality, AI, actions, spawning, loading, etc. */ #include "monster.h" #include <algorithm> #include <array> #include <climits> #include <fmt/format.h> #include "control.h" #include "cursor.h" #include "dead.h" #include "drlg_l1.h" #include "drlg_l4.h" #include "engine/cel_header.hpp" #include "engine/load_file.hpp" #include "engine/random.hpp" #include "engine/render/cl2_render.hpp" #include "init.h" #include "lighting.h" #include "minitext.h" #include "missiles.h" #include "movie.h" #include "options.h" #include "spelldat.h" #include "storm/storm.h" #include "themes.h" #include "towners.h" #include "trigs.h" #include "utils/language.h" #ifdef _DEBUG #include "debug.h" #endif namespace devilution { CMonster LevelMonsterTypes[MAX_LVLMTYPES]; int LevelMonsterTypeCount; MonsterStruct Monsters[MAXMONSTERS]; int ActiveMonsters[MAXMONSTERS]; int ActiveMonsterCount; // BUGFIX: replace MonsterKillCounts[MAXMONSTERS] with MonsterKillCounts[NUM_MTYPES]. /** Tracks the total number of monsters killed per monster_id. */ int MonsterKillCounts[MAXMONSTERS]; bool sgbSaveSoundOn; /** Maps from direction to a left turn from the direction. */ Direction left[8] = { DIR_SE, DIR_S, DIR_SW, DIR_W, DIR_NW, DIR_N, DIR_NE, DIR_E }; /** Maps from direction to a right turn from the direction. */ Direction right[8] = { DIR_SW, DIR_W, DIR_NW, DIR_N, DIR_NE, DIR_E, DIR_SE, DIR_S }; /** Maps from direction to the opposite direction. */ Direction opposite[8] = { DIR_N, DIR_NE, DIR_E, DIR_SE, DIR_S, DIR_SW, DIR_W, DIR_NW }; namespace { #define NIGHTMARE_TO_HIT_BONUS 85 #define HELL_TO_HIT_BONUS 120 #define NIGHTMARE_AC_BONUS 50 #define HELL_AC_BONUS 80 /** Tracks which missile files are already loaded */ int totalmonsters; int monstimgtot; int uniquetrans; // BUGFIX: MWVel velocity values are not rounded consistently. The correct // formula for monster walk velocity is calculated as follows (for 16, 32 and 64 // pixel distances, respectively): // // vel16 = (16 << monsterWalkShift) / nframes // vel32 = (32 << monsterWalkShift) / nframes // vel64 = (64 << monsterWalkShift) / nframes // // The correct monster walk velocity table is as follows: // // int MWVel[24][3] = { // { 256, 512, 1024 }, // { 128, 256, 512 }, // { 85, 171, 341 }, // { 64, 128, 256 }, // { 51, 102, 205 }, // { 43, 85, 171 }, // { 37, 73, 146 }, // { 32, 64, 128 }, // { 28, 57, 114 }, // { 26, 51, 102 }, // { 23, 47, 93 }, // { 21, 43, 85 }, // { 20, 39, 79 }, // { 18, 37, 73 }, // { 17, 34, 68 }, // { 16, 32, 64 }, // { 15, 30, 60 }, // { 14, 28, 57 }, // { 13, 27, 54 }, // { 13, 26, 51 }, // { 12, 24, 49 }, // { 12, 23, 47 }, // { 11, 22, 45 }, // { 11, 21, 43 } // }; /** Maps from monster walk animation frame num to monster velocity. */ int MWVel[24][3] = { { 256, 512, 1024 }, { 128, 256, 512 }, { 85, 170, 341 }, { 64, 128, 256 }, { 51, 102, 204 }, { 42, 85, 170 }, { 36, 73, 146 }, { 32, 64, 128 }, { 28, 56, 113 }, { 26, 51, 102 }, { 23, 46, 93 }, { 21, 42, 85 }, { 19, 39, 78 }, { 18, 36, 73 }, { 17, 34, 68 }, { 16, 32, 64 }, { 15, 30, 60 }, { 14, 28, 57 }, { 13, 26, 54 }, { 12, 25, 51 }, { 12, 24, 48 }, { 11, 23, 46 }, { 11, 22, 44 }, { 10, 21, 42 } }; /** Maps from monster action to monster animation letter. */ char animletter[7] = "nwahds"; void InitMonsterTRN(CMonster &monst) { std::array<uint8_t, 256> colorTranslations; LoadFileInMem(monst.MData->TransFile, colorTranslations); std::replace(colorTranslations.begin(), colorTranslations.end(), 255, 0); int n = monst.MData->has_special ? 6 : 5; for (int i = 0; i < n; i++) { if (i == 1 && monst.mtype >= MT_COUNSLR && monst.mtype <= MT_ADVOCATE) { continue; } for (int j = 0; j < 8; j++) { Cl2ApplyTrans( CelGetFrame(monst.Anims[i].CMem.get(), j), colorTranslations, monst.Anims[i].Frames); } } } void InitMonster(MonsterStruct &monster, Direction rd, int mtype, Point position) { auto &monsterType = LevelMonsterTypes[mtype]; const auto &animData = monsterType.GetAnimData(MonsterGraphic::Stand); monster._mdir = rd; monster.position.tile = position; monster.position.future = position; monster.position.old = position; monster._mMTidx = mtype; monster._mmode = MM_STAND; monster.mName = _(monsterType.MData->mName); monster.MType = &monsterType; monster.MData = monsterType.MData; monster.AnimInfo = {}; monster.AnimInfo.pCelSprite = animData.CelSpritesForDirections[rd] ? &*animData.CelSpritesForDirections[rd] : nullptr; monster.AnimInfo.TicksPerFrame = animData.Rate; monster.AnimInfo.TickCounterOfCurrentFrame = GenerateRnd(monster.AnimInfo.TicksPerFrame - 1); monster.AnimInfo.NumberOfFrames = animData.Frames; monster.AnimInfo.CurrentFrame = GenerateRnd(monster.AnimInfo.NumberOfFrames - 1) + 1; monster.mLevel = monsterType.MData->mLevel; monster._mmaxhp = (monsterType.mMinHP + GenerateRnd(monsterType.mMaxHP - monsterType.mMinHP + 1)) << 6; if (monsterType.mtype == MT_DIABLO && !gbIsHellfire) { monster._mmaxhp /= 2; monster.mLevel -= 15; } if (!gbIsMultiplayer) monster._mmaxhp = std::max(monster._mmaxhp / 2, 64); monster._mhitpoints = monster._mmaxhp; monster._mAi = monsterType.MData->mAi; monster._mint = monsterType.MData->mInt; monster._mgoal = MGOAL_NORMAL; monster._mgoalvar1 = 0; monster._mgoalvar2 = 0; monster._mgoalvar3 = 0; monster._pathcount = 0; monster._mDelFlag = false; monster._uniqtype = 0; monster._msquelch = 0; monster.mlid = NO_LIGHT; // BUGFIX monsters initial light id should be -1 (fixed) monster._mRndSeed = AdvanceRndSeed(); monster._mAISeed = AdvanceRndSeed(); monster.mWhoHit = 0; monster.mExp = monsterType.MData->mExp; monster.mHit = monsterType.MData->mHit; monster.mMinDamage = monsterType.MData->mMinDamage; monster.mMaxDamage = monsterType.MData->mMaxDamage; monster.mHit2 = monsterType.MData->mHit2; monster.mMinDamage2 = monsterType.MData->mMinDamage2; monster.mMaxDamage2 = monsterType.MData->mMaxDamage2; monster.mArmorClass = monsterType.MData->mArmorClass; monster.mMagicRes = monsterType.MData->mMagicRes; monster.leader = 0; monster.leaderRelation = LeaderRelation::None; monster._mFlags = monsterType.MData->mFlags; monster.mtalkmsg = TEXT_NONE; if (monster._mAi == AI_GARG) { monster.AnimInfo.pCelSprite = &*monsterType.GetAnimData(MonsterGraphic::Special).CelSpritesForDirections[rd]; monster.AnimInfo.CurrentFrame = 1; monster._mFlags |= MFLAG_ALLOW_SPECIAL; monster._mmode = MM_SATTACK; } if (sgGameInitInfo.nDifficulty == DIFF_NIGHTMARE) { monster._mmaxhp = 3 * monster._mmaxhp; if (gbIsHellfire) monster._mmaxhp += (gbIsMultiplayer ? 100 : 50) << 6; else monster._mmaxhp += 64; monster._mhitpoints = monster._mmaxhp; monster.mLevel += 15; monster.mExp = 2 * (monster.mExp + 1000); monster.mHit += NIGHTMARE_TO_HIT_BONUS; monster.mMinDamage = 2 * (monster.mMinDamage + 2); monster.mMaxDamage = 2 * (monster.mMaxDamage + 2); monster.mHit2 += NIGHTMARE_TO_HIT_BONUS; monster.mMinDamage2 = 2 * (monster.mMinDamage2 + 2); monster.mMaxDamage2 = 2 * (monster.mMaxDamage2 + 2); monster.mArmorClass += NIGHTMARE_AC_BONUS; } else if (sgGameInitInfo.nDifficulty == DIFF_HELL) { monster._mmaxhp = 4 * monster._mmaxhp; if (gbIsHellfire) monster._mmaxhp += (gbIsMultiplayer ? 200 : 100) << 6; else monster._mmaxhp += 192; monster._mhitpoints = monster._mmaxhp; monster.mLevel += 30; monster.mExp = 4 * (monster.mExp + 1000); monster.mHit += HELL_TO_HIT_BONUS; monster.mMinDamage = 4 * monster.mMinDamage + 6; monster.mMaxDamage = 4 * monster.mMaxDamage + 6; monster.mHit2 += HELL_TO_HIT_BONUS; monster.mMinDamage2 = 4 * monster.mMinDamage2 + 6; monster.mMaxDamage2 = 4 * monster.mMaxDamage2 + 6; monster.mArmorClass += HELL_AC_BONUS; monster.mMagicRes = monsterType.MData->mMagicRes2; } } bool CanPlaceMonster(int xp, int yp) { char f; if (xp < 0 || xp >= MAXDUNX || yp < 0 || yp >= MAXDUNY || dMonster[xp][yp] != 0 || dPlayer[xp][yp] != 0) { return false; } f = dFlags[xp][yp]; if ((f & BFLAG_VISIBLE) != 0) { return false; } if ((f & BFLAG_POPULATED) != 0) { return false; } return !IsTileSolid({ xp, yp }); } void PlaceMonster(int i, int mtype, int x, int y) { if (LevelMonsterTypes[mtype].mtype == MT_NAKRUL) { for (int j = 0; j < ActiveMonsterCount; j++) { if (Monsters[j]._mMTidx == mtype) { return; } if (Monsters[j].MType->mtype == MT_NAKRUL) { return; } } } dMonster[x][y] = i + 1; auto rd = static_cast<Direction>(GenerateRnd(8)); InitMonster(Monsters[i], rd, mtype, { x, y }); } void PlaceGroup(int mtype, int num, UniqueMonsterPack uniqueMonsterPack, int leaderId) { int placed = 0; auto &leader = Monsters[leaderId]; for (int try1 = 0; try1 < 10; try1++) { while (placed != 0) { ActiveMonsterCount--; placed--; const auto &position = Monsters[ActiveMonsterCount].position.tile; dMonster[position.x][position.y] = 0; } int xp; int yp; if (uniqueMonsterPack != UniqueMonsterPack::None) { int offset = GenerateRnd(8); auto position = leader.position.tile + static_cast<Direction>(offset); xp = position.x; yp = position.y; } else { do { xp = GenerateRnd(80) + 16; yp = GenerateRnd(80) + 16; } while (!CanPlaceMonster(xp, yp)); } int x1 = xp; int y1 = yp; if (num + ActiveMonsterCount > totalmonsters) { num = totalmonsters - ActiveMonsterCount; } int j = 0; for (int try2 = 0; j < num && try2 < 100; xp += Displacement::fromDirection(static_cast<Direction>(GenerateRnd(8))).deltaX, yp += Displacement::fromDirection(static_cast<Direction>(GenerateRnd(8))).deltaX) { /// BUGFIX: `yp += Point.y` if (!CanPlaceMonster(xp, yp) || (dTransVal[xp][yp] != dTransVal[x1][y1]) || (uniqueMonsterPack == UniqueMonsterPack::Leashed && (abs(xp - x1) >= 4 || abs(yp - y1) >= 4))) { try2++; continue; } PlaceMonster(ActiveMonsterCount, mtype, xp, yp); if (uniqueMonsterPack != UniqueMonsterPack::None) { auto &minion = Monsters[ActiveMonsterCount]; minion._mmaxhp *= 2; minion._mhitpoints = minion._mmaxhp; minion._mint = leader._mint; if (uniqueMonsterPack == UniqueMonsterPack::Leashed) { minion.leader = leaderId; minion.leaderRelation = LeaderRelation::Leashed; minion._mAi = leader._mAi; } if (minion._mAi != AI_GARG) { minion.AnimInfo.pCelSprite = &*minion.MType->GetAnimData(MonsterGraphic::Stand).CelSpritesForDirections[minion._mdir]; minion.AnimInfo.CurrentFrame = GenerateRnd(minion.AnimInfo.NumberOfFrames - 1) + 1; minion._mFlags &= ~MFLAG_ALLOW_SPECIAL; minion._mmode = MM_STAND; } } ActiveMonsterCount++; placed++; j++; } if (placed >= num) { break; } } if (uniqueMonsterPack == UniqueMonsterPack::Leashed) { leader.packsize = placed; } } void PlaceUniqueMonst(int uniqindex, int miniontype, int bosspacksize) { auto &monster = Monsters[ActiveMonsterCount]; const auto &uniqueData = UniqMonst[uniqindex]; if ((uniquetrans + 19) * 256 >= LIGHTSIZE) { return; } int uniqtype; for (uniqtype = 0; uniqtype < LevelMonsterTypeCount; uniqtype++) { if (LevelMonsterTypes[uniqtype].mtype == uniqueData.mtype) { break; } } int count = 0; int xp; int yp; while (true) { xp = GenerateRnd(80) + 16; yp = GenerateRnd(80) + 16; int count2 = 0; for (int x = xp - 3; x < xp + 3; x++) { for (int y = yp - 3; y < yp + 3; y++) { if (y >= 0 && y < MAXDUNY && x >= 0 && x < MAXDUNX && CanPlaceMonster(x, y)) { count2++; } } } if (count2 < 9) { count++; if (count < 1000) { continue; } } if (CanPlaceMonster(xp, yp)) { break; } } if (uniqindex == UMT_SNOTSPIL) { xp = 2 * setpc_x + 24; yp = 2 * setpc_y + 28; } if (uniqindex == UMT_WARLORD) { xp = 2 * setpc_x + 22; yp = 2 * setpc_y + 23; } if (uniqindex == UMT_ZHAR) { for (int i = 0; i < themeCount; i++) { if (i == zharlib) { xp = 2 * themeLoc[i].x + 20; yp = 2 * themeLoc[i].y + 20; break; } } } if (!gbIsMultiplayer) { if (uniqindex == UMT_LAZARUS) { xp = 32; yp = 46; } if (uniqindex == UMT_RED_VEX) { xp = 40; yp = 45; } if (uniqindex == UMT_BLACKJADE) { xp = 38; yp = 49; } if (uniqindex == UMT_SKELKING) { xp = 35; yp = 47; } } else { if (uniqindex == UMT_LAZARUS) { xp = 2 * setpc_x + 19; yp = 2 * setpc_y + 22; } if (uniqindex == UMT_RED_VEX) { xp = 2 * setpc_x + 21; yp = 2 * setpc_y + 19; } if (uniqindex == UMT_BLACKJADE) { xp = 2 * setpc_x + 21; yp = 2 * setpc_y + 25; } } if (uniqindex == UMT_BUTCHER) { bool done = false; for (yp = 0; yp < MAXDUNY && !done; yp++) { for (xp = 0; xp < MAXDUNX && !done; xp++) { done = dPiece[xp][yp] == 367; } } } if (uniqindex == UMT_NAKRUL) { if (UberRow == 0 || UberCol == 0) { UberDiabloMonsterIndex = -1; return; } xp = UberRow - 2; yp = UberCol; UberDiabloMonsterIndex = ActiveMonsterCount; } PlaceMonster(ActiveMonsterCount, uniqtype, xp, yp); monster._uniqtype = uniqindex + 1; if (uniqueData.mlevel != 0) { monster.mLevel = 2 * uniqueData.mlevel; } else { monster.mLevel += 5; } monster.mExp *= 2; monster.mName = _(uniqueData.mName); monster._mmaxhp = uniqueData.mmaxhp << 6; if (!gbIsMultiplayer) monster._mmaxhp = std::max(monster._mmaxhp / 2, 64); monster._mhitpoints = monster._mmaxhp; monster._mAi = uniqueData.mAi; monster._mint = uniqueData.mint; monster.mMinDamage = uniqueData.mMinDamage; monster.mMaxDamage = uniqueData.mMaxDamage; monster.mMinDamage2 = uniqueData.mMinDamage; monster.mMaxDamage2 = uniqueData.mMaxDamage; monster.mMagicRes = uniqueData.mMagicRes; monster.mtalkmsg = uniqueData.mtalkmsg; if (uniqindex == UMT_HORKDMN) monster.mlid = NO_LIGHT; // BUGFIX monsters initial light id should be -1 (fixed) else monster.mlid = AddLight(monster.position.tile, 3); if (gbIsMultiplayer) { if (monster._mAi == AI_LAZHELP) monster.mtalkmsg = TEXT_NONE; if (monster._mAi == AI_LAZARUS && Quests[Q_BETRAYER]._qvar1 > 3) { monster._mgoal = MGOAL_NORMAL; } else if (monster.mtalkmsg != TEXT_NONE) { monster._mgoal = MGOAL_INQUIRING; } } else if (monster.mtalkmsg != TEXT_NONE) { monster._mgoal = MGOAL_INQUIRING; } if (sgGameInitInfo.nDifficulty == DIFF_NIGHTMARE) { monster._mmaxhp = 3 * monster._mmaxhp; if (gbIsHellfire) monster._mmaxhp += (gbIsMultiplayer ? 100 : 50) << 6; else monster._mmaxhp += 64; monster.mLevel += 15; monster._mhitpoints = monster._mmaxhp; monster.mExp = 2 * (monster.mExp + 1000); monster.mMinDamage = 2 * (monster.mMinDamage + 2); monster.mMaxDamage = 2 * (monster.mMaxDamage + 2); monster.mMinDamage2 = 2 * (monster.mMinDamage2 + 2); monster.mMaxDamage2 = 2 * (monster.mMaxDamage2 + 2); } else if (sgGameInitInfo.nDifficulty == DIFF_HELL) { monster._mmaxhp = 4 * monster._mmaxhp; if (gbIsHellfire) monster._mmaxhp += (gbIsMultiplayer ? 200 : 100) << 6; else monster._mmaxhp += 192; monster.mLevel += 30; monster._mhitpoints = monster._mmaxhp; monster.mExp = 4 * (monster.mExp + 1000); monster.mMinDamage = 4 * monster.mMinDamage + 6; monster.mMaxDamage = 4 * monster.mMaxDamage + 6; monster.mMinDamage2 = 4 * monster.mMinDamage2 + 6; monster.mMaxDamage2 = 4 * monster.mMaxDamage2 + 6; } char filestr[64]; sprintf(filestr, "Monsters\\Monsters\\%s.TRN", uniqueData.mTrnName); LoadFileInMem(filestr, &LightTables[256 * (uniquetrans + 19)], 256); monster._uniqtrans = uniquetrans++; if (uniqueData.customHitpoints != 0) { monster.mHit = uniqueData.customHitpoints; monster.mHit2 = uniqueData.customHitpoints; if (sgGameInitInfo.nDifficulty == DIFF_NIGHTMARE) { monster.mHit += NIGHTMARE_TO_HIT_BONUS; monster.mHit2 += NIGHTMARE_TO_HIT_BONUS; } else if (sgGameInitInfo.nDifficulty == DIFF_HELL) { monster.mHit += HELL_TO_HIT_BONUS; monster.mHit2 += HELL_TO_HIT_BONUS; } } if (uniqueData.customArmorClass != 0) { monster.mArmorClass = uniqueData.customArmorClass; if (sgGameInitInfo.nDifficulty == DIFF_NIGHTMARE) { monster.mArmorClass += NIGHTMARE_AC_BONUS; } else if (sgGameInitInfo.nDifficulty == DIFF_HELL) { monster.mArmorClass += HELL_AC_BONUS; } } ActiveMonsterCount++; if (uniqueData.monsterPack != UniqueMonsterPack::None) { PlaceGroup(miniontype, bosspacksize, uniqueData.monsterPack, ActiveMonsterCount - 1); } if (monster._mAi != AI_GARG) { monster.AnimInfo.pCelSprite = &*monster.MType->GetAnimData(MonsterGraphic::Stand).CelSpritesForDirections[monster._mdir]; monster.AnimInfo.CurrentFrame = GenerateRnd(monster.AnimInfo.NumberOfFrames - 1) + 1; monster._mFlags &= ~MFLAG_ALLOW_SPECIAL; monster._mmode = MM_STAND; } } int AddMonsterType(_monster_id type, placeflag placeflag) { bool done = false; int i; for (i = 0; i < LevelMonsterTypeCount && !done; i++) { done = LevelMonsterTypes[i].mtype == type; } i--; if (!done) { i = LevelMonsterTypeCount; LevelMonsterTypeCount++; LevelMonsterTypes[i].mtype = type; monstimgtot += MonsterData[type].mImage; InitMonsterGFX(i); InitMonsterSND(i); } LevelMonsterTypes[i].mPlaceFlags |= placeflag; return i; } void ClearMVars(MonsterStruct &monster) { monster._mVar1 = 0; monster._mVar2 = 0; monster._mVar3 = 0; monster.position.temp = { 0, 0 }; monster.position.offset2 = { 0, 0 }; } void ClrAllMonsters() { for (auto &monster : Monsters) { ClearMVars(monster); monster.mName = "Invalid Monster"; monster._mgoal = MGOAL_NONE; monster._mmode = MM_STAND; monster._mVar1 = 0; monster._mVar2 = 0; monster.position.tile = { 0, 0 }; monster.position.future = { 0, 0 }; monster.position.old = { 0, 0 }; monster._mdir = static_cast<Direction>(GenerateRnd(8)); monster.position.velocity = { 0, 0 }; monster.AnimInfo = {}; monster._mFlags = 0; monster._mDelFlag = false; monster._menemy = GenerateRnd(gbActivePlayers); monster.enemyPosition = Players[monster._menemy].position.future; } } void PlaceUniqueMonsters() { for (int u = 0; UniqMonst[u].mtype != -1; u++) { if (UniqMonst[u].mlevel != currlevel) continue; bool done = false; int mt; for (mt = 0; mt < LevelMonsterTypeCount; mt++) { done = (LevelMonsterTypes[mt].mtype == UniqMonst[u].mtype); if (done) break; } if (u == UMT_GARBUD && Quests[Q_GARBUD]._qactive == QUEST_NOTAVAIL) done = false; if (u == UMT_ZHAR && Quests[Q_ZHAR]._qactive == QUEST_NOTAVAIL) done = false; if (u == UMT_SNOTSPIL && Quests[Q_LTBANNER]._qactive == QUEST_NOTAVAIL) done = false; if (u == UMT_LACHDAN && Quests[Q_VEIL]._qactive == QUEST_NOTAVAIL) done = false; if (u == UMT_WARLORD && Quests[Q_WARLORD]._qactive == QUEST_NOTAVAIL) done = false; if (done) PlaceUniqueMonst(u, mt, 8); } } void PlaceQuestMonsters() { int skeltype; if (!setlevel) { if (Quests[Q_BUTCHER].IsAvailable()) { PlaceUniqueMonst(UMT_BUTCHER, 0, 0); } if (currlevel == Quests[Q_SKELKING]._qlevel && gbIsMultiplayer) { skeltype = 0; for (skeltype = 0; skeltype < LevelMonsterTypeCount; skeltype++) { if (IsSkel(LevelMonsterTypes[skeltype].mtype)) { break; } } PlaceUniqueMonst(UMT_SKELKING, skeltype, 30); } if (Quests[Q_LTBANNER].IsAvailable()) { auto dunData = LoadFileInMem<uint16_t>("Levels\\L1Data\\Banner1.DUN"); SetMapMonsters(dunData.get(), Point { setpc_x, setpc_y } * 2); } if (Quests[Q_BLOOD].IsAvailable()) { auto dunData = LoadFileInMem<uint16_t>("Levels\\L2Data\\Blood2.DUN"); SetMapMonsters(dunData.get(), Point { setpc_x, setpc_y } * 2); } if (Quests[Q_BLIND].IsAvailable()) { auto dunData = LoadFileInMem<uint16_t>("Levels\\L2Data\\Blind2.DUN"); SetMapMonsters(dunData.get(), Point { setpc_x, setpc_y } * 2); } if (Quests[Q_ANVIL].IsAvailable()) { auto dunData = LoadFileInMem<uint16_t>("Levels\\L3Data\\Anvil.DUN"); SetMapMonsters(dunData.get(), Point { setpc_x + 2, setpc_y + 2 } * 2); } if (Quests[Q_WARLORD].IsAvailable()) { auto dunData = LoadFileInMem<uint16_t>("Levels\\L4Data\\Warlord.DUN"); SetMapMonsters(dunData.get(), Point { setpc_x, setpc_y } * 2); AddMonsterType(UniqMonst[UMT_WARLORD].mtype, PLACE_SCATTER); } if (Quests[Q_VEIL].IsAvailable()) { AddMonsterType(UniqMonst[UMT_LACHDAN].mtype, PLACE_SCATTER); } if (Quests[Q_ZHAR].IsAvailable() && zharlib == -1) { Quests[Q_ZHAR]._qactive = QUEST_NOTAVAIL; } if (currlevel == Quests[Q_BETRAYER]._qlevel && gbIsMultiplayer) { AddMonsterType(UniqMonst[UMT_LAZARUS].mtype, PLACE_UNIQUE); AddMonsterType(UniqMonst[UMT_RED_VEX].mtype, PLACE_UNIQUE); PlaceUniqueMonst(UMT_LAZARUS, 0, 0); PlaceUniqueMonst(UMT_RED_VEX, 0, 0); PlaceUniqueMonst(UMT_BLACKJADE, 0, 0); auto dunData = LoadFileInMem<uint16_t>("Levels\\L4Data\\Vile1.DUN"); SetMapMonsters(dunData.get(), Point { setpc_x, setpc_y } * 2); } if (currlevel == 24) { UberDiabloMonsterIndex = -1; int i1; for (i1 = 0; i1 < LevelMonsterTypeCount; i1++) { if (LevelMonsterTypes[i1].mtype == UniqMonst[UMT_NAKRUL].mtype) break; } if (i1 < LevelMonsterTypeCount) { for (int i2 = 0; i2 < ActiveMonsterCount; i2++) { auto &monster = Monsters[i2]; if (monster._uniqtype != 0 || monster._mMTidx == i1) { UberDiabloMonsterIndex = i2; break; } } } if (UberDiabloMonsterIndex == -1) PlaceUniqueMonst(UMT_NAKRUL, 0, 0); } } else if (setlvlnum == SL_SKELKING) { PlaceUniqueMonst(UMT_SKELKING, 0, 0); } } void LoadDiabMonsts() { { auto dunData = LoadFileInMem<uint16_t>("Levels\\L4Data\\diab1.DUN"); SetMapMonsters(dunData.get(), Point { diabquad1x, diabquad1y } * 2); } { auto dunData = LoadFileInMem<uint16_t>("Levels\\L4Data\\diab2a.DUN"); SetMapMonsters(dunData.get(), Point { diabquad2x, diabquad2y } * 2); } { auto dunData = LoadFileInMem<uint16_t>("Levels\\L4Data\\diab3a.DUN"); SetMapMonsters(dunData.get(), Point { diabquad3x, diabquad3y } * 2); } { auto dunData = LoadFileInMem<uint16_t>("Levels\\L4Data\\diab4a.DUN"); SetMapMonsters(dunData.get(), Point { diabquad4x, diabquad4y } * 2); } } void DeleteMonster(int i) { ActiveMonsterCount--; std::swap(ActiveMonsters[i], ActiveMonsters[ActiveMonsterCount]); // This ensures alive monsters are before ActiveMonsterCount in the array and any deleted monster after } void NewMonsterAnim(MonsterStruct &monster, MonsterGraphic graphic, Direction md, AnimationDistributionFlags flags = AnimationDistributionFlags::None, int numSkippedFrames = 0, int distributeFramesBeforeFrame = 0) { const auto &animData = monster.MType->GetAnimData(graphic); const auto *pCelSprite = &*animData.CelSpritesForDirections[md]; monster.AnimInfo.SetNewAnimation(pCelSprite, animData.Frames, animData.Rate, flags, numSkippedFrames, distributeFramesBeforeFrame); monster._mFlags &= ~(MFLAG_LOCK_ANIMATION | MFLAG_ALLOW_SPECIAL); monster._mdir = md; } void StartMonsterGotHit(int monsterId) { auto &monster = Monsters[monsterId]; if (monster.MType->mtype != MT_GOLEM) { auto animationFlags = gGameLogicStep < GameLogicStep::ProcessMonsters ? AnimationDistributionFlags::ProcessAnimationPending : AnimationDistributionFlags::None; int numSkippedFrames = (gbIsHellfire && monster.MType->mtype == MT_DIABLO) ? 4 : 0; NewMonsterAnim(monster, MonsterGraphic::GotHit, monster._mdir, animationFlags, numSkippedFrames); monster._mmode = MM_GOTHIT; } monster.position.offset = { 0, 0 }; monster.position.tile = monster.position.old; monster.position.future = monster.position.old; M_ClearSquares(monsterId); dMonster[monster.position.tile.x][monster.position.tile.y] = monsterId + 1; } bool IsRanged(MonsterStruct &monster) { return IsAnyOf(monster._mAi, AI_SKELBOW, AI_GOATBOW, AI_SUCC, AI_LAZHELP); } void UpdateEnemy(MonsterStruct &monster) { Point target; int menemy = -1; int bestDist = -1; bool bestsameroom = false; const auto &position = monster.position.tile; if ((monster._mFlags & MFLAG_BERSERK) != 0 || (monster._mFlags & MFLAG_GOLEM) == 0) { for (int pnum = 0; pnum < MAX_PLRS; pnum++) { auto &player = Players[pnum]; if (!player.plractive || currlevel != player.plrlevel || player._pLvlChanging || (((player._pHitPoints >> 6) == 0) && gbIsMultiplayer)) continue; bool sameroom = (dTransVal[position.x][position.y] == dTransVal[player.position.tile.x][player.position.tile.y]); int dist = position.WalkingDistance(player.position.tile); if ((sameroom && !bestsameroom) || ((sameroom || !bestsameroom) && dist < bestDist) || (menemy == -1)) { monster._mFlags &= ~MFLAG_TARGETS_MONSTER; menemy = pnum; target = player.position.future; bestDist = dist; bestsameroom = sameroom; } } } for (int j = 0; j < ActiveMonsterCount; j++) { int mi = ActiveMonsters[j]; auto &otherMonster = Monsters[mi]; if (&otherMonster == &monster) continue; if ((otherMonster._mhitpoints >> 6) <= 0) continue; if (otherMonster.position.tile == GolemHoldingCell) continue; if (M_Talker(otherMonster) && otherMonster.mtalkmsg != TEXT_NONE) continue; if ((monster._mFlags & MFLAG_GOLEM) != 0 && (otherMonster._mFlags & MFLAG_GOLEM) != 0) // prevent golems from fighting each other continue; int dist = otherMonster.position.tile.WalkingDistance(position); if (((monster._mFlags & MFLAG_GOLEM) == 0 && (monster._mFlags & MFLAG_BERSERK) == 0 && dist >= 2 && !IsRanged(monster)) || ((monster._mFlags & MFLAG_GOLEM) == 0 && (monster._mFlags & MFLAG_BERSERK) == 0 && (otherMonster._mFlags & MFLAG_GOLEM) == 0)) { continue; } bool sameroom = dTransVal[position.x][position.y] == dTransVal[otherMonster.position.tile.x][otherMonster.position.tile.y]; if ((sameroom && !bestsameroom) || ((sameroom || !bestsameroom) && dist < bestDist) || (menemy == -1)) { monster._mFlags |= MFLAG_TARGETS_MONSTER; menemy = mi; target = otherMonster.position.future; bestDist = dist; bestsameroom = sameroom; } } if (menemy != -1) { monster._mFlags &= ~MFLAG_NO_ENEMY; monster._menemy = menemy; monster.enemyPosition = target; } else { monster._mFlags |= MFLAG_NO_ENEMY; } } /** * @brief Make the AI wait a bit before thinking again * @param len */ void AiDelay(MonsterStruct &monster, int len) { if (len <= 0) { return; } if (monster._mAi == AI_LAZARUS) { return; } monster._mVar2 = len; monster._mmode = MM_DELAY; } /** * @brief Get the direction from the monster to its current enemy */ Direction GetMonsterDirection(MonsterStruct &monster) { return GetDirection(monster.position.tile, monster.enemyPosition); } void StartSpecialStand(MonsterStruct &monster, Direction md) { NewMonsterAnim(monster, MonsterGraphic::Special, md); monster._mmode = MM_SPSTAND; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; } void StartWalk(int i, int xvel, int yvel, int xadd, int yadd, Direction endDir) { auto &monster = Monsters[i]; int fx = xadd + monster.position.tile.x; int fy = yadd + monster.position.tile.y; dMonster[fx][fy] = -(i + 1); monster._mmode = MM_WALK; monster.position.old = monster.position.tile; monster.position.future = { fx, fy }; monster.position.velocity = { xvel, yvel }; monster._mVar1 = xadd; monster._mVar2 = yadd; monster._mVar3 = endDir; NewMonsterAnim(monster, MonsterGraphic::Walk, endDir, AnimationDistributionFlags::ProcessAnimationPending, -1); monster.position.offset2 = { 0, 0 }; } void StartWalk2(int i, int xvel, int yvel, int xoff, int yoff, int xadd, int yadd, Direction endDir) { auto &monster = Monsters[i]; int fx = xadd + monster.position.tile.x; int fy = yadd + monster.position.tile.y; dMonster[monster.position.tile.x][monster.position.tile.y] = -(i + 1); monster._mVar1 = monster.position.tile.x; monster._mVar2 = monster.position.tile.y; monster.position.old = monster.position.tile; monster.position.tile = { fx, fy }; monster.position.future = { fx, fy }; dMonster[fx][fy] = i + 1; if (monster.mlid != NO_LIGHT) ChangeLightXY(monster.mlid, monster.position.tile); monster.position.offset = { xoff, yoff }; monster._mmode = MM_WALK2; monster.position.velocity = { xvel, yvel }; monster._mVar3 = endDir; NewMonsterAnim(monster, MonsterGraphic::Walk, endDir, AnimationDistributionFlags::ProcessAnimationPending, -1); monster.position.offset2 = { 16 * xoff, 16 * yoff }; } void StartWalk3(int i, int xvel, int yvel, int xoff, int yoff, int xadd, int yadd, int mapx, int mapy, Direction endDir) { auto &monster = Monsters[i]; int fx = xadd + monster.position.tile.x; int fy = yadd + monster.position.tile.y; int x = mapx + monster.position.tile.x; int y = mapy + monster.position.tile.y; if (monster.mlid != NO_LIGHT) ChangeLightXY(monster.mlid, { x, y }); dMonster[monster.position.tile.x][monster.position.tile.y] = -(i + 1); dMonster[fx][fy] = -(i + 1); monster.position.temp = { x, y }; dFlags[x][y] |= BFLAG_MONSTLR; monster.position.old = monster.position.tile; monster.position.future = { fx, fy }; monster.position.offset = { xoff, yoff }; monster._mmode = MM_WALK3; monster.position.velocity = { xvel, yvel }; monster._mVar1 = fx; monster._mVar2 = fy; monster._mVar3 = endDir; NewMonsterAnim(monster, MonsterGraphic::Walk, endDir, AnimationDistributionFlags::ProcessAnimationPending, -1); monster.position.offset2 = { 16 * xoff, 16 * yoff }; } void StartAttack(MonsterStruct &monster) { Direction md = GetMonsterDirection(monster); NewMonsterAnim(monster, MonsterGraphic::Attack, md, AnimationDistributionFlags::ProcessAnimationPending); monster._mmode = MM_ATTACK; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; } void StartRangedAttack(MonsterStruct &monster, missile_id missileType, int dam) { Direction md = GetMonsterDirection(monster); NewMonsterAnim(monster, MonsterGraphic::Attack, md, AnimationDistributionFlags::ProcessAnimationPending); monster._mmode = MM_RATTACK; monster._mVar1 = missileType; monster._mVar2 = dam; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; } void StartRangedSpecialAttack(MonsterStruct &monster, missile_id missileType, int dam) { Direction md = GetMonsterDirection(monster); int distributeFramesBeforeFrame = 0; if (monster._mAi == AI_MEGA) distributeFramesBeforeFrame = monster.MData->mAFNum2; NewMonsterAnim(monster, MonsterGraphic::Special, md, AnimationDistributionFlags::ProcessAnimationPending, 0, distributeFramesBeforeFrame); monster._mmode = MM_RSPATTACK; monster._mVar1 = missileType; monster._mVar2 = 0; monster._mVar3 = dam; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; } void StartSpecialAttack(MonsterStruct &monster) { Direction md = GetMonsterDirection(monster); NewMonsterAnim(monster, MonsterGraphic::Special, md); monster._mmode = MM_SATTACK; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; } void StartEating(MonsterStruct &monster) { NewMonsterAnim(monster, MonsterGraphic::Special, monster._mdir); monster._mmode = MM_SATTACK; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; } void DiabloDeath(MonsterStruct &diablo, bool sendmsg) { PlaySFX(USFX_DIABLOD); Quests[Q_DIABLO]._qactive = QUEST_DONE; if (sendmsg) NetSendCmdQuest(true, Q_DIABLO); sgbSaveSoundOn = gbSoundOn; gbProcessPlayers = false; for (int j = 0; j < ActiveMonsterCount; j++) { int k = ActiveMonsters[j]; auto &monster = Monsters[k]; if (monster.MType->mtype == MT_DIABLO || diablo._msquelch == 0) continue; NewMonsterAnim(monster, MonsterGraphic::Death, monster._mdir); monster._mmode = MM_DEATH; monster.position.offset = { 0, 0 }; monster._mVar1 = 0; monster.position.tile = monster.position.old; monster.position.future = monster.position.tile; M_ClearSquares(k); dMonster[monster.position.tile.x][monster.position.tile.y] = k + 1; } AddLight(diablo.position.tile, 8); DoVision(diablo.position.tile, 8, false, true); int dist = diablo.position.tile.WalkingDistance({ ViewX, ViewY }); if (dist > 20) dist = 20; diablo._mVar3 = ViewX << 16; diablo.position.temp.x = ViewY << 16; diablo.position.temp.y = (int)((diablo._mVar3 - (diablo.position.tile.x << 16)) / (double)dist); diablo.position.offset2.deltaX = (int)((diablo.position.temp.x - (diablo.position.tile.y << 16)) / (double)dist); } void SpawnLoot(MonsterStruct &monster, bool sendmsg) { if (Quests[Q_GARBUD].IsAvailable() && monster._uniqtype - 1 == UMT_GARBUD) { CreateTypeItem(monster.position.tile + Displacement { 1, 1 }, true, ITYPE_MACE, IMISC_NONE, true, false); } else if (monster._uniqtype - 1 == UMT_DEFILER) { if (effect_is_playing(USFX_DEFILER8)) stream_stop(); Quests[Q_DEFILER]._qlog = false; SpawnMapOfDoom(monster.position.tile); } else if (monster._uniqtype - 1 == UMT_HORKDMN) { if (sgGameInitInfo.bTheoQuest != 0) { SpawnTheodore(monster.position.tile); } else { CreateAmulet(monster.position.tile, 13, false, true); } } else if (monster.MType->mtype == MT_HORKSPWN) { } else if (monster.MType->mtype == MT_NAKRUL) { int nSFX = IsUberRoomOpened ? USFX_NAKRUL4 : USFX_NAKRUL5; if (sgGameInitInfo.bCowQuest != 0) nSFX = USFX_NAKRUL6; if (effect_is_playing(nSFX)) stream_stop(); Quests[Q_NAKRUL]._qlog = false; UberDiabloMonsterIndex = -2; CreateMagicWeapon(monster.position.tile, ITYPE_SWORD, ICURS_GREAT_SWORD, false, true); CreateMagicWeapon(monster.position.tile, ITYPE_STAFF, ICURS_WAR_STAFF, false, true); CreateMagicWeapon(monster.position.tile, ITYPE_BOW, ICURS_LONG_WAR_BOW, false, true); CreateSpellBook(monster.position.tile, SPL_APOCA, false, true); } else if (monster.MType->mtype != MT_GOLEM) { SpawnItem(monster, monster.position.tile, sendmsg); } } void Teleport(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode == MM_STONE) return; int mx = monster.enemyPosition.x; int my = monster.enemyPosition.y; int rx = 2 * GenerateRnd(2) - 1; int ry = 2 * GenerateRnd(2) - 1; bool done = false; int x; int y; for (int j = -1; j <= 1 && !done; j++) { for (int k = -1; k < 1 && !done; k++) { if (j != 0 || k != 0) { x = mx + rx * j; y = my + ry * k; if (y >= 0 && y < MAXDUNY && x >= 0 && x < MAXDUNX && x != monster.position.tile.x && y != monster.position.tile.y) { if (IsTileAvailable(monster, { x, y })) done = true; } } } } if (done) { M_ClearSquares(i); dMonster[monster.position.tile.x][monster.position.tile.y] = 0; dMonster[x][y] = i + 1; monster.position.old = { x, y }; monster._mdir = GetMonsterDirection(monster); if (monster.mlid != NO_LIGHT) { ChangeLightXY(monster.mlid, { x, y }); } } } void MonsterHitMonster(int mid, int i, int dam) { assert(mid >= 0 && mid < MAXMONSTERS); auto &monster = Monsters[mid]; assert(monster.MType != nullptr); if (i >= 0 && i < MAX_PLRS) monster.mWhoHit |= 1 << i; delta_monster_hp(mid, monster._mhitpoints, currlevel); NetSendCmdMonDmg(false, mid, dam); PlayEffect(monster, 1); if ((monster.MType->mtype >= MT_SNEAK && monster.MType->mtype <= MT_ILLWEAV) || dam >> 6 >= monster.mLevel + 3) { if (i >= 0) monster._mdir = opposite[Monsters[i]._mdir]; if (monster.MType->mtype == MT_BLINK) { Teleport(mid); } else if ((monster.MType->mtype >= MT_NSCAV && monster.MType->mtype <= MT_YSCAV) || monster.MType->mtype == MT_GRAVEDIG) { monster._mgoal = MGOAL_NORMAL; monster._mgoalvar1 = 0; monster._mgoalvar2 = 0; } if (monster._mmode != MM_STONE) { StartMonsterGotHit(mid); } } } void StartMonsterDeath(int i, int pnum, bool sendmsg) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; assert(monster.MType != nullptr); if (pnum >= 0) monster.mWhoHit |= 1 << pnum; if (pnum < MAX_PLRS && i >= MAX_PLRS) /// BUGFIX: i >= MAX_PLRS (fixed) AddPlrMonstExper(monster.mLevel, monster.mExp, monster.mWhoHit); MonsterKillCounts[monster.MType->mtype]++; monster._mhitpoints = 0; SetRndSeed(monster._mRndSeed); SpawnLoot(monster, sendmsg); if (monster.MType->mtype == MT_DIABLO) DiabloDeath(monster, true); else PlayEffect(monster, 2); Direction md = pnum >= 0 ? GetMonsterDirection(monster) : monster._mdir; NewMonsterAnim(monster, MonsterGraphic::Death, md, gGameLogicStep < GameLogicStep::ProcessMonsters ? AnimationDistributionFlags::ProcessAnimationPending : AnimationDistributionFlags::None); monster._mmode = MM_DEATH; monster._mgoal = MGOAL_NONE; monster.position.offset = { 0, 0 }; monster._mVar1 = 0; monster.position.tile = monster.position.old; monster.position.future = monster.position.old; M_ClearSquares(i); dMonster[monster.position.tile.x][monster.position.tile.y] = i + 1; CheckQuestKill(monster, sendmsg); M_FallenFear(monster.position.tile); if ((monster.MType->mtype >= MT_NACID && monster.MType->mtype <= MT_XACID) || monster.MType->mtype == MT_SPIDLORD) AddMissile(monster.position.tile, { 0, 0 }, 0, MIS_ACIDPUD, TARGET_PLAYERS, i, monster._mint + 1, 0); } void StartDeathFromMonster(int i, int mid) { assert(i >= 0 && i < MAXMONSTERS); auto &killer = Monsters[i]; assert(mid >= 0 && mid < MAXMONSTERS); auto &monster = Monsters[mid]; assert(monster.MType != nullptr); delta_kill_monster(mid, monster.position.tile, currlevel); NetSendCmdLocParam1(false, CMD_MONSTDEATH, monster.position.tile, mid); if (i < MAX_PLRS) { monster.mWhoHit |= 1 << i; if (mid >= MAX_PLRS) AddPlrMonstExper(monster.mLevel, monster.mExp, monster.mWhoHit); } MonsterKillCounts[monster.MType->mtype]++; monster._mhitpoints = 0; SetRndSeed(monster._mRndSeed); SpawnLoot(monster, true); if (monster.MType->mtype == MT_DIABLO) DiabloDeath(monster, true); else PlayEffect(monster, 2); Direction md = opposite[killer._mdir]; if (monster.MType->mtype == MT_GOLEM) md = DIR_S; NewMonsterAnim(monster, MonsterGraphic::Death, md, gGameLogicStep < GameLogicStep::ProcessMonsters ? AnimationDistributionFlags::ProcessAnimationPending : AnimationDistributionFlags::None); monster._mmode = MM_DEATH; monster.position.offset = { 0, 0 }; monster.position.tile = monster.position.old; monster.position.future = monster.position.old; M_ClearSquares(mid); dMonster[monster.position.tile.x][monster.position.tile.y] = mid + 1; CheckQuestKill(monster, true); M_FallenFear(monster.position.tile); if (monster.MType->mtype >= MT_NACID && monster.MType->mtype <= MT_XACID) AddMissile(monster.position.tile, { 0, 0 }, 0, MIS_ACIDPUD, TARGET_PLAYERS, mid, monster._mint + 1, 0); if (gbIsHellfire) M_StartStand(killer, killer._mdir); } void StartFadein(MonsterStruct &monster, Direction md, bool backwards) { NewMonsterAnim(monster, MonsterGraphic::Special, md); monster._mmode = MM_FADEIN; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; monster._mFlags &= ~MFLAG_HIDDEN; if (backwards) { monster._mFlags |= MFLAG_LOCK_ANIMATION; monster.AnimInfo.CurrentFrame = monster.AnimInfo.NumberOfFrames; } } void StartFadeout(MonsterStruct &monster, Direction md, bool backwards) { NewMonsterAnim(monster, MonsterGraphic::Special, md); monster._mmode = MM_FADEOUT; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; if (backwards) { monster._mFlags |= MFLAG_LOCK_ANIMATION; monster.AnimInfo.CurrentFrame = monster.AnimInfo.NumberOfFrames; } } void StartHeal(MonsterStruct &monster) { monster.AnimInfo.pCelSprite = &*monster.MType->GetAnimData(MonsterGraphic::Special).CelSpritesForDirections[monster._mdir]; monster.AnimInfo.CurrentFrame = monster.MType->GetAnimData(MonsterGraphic::Special).Frames; monster._mFlags |= MFLAG_LOCK_ANIMATION; monster._mmode = MM_HEAL; monster._mVar1 = monster._mmaxhp / (16 * (GenerateRnd(5) + 4)); } void SyncLightPosition(MonsterStruct &monster) { int lx = (monster.position.offset.deltaX + 2 * monster.position.offset.deltaY) / 8; int ly = (2 * monster.position.offset.deltaY - monster.position.offset.deltaX) / 8; if (monster.mlid != NO_LIGHT) ChangeLightOffset(monster.mlid, { lx, ly }); } bool MonsterIdle(MonsterStruct &monster) { if (monster.MType->mtype == MT_GOLEM) monster.AnimInfo.pCelSprite = &*monster.MType->GetAnimData(MonsterGraphic::Walk).CelSpritesForDirections[monster._mdir]; else monster.AnimInfo.pCelSprite = &*monster.MType->GetAnimData(MonsterGraphic::Stand).CelSpritesForDirections[monster._mdir]; if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) UpdateEnemy(monster); monster._mVar2++; return false; } /** * @brief Continue movement towards new tile */ bool MonsterWalk(int i, int variant) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; assert(monster.MType != nullptr); //Check if we reached new tile bool isAnimationEnd = monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames; if (isAnimationEnd) { switch (variant) { case MM_WALK: dMonster[monster.position.tile.x][monster.position.tile.y] = 0; monster.position.tile.x += monster._mVar1; monster.position.tile.y += monster._mVar2; dMonster[monster.position.tile.x][monster.position.tile.y] = i + 1; break; case MM_WALK2: dMonster[monster._mVar1][monster._mVar2] = 0; break; case MM_WALK3: dMonster[monster.position.tile.x][monster.position.tile.y] = 0; monster.position.tile = { monster._mVar1, monster._mVar2 }; dFlags[monster.position.temp.x][monster.position.temp.y] &= ~BFLAG_MONSTLR; dMonster[monster.position.tile.x][monster.position.tile.y] = i + 1; break; } if (monster.mlid != NO_LIGHT) ChangeLightXY(monster.mlid, monster.position.tile); M_StartStand(monster, monster._mdir); } else { //We didn't reach new tile so update monster's "sub-tile" position if (monster.AnimInfo.TickCounterOfCurrentFrame == 0) { if (monster.AnimInfo.CurrentFrame == 0 && monster.MType->mtype == MT_FLESTHNG) PlayEffect(monster, 3); monster.position.offset2 += monster.position.velocity; monster.position.offset.deltaX = monster.position.offset2.deltaX >> 4; monster.position.offset.deltaY = monster.position.offset2.deltaY >> 4; } } if (monster.mlid != NO_LIGHT) // BUGFIX: change uniqtype check to mlid check like it is in all other places (fixed) SyncLightPosition(monster); return isAnimationEnd; } void MonsterAttackMonster(int i, int mid, int hper, int mind, int maxd) { assert(mid >= 0 && mid < MAXMONSTERS); auto &monster = Monsters[mid]; assert(monster.MType != nullptr); if (monster._mhitpoints >> 6 > 0 && (monster.MType->mtype != MT_ILLWEAV || monster._mgoal != MGOAL_RETREAT)) { int hit = GenerateRnd(100); if (monster._mmode == MM_STONE) hit = 0; bool unused; if (!CheckMonsterHit(monster, &unused) && hit < hper) { int dam = (mind + GenerateRnd(maxd - mind + 1)) << 6; monster._mhitpoints -= dam; if (monster._mhitpoints >> 6 <= 0) { if (monster._mmode == MM_STONE) { StartDeathFromMonster(i, mid); monster.Petrify(); } else { StartDeathFromMonster(i, mid); } } else { if (monster._mmode == MM_STONE) { MonsterHitMonster(mid, i, dam); monster.Petrify(); } else { MonsterHitMonster(mid, i, dam); } } } } } void MonsterAttackPlayer(int i, int pnum, int hit, int minDam, int maxDam) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; assert(monster.MType != nullptr); auto &player = Players[pnum]; if ((monster._mFlags & MFLAG_TARGETS_MONSTER) != 0) { MonsterAttackMonster(i, pnum, hit, minDam, maxDam); return; } if (player._pHitPoints >> 6 <= 0 || player._pInvincible || (player._pSpellFlags & 1) != 0) return; if (monster.position.tile.WalkingDistance(player.position.tile) >= 2) return; int hper = GenerateRnd(100); #ifdef _DEBUG if (debug_mode_dollar_sign || debug_mode_key_inverted_v) hper = 1000; #endif int ac = player.GetArmor(); if ((player.pDamAcFlags & ISPLHF_ACDEMON) != 0 && monster.MData->mMonstClass == MC_DEMON) ac += 40; if ((player.pDamAcFlags & ISPLHF_ACUNDEAD) != 0 && monster.MData->mMonstClass == MC_UNDEAD) ac += 20; hit += 2 * (monster.mLevel - player._pLevel) + 30 - ac; int minhit = 15; if (currlevel == 14) minhit = 20; if (currlevel == 15) minhit = 25; if (currlevel == 16) minhit = 30; hit = std::max(hit, minhit); int blkper = 100; if ((player._pmode == PM_STAND || player._pmode == PM_ATTACK) && player._pBlockFlag) { blkper = GenerateRnd(100); } int blk = player.GetBlockChance() - (monster.mLevel * 2); blk = clamp(blk, 0, 100); if (hper >= hit) return; if (blkper < blk) { Direction dir = GetDirection(player.position.tile, monster.position.tile); StartPlrBlock(pnum, dir); if (pnum == MyPlayerId && player.wReflections > 0) { player.wReflections--; int dam = GenerateRnd((maxDam - minDam + 1) << 6) + (minDam << 6); dam = std::max(dam + (player._pIGetHit << 6), 64); int mdam = dam * (GenerateRnd(10) + 20L) / 100; monster._mhitpoints -= mdam; dam = std::max(dam - mdam, 0); if (monster._mhitpoints >> 6 <= 0) M_StartKill(i, pnum); else M_StartHit(i, pnum, mdam); } return; } if (monster.MType->mtype == MT_YZOMBIE && pnum == MyPlayerId) { int currentMissileId = -1; for (int j = 0; j < ActiveMissileCount; j++) { int mi = ActiveMissiles[j]; auto &missile = Missiles[mi]; if (missile._mitype != MIS_MANASHIELD) continue; if (missile._misource == pnum) currentMissileId = mi; } if (player._pMaxHP > 64) { if (player._pMaxHPBase > 64) { player._pMaxHP -= 64; if (player._pHitPoints > player._pMaxHP) { player._pHitPoints = player._pMaxHP; if (currentMissileId >= 0) Missiles[currentMissileId]._miVar1 = player._pHitPoints; } player._pMaxHPBase -= 64; if (player._pHPBase > player._pMaxHPBase) { player._pHPBase = player._pMaxHPBase; if (currentMissileId >= 0) Missiles[currentMissileId]._miVar2 = player._pHPBase; } } } } int dam = (minDam << 6) + GenerateRnd((maxDam - minDam + 1) << 6); dam = std::max(dam + (player._pIGetHit << 6), 64); if (pnum == MyPlayerId) { if (player.wReflections > 0) { player.wReflections--; int mdam = dam * (GenerateRnd(10) + 20L) / 100; monster._mhitpoints -= mdam; dam = std::max(dam - mdam, 0); if (monster._mhitpoints >> 6 <= 0) M_StartKill(i, pnum); else M_StartHit(i, pnum, mdam); } ApplyPlrDamage(pnum, 0, 0, dam); } if ((player._pIFlags & ISPL_THORNS) != 0) { int mdam = (GenerateRnd(3) + 1) << 6; monster._mhitpoints -= mdam; if (monster._mhitpoints >> 6 <= 0) M_StartKill(i, pnum); else M_StartHit(i, pnum, mdam); } if ((monster._mFlags & MFLAG_NOLIFESTEAL) == 0 && monster.MType->mtype == MT_SKING && gbIsMultiplayer) monster._mhitpoints += dam; if (player._pHitPoints >> 6 <= 0) { if (gbIsHellfire) M_StartStand(monster, monster._mdir); return; } StartPlrHit(pnum, dam, false); if ((monster._mFlags & MFLAG_KNOCKBACK) != 0) { if (player._pmode != PM_GOTHIT) StartPlrHit(pnum, 0, true); Point newPosition = player.position.tile + monster._mdir; if (PosOkPlayer(player, newPosition)) { player.position.tile = newPosition; FixPlayerLocation(pnum, player._pdir); FixPlrWalkTags(pnum); dPlayer[newPosition.x][newPosition.y] = pnum + 1; SetPlayerOld(player); } } } bool MonsterAttack(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; assert(monster.MType != nullptr); assert(monster.MData != nullptr); if (monster.AnimInfo.CurrentFrame == monster.MData->mAFNum) { MonsterAttackPlayer(i, monster._menemy, monster.mHit, monster.mMinDamage, monster.mMaxDamage); if (monster._mAi != AI_SNAKE) PlayEffect(monster, 0); } if (monster.MType->mtype >= MT_NMAGMA && monster.MType->mtype <= MT_WMAGMA && monster.AnimInfo.CurrentFrame == 9) { MonsterAttackPlayer(i, monster._menemy, monster.mHit + 10, monster.mMinDamage - 2, monster.mMaxDamage - 2); PlayEffect(monster, 0); } if (monster.MType->mtype >= MT_STORM && monster.MType->mtype <= MT_MAEL && monster.AnimInfo.CurrentFrame == 13) { MonsterAttackPlayer(i, monster._menemy, monster.mHit - 20, monster.mMinDamage + 4, monster.mMaxDamage + 4); PlayEffect(monster, 0); } if (monster._mAi == AI_SNAKE && monster.AnimInfo.CurrentFrame == 1) PlayEffect(monster, 0); if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) { M_StartStand(monster, monster._mdir); return true; } return false; } bool MonaterRangedAttack(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; assert(monster.MType != nullptr); assert(monster.MData != nullptr); if (monster.AnimInfo.CurrentFrame == monster.MData->mAFNum) { if (monster._mVar1 != -1) { int multimissiles = 1; if (monster._mVar1 == MIS_CBOLT) multimissiles = 3; for (int mi = 0; mi < multimissiles; mi++) { Point sourcePosition = monster.position.tile; if (gbIsHellfire) { sourcePosition += monster._mdir; } AddMissile( sourcePosition, monster.enemyPosition, monster._mdir, monster._mVar1, TARGET_PLAYERS, i, monster._mVar2, 0); } } PlayEffect(monster, 0); } if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) { M_StartStand(monster, monster._mdir); return true; } return false; } bool MonsterRangedSpecialAttack(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; assert(monster.MType != nullptr); assert(monster.MData != nullptr); if (monster.AnimInfo.CurrentFrame == monster.MData->mAFNum2 && monster.AnimInfo.TickCounterOfCurrentFrame == 0) { Point sourcePosition = monster.position.tile; if (gbIsHellfire) { sourcePosition += monster._mdir; } AddMissile( sourcePosition, monster.enemyPosition, monster._mdir, monster._mVar1, TARGET_PLAYERS, i, monster._mVar3, 0); PlayEffect(monster, 3); } if (monster._mAi == AI_MEGA && monster.AnimInfo.CurrentFrame == monster.MData->mAFNum2) { if (monster._mVar2++ == 0) { monster._mFlags |= MFLAG_ALLOW_SPECIAL; } else if (monster._mVar2 == 15) { monster._mFlags &= ~MFLAG_ALLOW_SPECIAL; } } if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) { M_StartStand(monster, monster._mdir); return true; } return false; } bool MonsterSpecialAttack(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; assert(monster.MType != nullptr); assert(monster.MData != nullptr); if (monster.AnimInfo.CurrentFrame == monster.MData->mAFNum2) MonsterAttackPlayer(i, monster._menemy, monster.mHit2, monster.mMinDamage2, monster.mMaxDamage2); if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) { M_StartStand(monster, monster._mdir); return true; } return false; } bool MonsterFadein(MonsterStruct &monster) { if (((monster._mFlags & MFLAG_LOCK_ANIMATION) == 0 || monster.AnimInfo.CurrentFrame != 1) && ((monster._mFlags & MFLAG_LOCK_ANIMATION) != 0 || monster.AnimInfo.CurrentFrame != monster.AnimInfo.NumberOfFrames)) { return false; } M_StartStand(monster, monster._mdir); monster._mFlags &= ~MFLAG_LOCK_ANIMATION; return true; } bool MonsterFadeout(MonsterStruct &monster) { if (((monster._mFlags & MFLAG_LOCK_ANIMATION) == 0 || monster.AnimInfo.CurrentFrame != 1) && ((monster._mFlags & MFLAG_LOCK_ANIMATION) != 0 || monster.AnimInfo.CurrentFrame != monster.AnimInfo.NumberOfFrames)) { return false; } int mt = monster.MType->mtype; if (mt < MT_INCIN || mt > MT_HELLBURN) { monster._mFlags &= ~MFLAG_LOCK_ANIMATION; monster._mFlags |= MFLAG_HIDDEN; } else { monster._mFlags &= ~MFLAG_LOCK_ANIMATION; } M_StartStand(monster, monster._mdir); return true; } bool MonsterHeal(MonsterStruct &monster) { if ((monster._mFlags & MFLAG_NOHEAL) != 0) { monster._mFlags &= ~MFLAG_ALLOW_SPECIAL; monster._mmode = MM_SATTACK; return false; } if (monster.AnimInfo.CurrentFrame == 1) { monster._mFlags &= ~MFLAG_LOCK_ANIMATION; monster._mFlags |= MFLAG_ALLOW_SPECIAL; if (monster._mVar1 + monster._mhitpoints < monster._mmaxhp) { monster._mhitpoints = monster._mVar1 + monster._mhitpoints; } else { monster._mhitpoints = monster._mmaxhp; monster._mFlags &= ~MFLAG_ALLOW_SPECIAL; monster._mmode = MM_SATTACK; } } return false; } bool MonsterTalk(MonsterStruct &monster) { M_StartStand(monster, monster._mdir); monster._mgoal = MGOAL_TALKING; if (effect_is_playing(Texts[monster.mtalkmsg].sfxnr)) return false; InitQTextMsg(monster.mtalkmsg); if (monster._uniqtype - 1 == UMT_GARBUD) { if (monster.mtalkmsg == TEXT_GARBUD1) { Quests[Q_GARBUD]._qactive = QUEST_ACTIVE; Quests[Q_GARBUD]._qlog = true; // BUGFIX: (?) for other quests qactive and qlog go together, maybe this should actually go into the if above (fixed) } if (monster.mtalkmsg == TEXT_GARBUD2 && (monster._mFlags & MFLAG_QUEST_COMPLETE) == 0) { SpawnItem(monster, monster.position.tile + Displacement { 1, 1 }, true); monster._mFlags |= MFLAG_QUEST_COMPLETE; } } if (monster._uniqtype - 1 == UMT_ZHAR && monster.mtalkmsg == TEXT_ZHAR1 && (monster._mFlags & MFLAG_QUEST_COMPLETE) == 0) { Quests[Q_ZHAR]._qactive = QUEST_ACTIVE; Quests[Q_ZHAR]._qlog = true; CreateTypeItem(monster.position.tile + Displacement { 1, 1 }, false, ITYPE_MISC, IMISC_BOOK, true, false); monster._mFlags |= MFLAG_QUEST_COMPLETE; } if (monster._uniqtype - 1 == UMT_SNOTSPIL) { if (monster.mtalkmsg == TEXT_BANNER10 && (monster._mFlags & MFLAG_QUEST_COMPLETE) == 0) { ObjChangeMap(setpc_x, setpc_y, (setpc_w / 2) + setpc_x + 2, (setpc_h / 2) + setpc_y - 2); auto tren = TransVal; TransVal = 9; DRLG_MRectTrans(setpc_x, setpc_y, (setpc_w / 2) + setpc_x + 4, setpc_y + (setpc_h / 2)); TransVal = tren; Quests[Q_LTBANNER]._qvar1 = 2; if (Quests[Q_LTBANNER]._qactive == QUEST_INIT) Quests[Q_LTBANNER]._qactive = QUEST_ACTIVE; monster._mFlags |= MFLAG_QUEST_COMPLETE; } if (Quests[Q_LTBANNER]._qvar1 < 2) { app_fatal("SS Talk = %i, Flags = %i", monster.mtalkmsg, monster._mFlags); } } if (monster._uniqtype - 1 == UMT_LACHDAN) { if (monster.mtalkmsg == TEXT_VEIL9) { Quests[Q_VEIL]._qactive = QUEST_ACTIVE; Quests[Q_VEIL]._qlog = true; } if (monster.mtalkmsg == TEXT_VEIL11 && (monster._mFlags & MFLAG_QUEST_COMPLETE) == 0) { SpawnUnique(UITEM_STEELVEIL, monster.position.tile + DIR_S); monster._mFlags |= MFLAG_QUEST_COMPLETE; } } if (monster._uniqtype - 1 == UMT_WARLORD) Quests[Q_WARLORD]._qvar1 = 2; if (monster._uniqtype - 1 == UMT_LAZARUS && gbIsMultiplayer) { Quests[Q_BETRAYER]._qvar1 = 6; monster._mgoal = MGOAL_NORMAL; monster._msquelch = UINT8_MAX; monster.mtalkmsg = TEXT_NONE; } return false; } bool MonsterGotHit(MonsterStruct &monster) { if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) { M_StartStand(monster, monster._mdir); return true; } return false; } bool MonsterDeath(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; assert(monster.MType != nullptr); monster._mVar1++; if (monster.MType->mtype == MT_DIABLO) { if (monster.position.tile.x < ViewX) { ViewX--; } else if (monster.position.tile.x > ViewX) { ViewX++; } if (monster.position.tile.y < ViewY) { ViewY--; } else if (monster.position.tile.y > ViewY) { ViewY++; } if (monster._mVar1 == 140) PrepDoEnding(); } else if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) { if (monster._uniqtype == 0) AddDead(monster.position.tile, monster.MType->mdeadval, monster._mdir); else AddDead(monster.position.tile, monster._udeadval, monster._mdir); dMonster[monster.position.tile.x][monster.position.tile.y] = 0; monster._mDelFlag = true; M_UpdateLeader(i); } return false; } bool MonsterSpecialStand(MonsterStruct &monster) { if (monster.AnimInfo.CurrentFrame == monster.MData->mAFNum2) PlayEffect(monster, 3); if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) { M_StartStand(monster, monster._mdir); return true; } return false; } bool MonsterDelay(MonsterStruct &monster) { monster.AnimInfo.pCelSprite = &*monster.MType->GetAnimData(MonsterGraphic::Stand).CelSpritesForDirections[GetMonsterDirection(monster)]; if (monster._mAi == AI_LAZARUS) { if (monster._mVar2 > 8 || monster._mVar2 < 0) monster._mVar2 = 8; } if (monster._mVar2-- == 0) { int oFrame = monster.AnimInfo.CurrentFrame; M_StartStand(monster, monster._mdir); monster.AnimInfo.CurrentFrame = oFrame; return true; } return false; } bool MonsterPetrified(MonsterStruct &monster) { if (monster._mhitpoints <= 0) { dMonster[monster.position.tile.x][monster.position.tile.y] = 0; monster._mDelFlag = true; } return false; } int AddSkeleton(Point position, Direction dir, bool inMap) { int j = 0; for (int i = 0; i < LevelMonsterTypeCount; i++) { if (IsSkel(LevelMonsterTypes[i].mtype)) j++; } if (j == 0) { return -1; } int skeltypes = GenerateRnd(j); int m = 0; for (int i = 0; m < LevelMonsterTypeCount && i <= skeltypes; m++) { if (IsSkel(LevelMonsterTypes[m].mtype)) i++; } return AddMonster(position, dir, m - 1, inMap); } void SpawnSkeleton(Point position, Direction dir) { int skel = AddSkeleton(position, dir, true); if (skel != -1) StartSpecialStand(Monsters[skel], dir); } bool IsLineNotSolid(Point startPoint, Point endPoint) { return LineClear(IsTileNotSolid, startPoint, endPoint); } void GroupUnity(MonsterStruct &monster) { if (monster.leaderRelation == LeaderRelation::None) return; // Someone with a leaderRelation should have a leader ... assert(monster.leader >= 0); // And no unique monster would be a minion of someone else! assert(monster._uniqtype == 0); auto &leader = Monsters[monster.leader]; if (IsLineNotSolid(monster.position.tile, leader.position.future)) { if (monster.leaderRelation == LeaderRelation::Separated && monster.position.tile.WalkingDistance(leader.position.future) < 4) { // Reunite the separated monster with the pack leader.packsize++; monster.leaderRelation = LeaderRelation::Leashed; } } else if (monster.leaderRelation == LeaderRelation::Leashed) { leader.packsize--; monster.leaderRelation = LeaderRelation::Separated; } if (monster.leaderRelation == LeaderRelation::Leashed) { if (monster._msquelch > leader._msquelch) { leader.position.last = monster.position.tile; leader._msquelch = monster._msquelch - 1; } if (leader._mAi == AI_GARG && (leader._mFlags & MFLAG_ALLOW_SPECIAL) != 0) { leader._mFlags &= ~MFLAG_ALLOW_SPECIAL; leader._mmode = MM_SATTACK; } } } bool RandomWalk(int i, Direction md) { Direction mdtemp = md; bool ok = DirOK(i, md); if (GenerateRnd(2) != 0) ok = ok || (md = left[mdtemp], DirOK(i, md)) || (md = right[mdtemp], DirOK(i, md)); else ok = ok || (md = right[mdtemp], DirOK(i, md)) || (md = left[mdtemp], DirOK(i, md)); if (GenerateRnd(2) != 0) { ok = ok || (md = right[right[mdtemp]], DirOK(i, md)) || (md = left[left[mdtemp]], DirOK(i, md)); } else { ok = ok || (md = left[left[mdtemp]], DirOK(i, md)) || (md = right[right[mdtemp]], DirOK(i, md)); } if (ok) M_WalkDir(i, md); return ok; } bool RandomWalk2(int i, Direction md) { Direction mdtemp = md; bool ok = DirOK(i, md); // Can we continue in the same direction if (GenerateRnd(2) != 0) { // Randomly go left or right ok = ok || (mdtemp = left[md], DirOK(i, left[md])) || (mdtemp = right[md], DirOK(i, right[md])); } else { ok = ok || (mdtemp = right[md], DirOK(i, right[md])) || (mdtemp = left[md], DirOK(i, left[md])); } if (ok) M_WalkDir(i, mdtemp); return ok; } /** * @brief Check if a tile is affected by a spell we are vunerable to */ bool IsTileSafe(const MonsterStruct &monster, Point position) { int8_t mi = dMissile[position.x][position.y]; if (mi == 0) { return true; } bool fire = false; bool lightning = false; if (mi > 0) { if (Missiles[mi - 1]._mitype == MIS_FIREWALL) { // BUGFIX: Change 'mi' to 'mi - 1' (fixed) fire = true; } else if (Missiles[mi - 1]._mitype == MIS_LIGHTWALL) { // BUGFIX: Change 'mi' to 'mi - 1' (fixed) lightning = true; } } else { for (int j = 0; j < ActiveMissileCount; j++) { mi = ActiveMissiles[j]; auto &missile = Missiles[mi]; if (missile.position.tile == position) { if (missile._mitype == MIS_FIREWALL) { fire = true; break; } if (missile._mitype == MIS_LIGHTWALL) { lightning = true; break; } } } } if (fire && ((monster.mMagicRes & IMMUNE_FIRE) == 0 || monster.MType->mtype == MT_DIABLO)) return false; if (lightning && ((monster.mMagicRes & IMMUNE_LIGHTNING) == 0 || monster.MType->mtype == MT_DIABLO)) return false; return true; } /** * @brief Check that the given tile is not currently blocked */ bool IsTileAvailable(Point position) { if (dPlayer[position.x][position.y] != 0 || dMonster[position.x][position.y] != 0) return false; if (!IsTileWalkable(position)) return false; return true; } /** * @brief If a monster can access the given tile (possibly by opening a door) */ bool IsTileAccessible(const MonsterStruct &monster, Point position) { if (dPlayer[position.x][position.y] != 0 || dMonster[position.x][position.y] != 0) return false; if (!IsTileWalkable(position, (monster._mFlags & MFLAG_CAN_OPEN_DOOR) != 0)) return false; return IsTileSafe(monster, position); } bool AiPlanWalk(int i) { int8_t path[MAX_PATH_LENGTH]; /** Maps from walking path step to facing direction. */ const Direction plr2monst[9] = { DIR_S, DIR_NE, DIR_NW, DIR_SE, DIR_SW, DIR_N, DIR_E, DIR_S, DIR_W }; assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (FindPath([&monster](Point position) { return IsTileAccessible(monster, position); }, monster.position.tile, monster.enemyPosition, path) == 0) { return false; } RandomWalk(i, plr2monst[path[0]]); return true; } bool DumbWalk(int i, Direction md) { bool ok = DirOK(i, md); if (ok) M_WalkDir(i, md); return ok; } Direction Turn(Direction direction, bool turnLeft) { return turnLeft ? left[direction] : right[direction]; } bool RoundWalk(int i, Direction direction, int *dir) { Direction turn45deg = Turn(direction, *dir != 0); Direction turn90deg = Turn(turn45deg, *dir != 0); if (DirOK(i, turn90deg)) { // Turn 90 degrees M_WalkDir(i, turn90deg); return true; } if (DirOK(i, turn45deg)) { // Only do a small turn M_WalkDir(i, turn45deg); return true; } if (DirOK(i, direction)) { // Continue straight M_WalkDir(i, direction); return true; } // Try 90 degrees in the opposite than desired direction *dir = (*dir == 0) ? 1 : 0; return RandomWalk(i, opposite[turn90deg]); } bool AiPlanPath(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster.MType->mtype != MT_GOLEM) { if (monster._msquelch == 0) return false; if (monster._mmode != MM_STAND) return false; if (monster._mgoal != MGOAL_NORMAL && monster._mgoal != MGOAL_MOVE && monster._mgoal != MGOAL_ATTACK2) return false; if (monster.position.tile.x == 1 && monster.position.tile.y == 0) return false; } bool clear = LineClear( [&monster](Point position) { return IsTileAvailable(monster, position); }, monster.position.tile, monster.enemyPosition); if (!clear || (monster._pathcount >= 5 && monster._pathcount < 8)) { if ((monster._mFlags & MFLAG_CAN_OPEN_DOOR) != 0) MonstCheckDoors(monster); monster._pathcount++; if (monster._pathcount < 5) return false; if (AiPlanWalk(i)) return true; } if (monster.MType->mtype != MT_GOLEM) monster._pathcount = 0; return false; } void AiAvoidance(int i, bool special) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; int mx = monster.position.tile.x - fx; int my = monster.position.tile.y - fy; Direction md = GetDirection(monster.position.tile, monster.position.last); if (monster._msquelch < UINT8_MAX) MonstCheckDoors(monster); int v = GenerateRnd(100); if ((abs(mx) >= 2 || abs(my) >= 2) && monster._msquelch == UINT8_MAX && dTransVal[monster.position.tile.x][monster.position.tile.y] == dTransVal[fx][fy]) { if (monster._mgoal == MGOAL_MOVE || ((abs(mx) >= 4 || abs(my) >= 4) && GenerateRnd(4) == 0)) { if (monster._mgoal != MGOAL_MOVE) { monster._mgoalvar1 = 0; monster._mgoalvar2 = GenerateRnd(2); } monster._mgoal = MGOAL_MOVE; int dist = std::max(abs(mx), abs(my)); if ((monster._mgoalvar1++ >= 2 * dist && DirOK(i, md)) || dTransVal[monster.position.tile.x][monster.position.tile.y] != dTransVal[fx][fy]) { monster._mgoal = MGOAL_NORMAL; } else if (!RoundWalk(i, md, &monster._mgoalvar2)) { AiDelay(monster, GenerateRnd(10) + 10); } } } else { monster._mgoal = MGOAL_NORMAL; } if (monster._mgoal == MGOAL_NORMAL) { if (abs(mx) >= 2 || abs(my) >= 2) { if ((monster._mVar2 > 20 && v < 2 * monster._mint + 28) || ((monster._mVar1 == MM_WALK || monster._mVar1 == MM_WALK2 || monster._mVar1 == MM_WALK3) && monster._mVar2 == 0 && v < 2 * monster._mint + 78)) { RandomWalk(i, md); } } else if (v < 2 * monster._mint + 23) { monster._mdir = md; if (special && monster._mhitpoints < (monster._mmaxhp / 2) && GenerateRnd(2) != 0) StartSpecialAttack(monster); else StartAttack(monster); } } monster.CheckStandAnimationIsLoaded(md); } void AiRanged(int i, missile_id missileType, bool special) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } if (monster._msquelch == UINT8_MAX || (monster._mFlags & MFLAG_TARGETS_MONSTER) != 0) { int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; int mx = monster.position.tile.x - fx; int my = monster.position.tile.y - fy; Direction md = GetMonsterDirection(monster); if (monster._msquelch < UINT8_MAX) MonstCheckDoors(monster); monster._mdir = md; if (monster._mVar1 == MM_RATTACK) { AiDelay(monster, GenerateRnd(20)); } else if (abs(mx) < 4 && abs(my) < 4) { if (GenerateRnd(100) < 10 * (monster._mint + 7)) RandomWalk(i, opposite[md]); } if (monster._mmode == MM_STAND) { if (LineClearMissile(monster.position.tile, { fx, fy })) { if (special) StartRangedSpecialAttack(monster, missileType, 4); else StartRangedAttack(monster, missileType, 4); } else { monster.CheckStandAnimationIsLoaded(md); } } return; } if (monster._msquelch != 0) { int fx = monster.position.last.x; int fy = monster.position.last.y; Direction md = GetDirection(monster.position.tile, { fx, fy }); RandomWalk(i, md); } } void AiRangedAvoidance(int i, missile_id missileType, bool checkdoors, int dam, int lessmissiles) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; int mx = monster.position.tile.x - fx; int my = monster.position.tile.y - fy; Direction md = GetDirection(monster.position.tile, monster.position.last); if (checkdoors && monster._msquelch < UINT8_MAX) MonstCheckDoors(monster); int v = GenerateRnd(10000); int dist = std::max(abs(mx), abs(my)); if (dist >= 2 && monster._msquelch == UINT8_MAX && dTransVal[monster.position.tile.x][monster.position.tile.y] == dTransVal[fx][fy]) { if (monster._mgoal == MGOAL_MOVE || (dist >= 3 && GenerateRnd(4 << lessmissiles) == 0)) { if (monster._mgoal != MGOAL_MOVE) { monster._mgoalvar1 = 0; monster._mgoalvar2 = GenerateRnd(2); } monster._mgoal = MGOAL_MOVE; if (monster._mgoalvar1++ >= 2 * dist && DirOK(i, md)) { monster._mgoal = MGOAL_NORMAL; } else if (v < (500 * (monster._mint + 1) >> lessmissiles) && (LineClearMissile(monster.position.tile, { fx, fy }))) { StartRangedSpecialAttack(monster, missileType, dam); } else { RoundWalk(i, md, &monster._mgoalvar2); } } } else { monster._mgoal = MGOAL_NORMAL; } if (monster._mgoal == MGOAL_NORMAL) { if (((dist >= 3 && v < ((500 * (monster._mint + 2)) >> lessmissiles)) || v < ((500 * (monster._mint + 1)) >> lessmissiles)) && LineClearMissile(monster.position.tile, { fx, fy })) { StartRangedSpecialAttack(monster, missileType, dam); } else if (dist >= 2) { v = GenerateRnd(100); if (v < 1000 * (monster._mint + 5) || ((monster._mVar1 == MM_WALK || monster._mVar1 == MM_WALK2 || monster._mVar1 == MM_WALK3) && monster._mVar2 == 0 && v < 1000 * (monster._mint + 8))) { RandomWalk(i, md); } } else if (v < 1000 * (monster._mint + 6)) { monster._mdir = md; StartAttack(monster); } } if (monster._mmode == MM_STAND) { AiDelay(monster, GenerateRnd(10) + 5); } } void ZombieAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; if ((dFlags[mx][my] & BFLAG_VISIBLE) == 0) { return; } if (GenerateRnd(100) < 2 * monster._mint + 10) { int dist = monster.enemyPosition.WalkingDistance({ mx, my }); if (dist >= 2) { if (dist >= 2 * monster._mint + 4) { Direction md = monster._mdir; if (GenerateRnd(100) < 2 * monster._mint + 20) { md = static_cast<Direction>(GenerateRnd(8)); } DumbWalk(i, md); } else { RandomWalk(i, GetMonsterDirection(monster)); } } else { StartAttack(monster); } } monster.CheckStandAnimationIsLoaded(monster._mdir); } void OverlordAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int mx = monster.position.tile.x - monster.enemyPosition.x; int my = monster.position.tile.y - monster.enemyPosition.y; Direction md = GetMonsterDirection(monster); monster._mdir = md; int v = GenerateRnd(100); if (abs(mx) >= 2 || abs(my) >= 2) { if ((monster._mVar2 > 20 && v < 4 * monster._mint + 20) || ((monster._mVar1 == MM_WALK || monster._mVar1 == MM_WALK2 || monster._mVar1 == MM_WALK3) && monster._mVar2 == 0 && v < 4 * monster._mint + 70)) { RandomWalk(i, md); } } else if (v < 4 * monster._mint + 15) { StartAttack(monster); } else if (v < 4 * monster._mint + 20) { StartSpecialAttack(monster); } monster.CheckStandAnimationIsLoaded(md); } void SkeletonAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int x = monster.position.tile.x - monster.enemyPosition.x; int y = monster.position.tile.y - monster.enemyPosition.y; Direction md = GetDirection(monster.position.tile, monster.position.last); monster._mdir = md; if (abs(x) >= 2 || abs(y) >= 2) { if (monster._mVar1 == MM_DELAY || (GenerateRnd(100) >= 35 - 4 * monster._mint)) { RandomWalk(i, md); } else { AiDelay(monster, 15 - 2 * monster._mint + GenerateRnd(10)); } } else { if (monster._mVar1 == MM_DELAY || (GenerateRnd(100) < 2 * monster._mint + 20)) { StartAttack(monster); } else { AiDelay(monster, 2 * (5 - monster._mint) + GenerateRnd(10)); } } monster.CheckStandAnimationIsLoaded(md); } void SkeletonBowAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int mx = monster.position.tile.x - monster.enemyPosition.x; int my = monster.position.tile.y - monster.enemyPosition.y; Direction md = GetMonsterDirection(monster); monster._mdir = md; int v = GenerateRnd(100); bool walking = false; if (abs(mx) < 4 && abs(my) < 4) { if ((monster._mVar2 > 20 && v < 2 * monster._mint + 13) || ((monster._mVar1 == MM_WALK || monster._mVar1 == MM_WALK2 || monster._mVar1 == MM_WALK3) && monster._mVar2 == 0 && v < 2 * monster._mint + 63)) { walking = DumbWalk(i, opposite[md]); } } if (!walking) { if (GenerateRnd(100) < 2 * monster._mint + 3) { if (LineClearMissile(monster.position.tile, monster.enemyPosition)) StartRangedAttack(monster, MIS_ARROW, 4); } } monster.CheckStandAnimationIsLoaded(md); } void ScavengerAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) return; if (monster._mhitpoints < (monster._mmaxhp / 2) && monster._mgoal != MGOAL_HEALING) { if (monster.leaderRelation != LeaderRelation::None) { Monsters[monster.leader].packsize--; monster.leaderRelation = LeaderRelation::None; } monster._mgoal = MGOAL_HEALING; monster._mgoalvar3 = 10; } if (monster._mgoal == MGOAL_HEALING && monster._mgoalvar3 != 0) { monster._mgoalvar3--; if (dDead[monster.position.tile.x][monster.position.tile.y] != 0) { StartEating(monster); if ((monster._mFlags & MFLAG_NOHEAL) == 0) { if (gbIsHellfire) { int mMaxHP = monster._mmaxhp; // BUGFIX use _mmaxhp or we loose health when difficulty isn't normal (fixed) monster._mhitpoints += mMaxHP / 8; if (monster._mhitpoints > monster._mmaxhp) monster._mhitpoints = monster._mmaxhp; if (monster._mgoalvar3 <= 0 || monster._mhitpoints == monster._mmaxhp) dDead[monster.position.tile.x][monster.position.tile.y] = 0; } else { monster._mhitpoints += 64; } } int targetHealth = monster._mmaxhp; if (!gbIsHellfire) targetHealth = (monster._mmaxhp / 2) + (monster._mmaxhp / 4); if (monster._mhitpoints >= targetHealth) { monster._mgoal = MGOAL_NORMAL; monster._mgoalvar1 = 0; monster._mgoalvar2 = 0; } } else { if (monster._mgoalvar1 == 0) { bool done = false; int x; int y; if (GenerateRnd(2) != 0) { for (y = -4; y <= 4 && !done; y++) { for (x = -4; x <= 4 && !done; x++) { // BUGFIX: incorrect check of offset against limits of the dungeon if (y < 0 || y >= MAXDUNY || x < 0 || x >= MAXDUNX) continue; done = dDead[monster.position.tile.x + x][monster.position.tile.y + y] != 0 && IsLineNotSolid( monster.position.tile, monster.position.tile + Displacement { x, y }); } } x--; y--; } else { for (y = 4; y >= -4 && !done; y--) { for (x = 4; x >= -4 && !done; x--) { // BUGFIX: incorrect check of offset against limits of the dungeon if (y < 0 || y >= MAXDUNY || x < 0 || x >= MAXDUNX) continue; done = dDead[monster.position.tile.x + x][monster.position.tile.y + y] != 0 && IsLineNotSolid( monster.position.tile, monster.position.tile + Displacement { x, y }); } } x++; y++; } if (done) { monster._mgoalvar1 = x + monster.position.tile.x + 1; monster._mgoalvar2 = y + monster.position.tile.y + 1; } } if (monster._mgoalvar1 != 0) { int x = monster._mgoalvar1 - 1; int y = monster._mgoalvar2 - 1; monster._mdir = GetDirection(monster.position.tile, { x, y }); RandomWalk(i, monster._mdir); } } } if (monster._mmode == MM_STAND) SkeletonAi(i); } void RhinoAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; int mx = monster.position.tile.x - fx; int my = monster.position.tile.y - fy; Direction md = GetDirection(monster.position.tile, monster.position.last); if (monster._msquelch < UINT8_MAX) MonstCheckDoors(monster); int v = GenerateRnd(100); int dist = std::max(abs(mx), abs(my)); if (dist >= 2) { if (monster._mgoal == MGOAL_MOVE || (dist >= 5 && GenerateRnd(4) != 0)) { if (monster._mgoal != MGOAL_MOVE) { monster._mgoalvar1 = 0; monster._mgoalvar2 = GenerateRnd(2); } monster._mgoal = MGOAL_MOVE; if (monster._mgoalvar1++ >= 2 * dist || dTransVal[monster.position.tile.x][monster.position.tile.y] != dTransVal[fx][fy]) { monster._mgoal = MGOAL_NORMAL; } else if (!RoundWalk(i, md, &monster._mgoalvar2)) { AiDelay(monster, GenerateRnd(10) + 10); } } } else { monster._mgoal = MGOAL_NORMAL; } if (monster._mgoal == MGOAL_NORMAL) { if (dist >= 5 && v < 2 * monster._mint + 43 && LineClear([&monster](Point position) { return IsTileAvailable(monster, position); }, monster.position.tile, { fx, fy })) { if (AddMissile(monster.position.tile, { fx, fy }, md, MIS_RHINO, monster._menemy, i, 0, 0) != -1) { if (monster.MData->snd_special) PlayEffect(monster, 3); dMonster[monster.position.tile.x][monster.position.tile.y] = -(i + 1); monster._mmode = MM_CHARGE; } } else { if (dist >= 2) { v = GenerateRnd(100); if (v >= 2 * monster._mint + 33 && ((monster._mVar1 != MM_WALK && monster._mVar1 != MM_WALK2 && monster._mVar1 != MM_WALK3) || monster._mVar2 != 0 || v >= 2 * monster._mint + 83)) { AiDelay(monster, GenerateRnd(10) + 10); } else { RandomWalk(i, md); } } else if (v < 2 * monster._mint + 28) { monster._mdir = md; StartAttack(monster); } } } monster.CheckStandAnimationIsLoaded(monster._mdir); } void GoatAi(int i) { AiAvoidance(i, true); } void GoatBowAi(int i) { AiRanged(i, MIS_ARROW, false); } void FallenAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mgoal == MGOAL_ATTACK2) { if (monster._mgoalvar1 != 0) monster._mgoalvar1--; else monster._mgoal = MGOAL_NORMAL; } if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } if (monster._mgoal == MGOAL_RETREAT) { if (monster._mgoalvar1-- == 0) { monster._mgoal = MGOAL_NORMAL; M_StartStand(monster, opposite[monster._mgoalvar2]); } } if (monster.AnimInfo.CurrentFrame == monster.AnimInfo.NumberOfFrames) { if (GenerateRnd(4) != 0) { return; } if ((monster._mFlags & MFLAG_NOHEAL) == 0) { StartSpecialStand(monster, monster._mdir); if (monster._mmaxhp - (2 * monster._mint + 2) >= monster._mhitpoints) monster._mhitpoints += 2 * monster._mint + 2; else monster._mhitpoints = monster._mmaxhp; } int rad = 2 * monster._mint + 4; for (int y = -rad; y <= rad; y++) { for (int x = -rad; x <= rad; x++) { int xpos = monster.position.tile.x + x; int ypos = monster.position.tile.y + y; if (y >= 0 && y < MAXDUNY && x >= 0 && x < MAXDUNX) { int m = dMonster[xpos][ypos]; if (m <= 0) continue; auto &otherMonster = Monsters[m - 1]; if (otherMonster._mAi != AI_FALLEN) continue; otherMonster._mgoal = MGOAL_ATTACK2; otherMonster._mgoalvar1 = 30 * monster._mint + 105; } } } } else if (monster._mgoal == MGOAL_RETREAT) { RandomWalk(i, monster._mdir); } else if (monster._mgoal == MGOAL_ATTACK2) { int xpos = monster.position.tile.x - monster.enemyPosition.x; int ypos = monster.position.tile.y - monster.enemyPosition.y; if (abs(xpos) < 2 && abs(ypos) < 2) StartAttack(monster); else RandomWalk(i, GetMonsterDirection(monster)); } else SkeletonAi(i); } void MagmaAi(int i) { AiRangedAvoidance(i, MIS_MAGMABALL, true, 4, 0); } void LeoricAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; int mx = monster.position.tile.x - fx; int my = monster.position.tile.y - fy; Direction md = GetDirection(monster.position.tile, monster.position.last); if (monster._msquelch < UINT8_MAX) MonstCheckDoors(monster); int v = GenerateRnd(100); int dist = std::max(abs(mx), abs(my)); if (dist >= 2 && monster._msquelch == UINT8_MAX && dTransVal[monster.position.tile.x][monster.position.tile.y] == dTransVal[fx][fy]) { if (monster._mgoal == MGOAL_MOVE || ((abs(mx) >= 3 || abs(my) >= 3) && GenerateRnd(4) == 0)) { if (monster._mgoal != MGOAL_MOVE) { monster._mgoalvar1 = 0; monster._mgoalvar2 = GenerateRnd(2); } monster._mgoal = MGOAL_MOVE; if ((monster._mgoalvar1++ >= 2 * dist && DirOK(i, md)) || dTransVal[monster.position.tile.x][monster.position.tile.y] != dTransVal[fx][fy]) { monster._mgoal = MGOAL_NORMAL; } else if (!RoundWalk(i, md, &monster._mgoalvar2)) { AiDelay(monster, GenerateRnd(10) + 10); } } } else { monster._mgoal = MGOAL_NORMAL; } if (monster._mgoal == MGOAL_NORMAL) { if (!gbIsMultiplayer && ((dist >= 3 && v < 4 * monster._mint + 35) || v < 6) && LineClearMissile(monster.position.tile, { fx, fy })) { Point newPosition = monster.position.tile + md; if (IsTileAvailable(monster, newPosition) && ActiveMonsterCount < MAXMONSTERS) { SpawnSkeleton(newPosition, md); StartSpecialStand(monster, md); } } else { if (dist >= 2) { v = GenerateRnd(100); if (v >= monster._mint + 25 && ((monster._mVar1 != MM_WALK && monster._mVar1 != MM_WALK2 && monster._mVar1 != MM_WALK3) || monster._mVar2 != 0 || (v >= monster._mint + 75))) { AiDelay(monster, GenerateRnd(10) + 10); } else { RandomWalk(i, md); } } else if (v < monster._mint + 20) { monster._mdir = md; StartAttack(monster); } } } monster.CheckStandAnimationIsLoaded(md); } void BatAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; int pnum = monster._menemy; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int xd = monster.position.tile.x - monster.enemyPosition.x; int yd = monster.position.tile.y - monster.enemyPosition.y; Direction md = GetDirection(monster.position.tile, monster.position.last); monster._mdir = md; int v = GenerateRnd(100); if (monster._mgoal == MGOAL_RETREAT) { if (monster._mgoalvar1 == 0) { RandomWalk(i, opposite[md]); monster._mgoalvar1++; } else { if (GenerateRnd(2) != 0) RandomWalk(i, left[md]); else RandomWalk(i, right[md]); monster._mgoal = MGOAL_NORMAL; } return; } int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; if (monster.MType->mtype == MT_GLOOM && (abs(xd) >= 5 || abs(yd) >= 5) && v < 4 * monster._mint + 33 && LineClear([&monster](Point position) { return IsTileAvailable(monster, position); }, monster.position.tile, { fx, fy })) { if (AddMissile(monster.position.tile, { fx, fy }, md, MIS_RHINO, pnum, i, 0, 0) != -1) { dMonster[monster.position.tile.x][monster.position.tile.y] = -(i + 1); monster._mmode = MM_CHARGE; } } else if (abs(xd) >= 2 || abs(yd) >= 2) { if ((monster._mVar2 > 20 && v < monster._mint + 13) || ((monster._mVar1 == MM_WALK || monster._mVar1 == MM_WALK2 || monster._mVar1 == MM_WALK3) && monster._mVar2 == 0 && v < monster._mint + 63)) { RandomWalk(i, md); } } else if (v < 4 * monster._mint + 8) { StartAttack(monster); monster._mgoal = MGOAL_RETREAT; monster._mgoalvar1 = 0; if (monster.MType->mtype == MT_FAMILIAR) { AddMissile(monster.enemyPosition, { monster.enemyPosition.x + 1, 0 }, -1, MIS_LIGHTNING, TARGET_PLAYERS, i, GenerateRnd(10) + 1, 0); } } monster.CheckStandAnimationIsLoaded(md); } void GargoyleAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; int dx = monster.position.tile.x - monster.position.last.x; int dy = monster.position.tile.y - monster.position.last.y; Direction md = GetMonsterDirection(monster); if (monster._msquelch != 0 && (monster._mFlags & MFLAG_ALLOW_SPECIAL) != 0) { UpdateEnemy(monster); int mx = monster.position.tile.x - monster.enemyPosition.x; int my = monster.position.tile.y - monster.enemyPosition.y; if (abs(mx) < monster._mint + 2 && abs(my) < monster._mint + 2) { monster._mFlags &= ~MFLAG_ALLOW_SPECIAL; } return; } if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } if (monster._mhitpoints < (monster._mmaxhp / 2)) if ((monster._mFlags & MFLAG_NOHEAL) == 0) monster._mgoal = MGOAL_RETREAT; if (monster._mgoal == MGOAL_RETREAT) { if (abs(dx) >= monster._mint + 2 || abs(dy) >= monster._mint + 2) { monster._mgoal = MGOAL_NORMAL; StartHeal(monster); } else if (!RandomWalk(i, opposite[md])) { monster._mgoal = MGOAL_NORMAL; } } AiAvoidance(i, false); } void ButcherAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; int x = mx - monster.enemyPosition.x; int y = my - monster.enemyPosition.y; Direction md = GetDirection({ mx, my }, monster.position.last); monster._mdir = md; if (abs(x) >= 2 || abs(y) >= 2) RandomWalk(i, md); else StartAttack(monster); monster.CheckStandAnimationIsLoaded(md); } void SuccubusAi(int i) { AiRanged(i, MIS_FLARE, false); } void SneakAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; if (dLight[mx][my] == LightsMax) { return; } mx -= monster.enemyPosition.x; my -= monster.enemyPosition.y; int dist = 5 - monster._mint; if (monster._mVar1 == MM_GOTHIT) { monster._mgoal = MGOAL_RETREAT; monster._mgoalvar1 = 0; } else if (abs(mx) >= dist + 3 || abs(my) >= dist + 3 || monster._mgoalvar1 > 8) { monster._mgoal = MGOAL_NORMAL; monster._mgoalvar1 = 0; } Direction md = GetMonsterDirection(monster); if (monster._mgoal == MGOAL_RETREAT && (monster._mFlags & MFLAG_NO_ENEMY) == 0) { if ((monster._mFlags & MFLAG_TARGETS_MONSTER) != 0) md = GetDirection(monster.position.tile, Monsters[monster._menemy].position.tile); else md = GetDirection(monster.position.tile, Players[monster._menemy].position.last); md = opposite[md]; if (monster.MType->mtype == MT_UNSEEN) { if (GenerateRnd(2) != 0) md = left[md]; else md = right[md]; } } monster._mdir = md; int v = GenerateRnd(100); if (abs(mx) < dist && abs(my) < dist && (monster._mFlags & MFLAG_HIDDEN) != 0) { StartFadein(monster, md, false); } else { if ((abs(mx) >= dist + 1 || abs(my) >= dist + 1) && (monster._mFlags & MFLAG_HIDDEN) == 0) { StartFadeout(monster, md, true); } else { if (monster._mgoal == MGOAL_RETREAT || ((abs(mx) >= 2 || abs(my) >= 2) && ((monster._mVar2 > 20 && v < 4 * monster._mint + 14) || ((monster._mVar1 == MM_WALK || monster._mVar1 == MM_WALK2 || monster._mVar1 == MM_WALK3) && monster._mVar2 == 0 && v < 4 * monster._mint + 64)))) { monster._mgoalvar1++; RandomWalk(i, md); } } } if (monster._mmode == MM_STAND) { if (abs(mx) >= 2 || abs(my) >= 2 || v >= 4 * monster._mint + 10) monster.AnimInfo.pCelSprite = &*monster.MType->GetAnimData(MonsterGraphic::Stand).CelSpritesForDirections[md]; else StartAttack(monster); } } void StormAi(int i) { AiRangedAvoidance(i, MIS_LIGHTCTRL2, true, 4, 0); } void GharbadAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; Direction md = GetMonsterDirection(monster); if (monster.mtalkmsg >= TEXT_GARBUD1 && monster.mtalkmsg <= TEXT_GARBUD3 && (dFlags[mx][my] & BFLAG_VISIBLE) == 0 && monster._mgoal == MGOAL_TALKING) { monster._mgoal = MGOAL_INQUIRING; switch (monster.mtalkmsg) { case TEXT_GARBUD1: monster.mtalkmsg = TEXT_GARBUD2; break; case TEXT_GARBUD2: monster.mtalkmsg = TEXT_GARBUD3; break; case TEXT_GARBUD3: monster.mtalkmsg = TEXT_GARBUD4; break; default: break; } } if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0) { if (monster.mtalkmsg == TEXT_GARBUD4) { if (!effect_is_playing(USFX_GARBUD4) && monster._mgoal == MGOAL_TALKING) { monster._mgoal = MGOAL_NORMAL; monster._msquelch = UINT8_MAX; monster.mtalkmsg = TEXT_NONE; } } } if (monster._mgoal == MGOAL_NORMAL || monster._mgoal == MGOAL_MOVE) AiAvoidance(i, true); monster.CheckStandAnimationIsLoaded(md); } void AcidAvoidanceAi(int i) { AiRangedAvoidance(i, MIS_ACID, false, 4, 1); } void AcidAi(int i) { AiRanged(i, MIS_ACID, true); } void SnotSpilAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; Direction md = GetMonsterDirection(monster); if (monster.mtalkmsg == TEXT_BANNER10 && (dFlags[mx][my] & BFLAG_VISIBLE) == 0 && monster._mgoal == MGOAL_TALKING) { monster.mtalkmsg = TEXT_BANNER11; monster._mgoal = MGOAL_INQUIRING; } if (monster.mtalkmsg == TEXT_BANNER11 && Quests[Q_LTBANNER]._qvar1 == 3) { monster.mtalkmsg = TEXT_NONE; monster._mgoal = MGOAL_NORMAL; } if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0) { if (monster.mtalkmsg == TEXT_BANNER12) { if (!effect_is_playing(USFX_SNOT3) && monster._mgoal == MGOAL_TALKING) { ObjChangeMap(setpc_x, setpc_y, setpc_x + setpc_w + 1, setpc_y + setpc_h + 1); Quests[Q_LTBANNER]._qvar1 = 3; RedoPlayerVision(); monster._msquelch = UINT8_MAX; monster.mtalkmsg = TEXT_NONE; monster._mgoal = MGOAL_NORMAL; } } if (Quests[Q_LTBANNER]._qvar1 == 3) { if (monster._mgoal == MGOAL_NORMAL || monster._mgoal == MGOAL_ATTACK2) FallenAi(i); } } monster.CheckStandAnimationIsLoaded(md); } void SnakeAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; char pattern[6] = { 1, 1, 0, -1, -1, 0 }; int pnum = monster._menemy; if (monster._mmode != MM_STAND || monster._msquelch == 0) return; int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; int mx = monster.position.tile.x - fx; int my = monster.position.tile.y - fy; Direction md = GetDirection(monster.position.tile, monster.position.last); monster._mdir = md; if (abs(mx) >= 2 || abs(my) >= 2) { if (abs(mx) < 3 && abs(my) < 3 && LineClear([&monster](Point position) { return IsTileAvailable(monster, position); }, monster.position.tile, { fx, fy }) && monster._mVar1 != MM_CHARGE) { if (AddMissile(monster.position.tile, { fx, fy }, md, MIS_RHINO, pnum, i, 0, 0) != -1) { PlayEffect(monster, 0); dMonster[monster.position.tile.x][monster.position.tile.y] = -(i + 1); monster._mmode = MM_CHARGE; } } else if (monster._mVar1 == MM_DELAY || GenerateRnd(100) >= 35 - 2 * monster._mint) { if (pattern[monster._mgoalvar1] == -1) md = left[md]; else if (pattern[monster._mgoalvar1] == 1) md = right[md]; monster._mgoalvar1++; if (monster._mgoalvar1 > 5) monster._mgoalvar1 = 0; if (md != monster._mgoalvar2) { int drift = md - monster._mgoalvar2; if (drift < 0) drift += 8; if (drift < 4) md = right[monster._mgoalvar2]; else if (drift > 4) md = left[monster._mgoalvar2]; monster._mgoalvar2 = md; } if (!DumbWalk(i, md)) RandomWalk2(i, monster._mdir); } else { AiDelay(monster, 15 - monster._mint + GenerateRnd(10)); } } else { if (monster._mVar1 == MM_DELAY || monster._mVar1 == MM_CHARGE || (GenerateRnd(100) < monster._mint + 20)) { StartAttack(monster); } else AiDelay(monster, 10 - monster._mint + GenerateRnd(10)); } monster.CheckStandAnimationIsLoaded(monster._mdir); } void CounselorAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; int mx = monster.position.tile.x - fx; int my = monster.position.tile.y - fy; Direction md = GetDirection(monster.position.tile, monster.position.last); if (monster._msquelch < UINT8_MAX) MonstCheckDoors(monster); int v = GenerateRnd(100); if (monster._mgoal == MGOAL_RETREAT) { if (monster._mgoalvar1++ <= 3) RandomWalk(i, opposite[md]); else { monster._mgoal = MGOAL_NORMAL; StartFadein(monster, md, true); } } else if (monster._mgoal == MGOAL_MOVE) { int dist = std::max(abs(mx), abs(my)); if (dist >= 2 && monster._msquelch == UINT8_MAX && dTransVal[monster.position.tile.x][monster.position.tile.y] == dTransVal[fx][fy]) { if (monster._mgoalvar1++ < 2 * dist || !DirOK(i, md)) { RoundWalk(i, md, &monster._mgoalvar2); } else { monster._mgoal = MGOAL_NORMAL; StartFadein(monster, md, true); } } else { monster._mgoal = MGOAL_NORMAL; StartFadein(monster, md, true); } } else if (monster._mgoal == MGOAL_NORMAL) { if (abs(mx) >= 2 || abs(my) >= 2) { if (v < 5 * (monster._mint + 10) && LineClearMissile(monster.position.tile, { fx, fy })) { constexpr missile_id MissileTypes[4] = { MIS_FIREBOLT, MIS_CBOLT, MIS_LIGHTCTRL, MIS_FIREBALL }; StartRangedAttack(monster, MissileTypes[monster._mint], monster.mMinDamage + GenerateRnd(monster.mMaxDamage - monster.mMinDamage + 1)); } else if (GenerateRnd(100) < 30) { monster._mgoal = MGOAL_MOVE; monster._mgoalvar1 = 0; StartFadeout(monster, md, false); } else AiDelay(monster, GenerateRnd(10) + 2 * (5 - monster._mint)); } else { monster._mdir = md; if (monster._mhitpoints < (monster._mmaxhp / 2)) { monster._mgoal = MGOAL_RETREAT; monster._mgoalvar1 = 0; StartFadeout(monster, md, false); } else if (monster._mVar1 == MM_DELAY || GenerateRnd(100) < 2 * monster._mint + 20) { StartRangedAttack(monster, MIS_NULL, 0); AddMissile(monster.position.tile, { 0, 0 }, monster._mdir, MIS_FLASH, TARGET_PLAYERS, i, 4, 0); AddMissile(monster.position.tile, { 0, 0 }, monster._mdir, MIS_FLASH2, TARGET_PLAYERS, i, 4, 0); } else AiDelay(monster, GenerateRnd(10) + 2 * (5 - monster._mint)); } } if (monster._mmode == MM_STAND) { AiDelay(monster, GenerateRnd(10) + 5); } } void ZharAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; Direction md = GetMonsterDirection(monster); if (monster.mtalkmsg == TEXT_ZHAR1 && (dFlags[mx][my] & BFLAG_VISIBLE) == 0 && monster._mgoal == MGOAL_TALKING) { monster.mtalkmsg = TEXT_ZHAR2; monster._mgoal = MGOAL_INQUIRING; } if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0) { if (monster.mtalkmsg == TEXT_ZHAR2) { if (!effect_is_playing(USFX_ZHAR2) && monster._mgoal == MGOAL_TALKING) { monster._msquelch = UINT8_MAX; monster.mtalkmsg = TEXT_NONE; monster._mgoal = MGOAL_NORMAL; } } } if (monster._mgoal == MGOAL_NORMAL || monster._mgoal == MGOAL_RETREAT || monster._mgoal == MGOAL_MOVE) CounselorAi(i); monster.CheckStandAnimationIsLoaded(md); } void MegaAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; int mx = monster.position.tile.x - monster.enemyPosition.x; int my = monster.position.tile.y - monster.enemyPosition.y; if (abs(mx) >= 5 || abs(my) >= 5) { SkeletonAi(i); return; } if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; mx = monster.position.tile.x - fx; my = monster.position.tile.y - fy; Direction md = GetDirection(monster.position.tile, monster.position.last); if (monster._msquelch < UINT8_MAX) MonstCheckDoors(monster); int v = GenerateRnd(100); int dist = std::max(abs(mx), abs(my)); if (dist >= 2 && monster._msquelch == UINT8_MAX && dTransVal[monster.position.tile.x][monster.position.tile.y] == dTransVal[fx][fy]) { if (monster._mgoal == MGOAL_MOVE || dist >= 3) { if (monster._mgoal != MGOAL_MOVE) { monster._mgoalvar1 = 0; monster._mgoalvar2 = GenerateRnd(2); } monster._mgoal = MGOAL_MOVE; monster._mgoalvar3 = 4; if (monster._mgoalvar1++ < 2 * dist || !DirOK(i, md)) { if (v < 5 * (monster._mint + 16)) RoundWalk(i, md, &monster._mgoalvar2); } else monster._mgoal = MGOAL_NORMAL; } } else { monster._mgoal = MGOAL_NORMAL; } if (monster._mgoal == MGOAL_NORMAL) { if (((dist >= 3 && v < 5 * (monster._mint + 2)) || v < 5 * (monster._mint + 1) || monster._mgoalvar3 == 4) && LineClearMissile(monster.position.tile, { fx, fy })) { StartRangedSpecialAttack(monster, MIS_FLAMEC, 0); } else if (dist >= 2) { v = GenerateRnd(100); if (v < 2 * (5 * monster._mint + 25) || ((monster._mVar1 == MM_WALK || monster._mVar1 == MM_WALK2 || monster._mVar1 == MM_WALK3) && monster._mVar2 == 0 && v < 2 * (5 * monster._mint + 40))) { RandomWalk(i, md); } } else { if (GenerateRnd(100) < 10 * (monster._mint + 4)) { monster._mdir = md; if (GenerateRnd(2) != 0) StartAttack(monster); else StartRangedSpecialAttack(monster, MIS_FLAMEC, 0); } } monster._mgoalvar3 = 1; } if (monster._mmode == MM_STAND) { AiDelay(monster, GenerateRnd(10) + 5); } } void DiabloAi(int i) { AiRangedAvoidance(i, MIS_DIABAPOCA, false, 40, 0); } void LazarusAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; Direction md = GetMonsterDirection(monster); if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0) { if (!gbIsMultiplayer) { auto &myPlayer = Players[MyPlayerId]; if (monster.mtalkmsg == TEXT_VILE13 && monster._mgoal == MGOAL_INQUIRING && myPlayer.position.tile.x == 35 && myPlayer.position.tile.y == 46) { PlayInGameMovie("gendata\\fprst3.smk"); monster._mmode = MM_TALK; Quests[Q_BETRAYER]._qvar1 = 5; } if (monster.mtalkmsg == TEXT_VILE13 && !effect_is_playing(USFX_LAZ1) && monster._mgoal == MGOAL_TALKING) { ObjChangeMapResync(1, 18, 20, 24); RedoPlayerVision(); Quests[Q_BETRAYER]._qvar1 = 6; monster._mgoal = MGOAL_NORMAL; monster._msquelch = UINT8_MAX; monster.mtalkmsg = TEXT_NONE; } } if (gbIsMultiplayer && monster.mtalkmsg == TEXT_VILE13 && monster._mgoal == MGOAL_INQUIRING && Quests[Q_BETRAYER]._qvar1 <= 3) { monster._mmode = MM_TALK; } } if (monster._mgoal == MGOAL_NORMAL || monster._mgoal == MGOAL_RETREAT || monster._mgoal == MGOAL_MOVE) { if (!gbIsMultiplayer && Quests[Q_BETRAYER]._qvar1 == 4 && monster.mtalkmsg == TEXT_NONE) { // Fix save games affected by teleport bug ObjChangeMapResync(1, 18, 20, 24); RedoPlayerVision(); Quests[Q_BETRAYER]._qvar1 = 6; } monster.mtalkmsg = TEXT_NONE; CounselorAi(i); } monster.CheckStandAnimationIsLoaded(md); } void LazarusMinionAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) return; int mx = monster.position.tile.x; int my = monster.position.tile.y; Direction md = GetMonsterDirection(monster); if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0) { if (!gbIsMultiplayer) { if (Quests[Q_BETRAYER]._qvar1 <= 5) { monster._mgoal = MGOAL_INQUIRING; } else { monster._mgoal = MGOAL_NORMAL; monster.mtalkmsg = TEXT_NONE; } } else monster._mgoal = MGOAL_NORMAL; } if (monster._mgoal == MGOAL_NORMAL) SuccubusAi(i); monster.CheckStandAnimationIsLoaded(md); } void LachdananAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; Direction md = GetMonsterDirection(monster); if (monster.mtalkmsg == TEXT_VEIL9 && (dFlags[mx][my] & BFLAG_VISIBLE) == 0 && monster._mgoal == MGOAL_TALKING) { monster.mtalkmsg = TEXT_VEIL10; monster._mgoal = MGOAL_INQUIRING; } if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0) { if (monster.mtalkmsg == TEXT_VEIL11) { if (!effect_is_playing(USFX_LACH3) && monster._mgoal == MGOAL_TALKING) { monster.mtalkmsg = TEXT_NONE; Quests[Q_VEIL]._qactive = QUEST_DONE; M_StartKill(i, -1); } } } monster.CheckStandAnimationIsLoaded(md); } void WarlordAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND) { return; } int mx = monster.position.tile.x; int my = monster.position.tile.y; Direction md = GetMonsterDirection(monster); if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0) { if (monster.mtalkmsg == TEXT_WARLRD9 && monster._mgoal == MGOAL_INQUIRING) monster._mmode = MM_TALK; if (monster.mtalkmsg == TEXT_WARLRD9 && !effect_is_playing(USFX_WARLRD1) && monster._mgoal == MGOAL_TALKING) { monster._msquelch = UINT8_MAX; monster.mtalkmsg = TEXT_NONE; monster._mgoal = MGOAL_NORMAL; } } if (monster._mgoal == MGOAL_NORMAL) SkeletonAi(i); monster.CheckStandAnimationIsLoaded(md); } void FirebatAi(int i) { AiRanged(i, MIS_FIREBOLT, false); } void TorchantAi(int i) { AiRanged(i, MIS_FIREBALL, false); } void HorkDemonAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mmode != MM_STAND || monster._msquelch == 0) { return; } int fx = monster.enemyPosition.x; int fy = monster.enemyPosition.y; int mx = monster.position.tile.x - fx; int my = monster.position.tile.y - fy; Direction md = GetDirection(monster.position.tile, monster.position.last); if (monster._msquelch < 255) { MonstCheckDoors(monster); } int v = GenerateRnd(100); if (abs(mx) < 2 && abs(my) < 2) { monster._mgoal = MGOAL_NORMAL; } else if (monster._mgoal == 4 || ((abs(mx) >= 5 || abs(my) >= 5) && GenerateRnd(4) != 0)) { if (monster._mgoal != 4) { monster._mgoalvar1 = 0; monster._mgoalvar2 = GenerateRnd(2); } monster._mgoal = MGOAL_MOVE; int dist = std::max(abs(mx), abs(my)); if (monster._mgoalvar1++ >= 2 * dist || dTransVal[monster.position.tile.x][monster.position.tile.y] != dTransVal[fx][fy]) { monster._mgoal = MGOAL_NORMAL; } else if (!RoundWalk(i, md, &monster._mgoalvar2)) { AiDelay(monster, GenerateRnd(10) + 10); } } if (monster._mgoal == 1) { if ((abs(mx) >= 3 || abs(my) >= 3) && v < 2 * monster._mint + 43) { Point position = monster.position.tile + monster._mdir; if (IsTileAvailable(monster, position) && ActiveMonsterCount < MAXMONSTERS) { StartRangedSpecialAttack(monster, MIS_HORKDMN, 0); } } else if (abs(mx) < 2 && abs(my) < 2) { if (v < 2 * monster._mint + 28) { monster._mdir = md; StartAttack(monster); } } else { v = GenerateRnd(100); if (v < 2 * monster._mint + 33 || ((monster._mVar1 == MM_WALK || monster._mVar1 == MM_WALK2 || monster._mVar1 == MM_WALK3) && monster._mVar2 == 0 && v < 2 * monster._mint + 83)) { RandomWalk(i, md); } else { AiDelay(monster, GenerateRnd(10) + 10); } } } monster.CheckStandAnimationIsLoaded(monster._mdir); } void LichAi(int i) { AiRanged(i, MIS_LICH, false); } void ArchLichAi(int i) { AiRanged(i, MIS_ARCHLICH, false); } void PsychorbAi(int i) { AiRanged(i, MIS_PSYCHORB, false); } void NecromorbAi(int i) { AiRanged(i, MIS_NECROMORB, false); } void BoneDemonAi(int i) { AiRangedAvoidance(i, MIS_BONEDEMON, true, 4, 0); } const char *GetMonsterTypeText(const MonsterDataStruct &monsterData) { switch (monsterData.mMonstClass) { case MC_ANIMAL: return _("Animal"); case MC_DEMON: return _("Demon"); case MC_UNDEAD: return _("Undead"); } app_fatal("Unknown mMonstClass %i", monsterData.mMonstClass); } void ActivateSpawn(int i, Point position, Direction dir) { auto &monster = Monsters[i]; dMonster[position.x][position.y] = i + 1; monster.position.tile = position; monster.position.future = position; monster.position.old = position; StartSpecialStand(monster, dir); } /** Maps from monster AI ID to monster AI function. */ void (*AiProc[])(int i) = { &ZombieAi, &OverlordAi, &SkeletonAi, &SkeletonBowAi, &ScavengerAi, &RhinoAi, &GoatAi, &GoatBowAi, &FallenAi, &MagmaAi, &LeoricAi, &BatAi, &GargoyleAi, &ButcherAi, &SuccubusAi, &SneakAi, &StormAi, nullptr, &GharbadAi, &AcidAvoidanceAi, &AcidAi, &GolumAi, &ZharAi, &SnotSpilAi, &SnakeAi, &CounselorAi, &MegaAi, &DiabloAi, &LazarusAi, &LazarusMinionAi, &LachdananAi, &WarlordAi, &FirebatAi, &TorchantAi, &HorkDemonAi, &LichAi, &ArchLichAi, &PsychorbAi, &NecromorbAi, &BoneDemonAi }; } // namespace void InitLevelMonsters() { LevelMonsterTypeCount = 0; monstimgtot = 0; for (auto &levelMonsterType : LevelMonsterTypes) { levelMonsterType.mPlaceFlags = 0; } ClrAllMonsters(); ActiveMonsterCount = 0; totalmonsters = MAXMONSTERS; for (int i = 0; i < MAXMONSTERS; i++) { ActiveMonsters[i] = i; } uniquetrans = 0; } void GetLevelMTypes() { // this array is merged with skeltypes down below. _monster_id typelist[MAXMONSTERS]; _monster_id skeltypes[NUM_MTYPES]; int minl; // min level int maxl; // max level char mamask; const int numskeltypes = 19; int nt; // number of types if (gbIsSpawn) mamask = 1; // monster availability mask else mamask = 3; // monster availability mask AddMonsterType(MT_GOLEM, PLACE_SPECIAL); if (currlevel == 16) { AddMonsterType(MT_ADVOCATE, PLACE_SCATTER); AddMonsterType(MT_RBLACK, PLACE_SCATTER); AddMonsterType(MT_DIABLO, PLACE_SPECIAL); return; } if (currlevel == 18) AddMonsterType(MT_HORKSPWN, PLACE_SCATTER); if (currlevel == 19) { AddMonsterType(MT_HORKSPWN, PLACE_SCATTER); AddMonsterType(MT_HORKDMN, PLACE_UNIQUE); } if (currlevel == 20) AddMonsterType(MT_DEFILER, PLACE_UNIQUE); if (currlevel == 24) { AddMonsterType(MT_ARCHLICH, PLACE_SCATTER); AddMonsterType(MT_NAKRUL, PLACE_SPECIAL); } if (!setlevel) { if (Quests[Q_BUTCHER].IsAvailable()) AddMonsterType(MT_CLEAVER, PLACE_SPECIAL); if (Quests[Q_GARBUD].IsAvailable()) AddMonsterType(UniqMonst[UMT_GARBUD].mtype, PLACE_UNIQUE); if (Quests[Q_ZHAR].IsAvailable()) AddMonsterType(UniqMonst[UMT_ZHAR].mtype, PLACE_UNIQUE); if (Quests[Q_LTBANNER].IsAvailable()) AddMonsterType(UniqMonst[UMT_SNOTSPIL].mtype, PLACE_UNIQUE); if (Quests[Q_VEIL].IsAvailable()) AddMonsterType(UniqMonst[UMT_LACHDAN].mtype, PLACE_UNIQUE); if (Quests[Q_WARLORD].IsAvailable()) AddMonsterType(UniqMonst[UMT_WARLORD].mtype, PLACE_UNIQUE); if (gbIsMultiplayer && currlevel == Quests[Q_SKELKING]._qlevel) { AddMonsterType(MT_SKING, PLACE_UNIQUE); nt = 0; for (int i = MT_WSKELAX; i <= MT_WSKELAX + numskeltypes; i++) { if (IsSkel(i)) { minl = 15 * MonsterData[i].mMinDLvl / 30 + 1; maxl = 15 * MonsterData[i].mMaxDLvl / 30 + 1; if (currlevel >= minl && currlevel <= maxl) { if ((MonstAvailTbl[i] & mamask) != 0) { skeltypes[nt++] = (_monster_id)i; } } } } AddMonsterType(skeltypes[GenerateRnd(nt)], PLACE_SCATTER); } nt = 0; for (int i = MT_NZOMBIE; i < NUM_MTYPES; i++) { minl = 15 * MonsterData[i].mMinDLvl / 30 + 1; maxl = 15 * MonsterData[i].mMaxDLvl / 30 + 1; if (currlevel >= minl && currlevel <= maxl) { if ((MonstAvailTbl[i] & mamask) != 0) { typelist[nt++] = (_monster_id)i; } } } #ifdef _DEBUG if (monstdebug) { for (int i = 0; i < debugmonsttypes; i++) AddMonsterType(DebugMonsters[i], PLACE_SCATTER); } else #endif { while (nt > 0 && LevelMonsterTypeCount < MAX_LVLMTYPES && monstimgtot < 4000) { for (int i = 0; i < nt;) { if (MonsterData[typelist[i]].mImage > 4000 - monstimgtot) { typelist[i] = typelist[--nt]; continue; } i++; } if (nt != 0) { int i = GenerateRnd(nt); AddMonsterType(typelist[i], PLACE_SCATTER); typelist[i] = typelist[--nt]; } } } } else { if (setlvlnum == SL_SKELKING) { AddMonsterType(MT_SKING, PLACE_UNIQUE); } } } void InitMonsterGFX(int monst) { int mtype = LevelMonsterTypes[monst].mtype; int width = MonsterData[mtype].width; for (int anim = 0; anim < 6; anim++) { int frames = MonsterData[mtype].Frames[anim]; if ((animletter[anim] != 's' || MonsterData[mtype].has_special) && frames > 0) { char strBuff[256]; sprintf(strBuff, MonsterData[mtype].GraphicType, animletter[anim]); byte *celBuf; { auto celData = LoadFileInMem(strBuff); celBuf = celData.get(); LevelMonsterTypes[monst].Anims[anim].CMem = std::move(celData); } if (LevelMonsterTypes[monst].mtype != MT_GOLEM || (animletter[anim] != 's' && animletter[anim] != 'd')) { for (int i = 0; i < 8; i++) { byte *pCelStart = CelGetFrame(celBuf, i); LevelMonsterTypes[monst].Anims[anim].CelSpritesForDirections[i].emplace(pCelStart, width); } } else { for (int i = 0; i < 8; i++) { LevelMonsterTypes[monst].Anims[anim].CelSpritesForDirections[i].emplace(celBuf, width); } } } LevelMonsterTypes[monst].Anims[anim].Frames = frames; LevelMonsterTypes[monst].Anims[anim].Rate = MonsterData[mtype].Rate[anim]; } LevelMonsterTypes[monst].mMinHP = MonsterData[mtype].mMinHP; LevelMonsterTypes[monst].mMaxHP = MonsterData[mtype].mMaxHP; if (!gbIsHellfire && mtype == MT_DIABLO) { LevelMonsterTypes[monst].mMinHP -= 2000; LevelMonsterTypes[monst].mMaxHP -= 2000; } LevelMonsterTypes[monst].mAFNum = MonsterData[mtype].mAFNum; LevelMonsterTypes[monst].MData = &MonsterData[mtype]; if (MonsterData[mtype].has_trans) { InitMonsterTRN(LevelMonsterTypes[monst]); } if (mtype >= MT_NMAGMA && mtype <= MT_WMAGMA) MissileSpriteData[MFILE_MAGBALL].LoadGFX(); if (mtype >= MT_STORM && mtype <= MT_MAEL) MissileSpriteData[MFILE_THINLGHT].LoadGFX(); if (mtype == MT_SNOWWICH) { MissileSpriteData[MFILE_SCUBMISB].LoadGFX(); MissileSpriteData[MFILE_SCBSEXPB].LoadGFX(); } if (mtype == MT_HLSPWN) { MissileSpriteData[MFILE_SCUBMISD].LoadGFX(); MissileSpriteData[MFILE_SCBSEXPD].LoadGFX(); } if (mtype == MT_SOLBRNR) { MissileSpriteData[MFILE_SCUBMISC].LoadGFX(); MissileSpriteData[MFILE_SCBSEXPC].LoadGFX(); } if ((mtype >= MT_NACID && mtype <= MT_XACID) || mtype == MT_SPIDLORD) { MissileSpriteData[MFILE_ACIDBF].LoadGFX(); MissileSpriteData[MFILE_ACIDSPLA].LoadGFX(); MissileSpriteData[MFILE_ACIDPUD].LoadGFX(); } if (mtype == MT_LICH) { MissileSpriteData[MFILE_LICH].LoadGFX(); MissileSpriteData[MFILE_EXORA1].LoadGFX(); } if (mtype == MT_ARCHLICH) { MissileSpriteData[MFILE_ARCHLICH].LoadGFX(); MissileSpriteData[MFILE_EXYEL2].LoadGFX(); } if (mtype == MT_PSYCHORB || mtype == MT_BONEDEMN) MissileSpriteData[MFILE_BONEDEMON].LoadGFX(); if (mtype == MT_NECRMORB) { MissileSpriteData[MFILE_NECROMORB].LoadGFX(); MissileSpriteData[MFILE_EXRED3].LoadGFX(); } if (mtype == MT_PSYCHORB) MissileSpriteData[MFILE_EXBL2].LoadGFX(); if (mtype == MT_BONEDEMN) MissileSpriteData[MFILE_EXBL3].LoadGFX(); if (mtype == MT_DIABLO) MissileSpriteData[MFILE_FIREPLAR].LoadGFX(); } void monster_some_crypt() { if (currlevel != 24 || UberDiabloMonsterIndex < 0 || UberDiabloMonsterIndex >= ActiveMonsterCount) return; auto &monster = Monsters[UberDiabloMonsterIndex]; PlayEffect(monster, 2); Quests[Q_NAKRUL]._qlog = false; monster.mArmorClass -= 50; int hp = monster._mmaxhp / 2; monster.mMagicRes = 0; monster._mhitpoints = hp; monster._mmaxhp = hp; } void InitMonsters() { if (!setlevel) { AddMonster(GolemHoldingCell, DIR_S, 0, false); AddMonster(GolemHoldingCell, DIR_S, 0, false); AddMonster(GolemHoldingCell, DIR_S, 0, false); AddMonster(GolemHoldingCell, DIR_S, 0, false); } if (!gbIsSpawn && !setlevel && currlevel == 16) LoadDiabMonsts(); int nt = numtrigs; if (currlevel == 15) nt = 1; for (int i = 0; i < nt; i++) { for (int s = -2; s < 2; s++) { for (int t = -2; t < 2; t++) DoVision(trigs[i].position + Displacement { s, t }, 15, false, false); } } if (!gbIsSpawn) PlaceQuestMonsters(); if (!setlevel) { if (!gbIsSpawn) PlaceUniqueMonsters(); int na = 0; for (int s = 16; s < 96; s++) { for (int t = 16; t < 96; t++) { if (!IsTileSolid({ s, t })) na++; } } int numplacemonsters = na / 30; if (gbIsMultiplayer) numplacemonsters += numplacemonsters / 2; if (ActiveMonsterCount + numplacemonsters > MAXMONSTERS - 10) numplacemonsters = MAXMONSTERS - 10 - ActiveMonsterCount; totalmonsters = ActiveMonsterCount + numplacemonsters; int numscattypes = 0; int scattertypes[NUM_MTYPES]; for (int i = 0; i < LevelMonsterTypeCount; i++) { if ((LevelMonsterTypes[i].mPlaceFlags & PLACE_SCATTER) != 0) { scattertypes[numscattypes] = i; numscattypes++; } } while (ActiveMonsterCount < totalmonsters) { int mtype = scattertypes[GenerateRnd(numscattypes)]; if (currlevel == 1 || GenerateRnd(2) == 0) na = 1; else if (currlevel == 2 || (currlevel >= 21 && currlevel <= 24)) na = GenerateRnd(2) + 2; else na = GenerateRnd(3) + 3; PlaceGroup(mtype, na, UniqueMonsterPack::None, 0); } } for (int i = 0; i < nt; i++) { for (int s = -2; s < 2; s++) { for (int t = -2; t < 2; t++) DoUnVision(trigs[i].position + Displacement { s, t }, 15); } } } void SetMapMonsters(const uint16_t *dunData, Point startPosition) { AddMonsterType(MT_GOLEM, PLACE_SPECIAL); AddMonster(GolemHoldingCell, DIR_S, 0, false); AddMonster(GolemHoldingCell, DIR_S, 0, false); AddMonster(GolemHoldingCell, DIR_S, 0, false); AddMonster(GolemHoldingCell, DIR_S, 0, false); if (setlevel && setlvlnum == SL_VILEBETRAYER) { AddMonsterType(UniqMonst[UMT_LAZARUS].mtype, PLACE_UNIQUE); AddMonsterType(UniqMonst[UMT_RED_VEX].mtype, PLACE_UNIQUE); AddMonsterType(UniqMonst[UMT_BLACKJADE].mtype, PLACE_UNIQUE); PlaceUniqueMonst(UMT_LAZARUS, 0, 0); PlaceUniqueMonst(UMT_RED_VEX, 0, 0); PlaceUniqueMonst(UMT_BLACKJADE, 0, 0); } int width = SDL_SwapLE16(dunData[0]); int height = SDL_SwapLE16(dunData[1]); int layer2Offset = 2 + width * height; // The rest of the layers are at dPiece scale width *= 2; height *= 2; const uint16_t *monsterLayer = &dunData[layer2Offset + width * height]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { uint8_t monsterId = SDL_SwapLE16(monsterLayer[j * width + i]); if (monsterId != 0) { int mtype = AddMonsterType(MonstConvTbl[monsterId - 1], PLACE_SPECIAL); PlaceMonster(ActiveMonsterCount++, mtype, i + startPosition.x + 16, j + startPosition.y + 16); } } } } int AddMonster(Point position, Direction dir, int mtype, bool inMap) { if (ActiveMonsterCount < MAXMONSTERS) { int i = ActiveMonsters[ActiveMonsterCount++]; if (inMap) dMonster[position.x][position.y] = i + 1; InitMonster(Monsters[i], dir, mtype, position); return i; } return -1; } void AddDoppelganger(MonsterStruct &monster) { if (monster.MType == nullptr) { return; } Point target = { 0, 0 }; for (int d = 0; d < 8; d++) { const Point position = monster.position.tile + static_cast<Direction>(d); if (!IsTileAvailable(position)) continue; target = position; } if (target != Point { 0, 0 }) { for (int j = 0; j < MAX_LVLMTYPES; j++) { if (LevelMonsterTypes[j].mtype == monster.MType->mtype) { AddMonster(target, monster._mdir, j, true); break; } } } } bool M_Talker(MonsterStruct &monster) { return IsAnyOf(monster._mAi, AI_LAZARUS, AI_WARLORD, AI_GARBUD, AI_ZHAR, AI_SNOTSPIL, AI_LACHDAN, AI_LAZHELP); } void M_StartStand(MonsterStruct &monster, Direction md) { ClearMVars(monster); if (monster.MType->mtype == MT_GOLEM) NewMonsterAnim(monster, MonsterGraphic::Walk, md); else NewMonsterAnim(monster, MonsterGraphic::Stand, md); monster._mVar1 = monster._mmode; monster._mVar2 = 0; monster._mmode = MM_STAND; monster.position.offset = { 0, 0 }; monster.position.future = monster.position.tile; monster.position.old = monster.position.tile; UpdateEnemy(monster); } void M_ClearSquares(int i) { auto &monster = Monsters[i]; int mx = monster.position.old.x; int my = monster.position.old.y; int m1 = -(i + 1); int m2 = i + 1; for (int y = my - 1; y <= my + 1; y++) { if (y >= 0 && y < MAXDUNY) { for (int x = mx - 1; x <= mx + 1; x++) { if (x >= 0 && x < MAXDUNX && (dMonster[x][y] == m1 || dMonster[x][y] == m2)) dMonster[x][y] = 0; } } } if (mx + 1 < MAXDUNX) dFlags[mx + 1][my] &= ~BFLAG_MONSTLR; if (my + 1 < MAXDUNY) dFlags[mx][my + 1] &= ~BFLAG_MONSTLR; } void M_GetKnockback(int i) { auto &monster = Monsters[i]; Direction d = opposite[monster._mdir]; if (!DirOK(i, d)) { return; } M_ClearSquares(i); monster.position.old += d; StartMonsterGotHit(i); } void M_StartHit(int i, int pnum, int dam) { auto &monster = Monsters[i]; if (pnum >= 0) monster.mWhoHit |= 1 << pnum; if (pnum == MyPlayerId) { delta_monster_hp(i, monster._mhitpoints, currlevel); NetSendCmdMonDmg(false, i, dam); } PlayEffect(monster, 1); if ((monster.MType->mtype >= MT_SNEAK && monster.MType->mtype <= MT_ILLWEAV) || dam >> 6 >= monster.mLevel + 3) { if (pnum >= 0) { monster._menemy = pnum; monster.enemyPosition = Players[pnum].position.future; monster._mFlags &= ~MFLAG_TARGETS_MONSTER; monster._mdir = GetMonsterDirection(monster); } if (monster.MType->mtype == MT_BLINK) { Teleport(i); } else if ((monster.MType->mtype >= MT_NSCAV && monster.MType->mtype <= MT_YSCAV) || monster.MType->mtype == MT_GRAVEDIG) { monster._mgoal = MGOAL_NORMAL; monster._mgoalvar1 = 0; monster._mgoalvar2 = 0; } if (monster._mmode != MM_STONE) { StartMonsterGotHit(i); } } } void M_StartKill(int i, int pnum) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (MyPlayerId == pnum) { delta_kill_monster(i, monster.position.tile, currlevel); if (i != pnum) { NetSendCmdLocParam1(false, CMD_MONSTDEATH, monster.position.tile, i); } else { NetSendCmdLocParam1(false, CMD_KILLGOLEM, monster.position.tile, currlevel); } } StartMonsterDeath(i, pnum, true); } void M_SyncStartKill(int i, Point position, int pnum) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; if (monster._mhitpoints == 0 || monster._mmode == MM_DEATH) { return; } if (dMonster[position.x][position.y] == 0) { M_ClearSquares(i); monster.position.tile = position; monster.position.old = position; } if (monster._mmode == MM_STONE) { StartMonsterDeath(i, pnum, false); monster.Petrify(); } else { StartMonsterDeath(i, pnum, false); } } void M_UpdateLeader(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; for (int j = 0; j < ActiveMonsterCount; j++) { auto &minion = Monsters[ActiveMonsters[j]]; if (minion.leaderRelation == LeaderRelation::Leashed && minion.leader == i) minion.leaderRelation = LeaderRelation::None; } if (monster.leaderRelation == LeaderRelation::Leashed) { Monsters[monster.leader].packsize--; } } void DoEnding() { if (gbIsMultiplayer) { SNetLeaveGame(LEAVE_ENDING); } music_stop(); if (gbIsMultiplayer) { SDL_Delay(1000); } if (gbIsSpawn) return; switch (Players[MyPlayerId]._pClass) { case HeroClass::Sorcerer: case HeroClass::Monk: play_movie("gendata\\DiabVic1.smk", false); break; case HeroClass::Warrior: case HeroClass::Barbarian: play_movie("gendata\\DiabVic2.smk", false); break; default: play_movie("gendata\\DiabVic3.smk", false); break; } play_movie("gendata\\Diabend.smk", false); bool bMusicOn = gbMusicOn; gbMusicOn = true; int musicVolume = sound_get_or_set_music_volume(1); sound_get_or_set_music_volume(0); music_start(TMUSIC_L2); loop_movie = true; play_movie("gendata\\loopdend.smk", true); loop_movie = false; music_stop(); sound_get_or_set_music_volume(musicVolume); gbMusicOn = bMusicOn; } void PrepDoEnding() { gbSoundOn = sgbSaveSoundOn; gbRunGame = false; MyPlayerIsDead = false; cineflag = true; auto &myPlayer = Players[MyPlayerId]; myPlayer.pDiabloKillLevel = std::max(myPlayer.pDiabloKillLevel, static_cast<uint8_t>(sgGameInitInfo.nDifficulty + 1)); for (auto &player : Players) { player._pmode = PM_QUIT; player._pInvincible = true; if (gbIsMultiplayer) { if (player._pHitPoints >> 6 == 0) player._pHitPoints = 64; if (player._pMana >> 6 == 0) player._pMana = 64; } } } void M_WalkDir(int i, Direction md) { assert(i >= 0 && i < MAXMONSTERS); int mwi = Monsters[i].MType->GetAnimData(MonsterGraphic::Walk).Frames - 1; switch (md) { case DIR_N: StartWalk(i, 0, -MWVel[mwi][1], -1, -1, DIR_N); break; case DIR_NE: StartWalk(i, MWVel[mwi][1], -MWVel[mwi][0], 0, -1, DIR_NE); break; case DIR_E: StartWalk3(i, MWVel[mwi][2], 0, -32, -16, 1, -1, 1, 0, DIR_E); break; case DIR_SE: StartWalk2(i, MWVel[mwi][1], MWVel[mwi][0], -32, -16, 1, 0, DIR_SE); break; case DIR_S: StartWalk2(i, 0, MWVel[mwi][1], 0, -32, 1, 1, DIR_S); break; case DIR_SW: StartWalk2(i, -MWVel[mwi][1], MWVel[mwi][0], 32, -16, 0, 1, DIR_SW); break; case DIR_W: StartWalk3(i, -MWVel[mwi][2], 0, 32, -16, -1, 1, 0, 1, DIR_W); break; case DIR_NW: StartWalk(i, -MWVel[mwi][1], -MWVel[mwi][0], -1, 0, DIR_NW); break; case DIR_OMNI: break; } } void GolumAi(int i) { assert(i >= 0 && i < MAXMONSTERS); auto &golem = Monsters[i]; if (golem.position.tile.x == 1 && golem.position.tile.y == 0) { return; } if (golem._mmode == MM_DEATH || golem._mmode == MM_SPSTAND || (golem._mmode >= MM_WALK && golem._mmode <= MM_WALK3)) { return; } if ((golem._mFlags & MFLAG_TARGETS_MONSTER) == 0) UpdateEnemy(golem); if (golem._mmode == MM_ATTACK) { return; } if ((golem._mFlags & MFLAG_NO_ENEMY) == 0) { auto &enemy = Monsters[golem._menemy]; int mex = golem.position.tile.x - enemy.position.future.x; int mey = golem.position.tile.y - enemy.position.future.y; golem._mdir = GetDirection(golem.position.tile, enemy.position.tile); if (abs(mex) < 2 && abs(mey) < 2) { golem.enemyPosition = enemy.position.tile; if (enemy._msquelch == 0) { enemy._msquelch = UINT8_MAX; enemy.position.last = golem.position.tile; for (int j = 0; j < 5; j++) { for (int k = 0; k < 5; k++) { int enemyId = dMonster[golem.position.tile.x + k - 2][golem.position.tile.y + j - 2]; // BUGFIX: Check if indexes are between 0 and 112 if (enemyId > 0) Monsters[enemyId - 1]._msquelch = UINT8_MAX; // BUGFIX: should be `Monsters[_menemy-1]`, not Monsters[_menemy]. (fixed) } } } StartAttack(golem); return; } if (AiPlanPath(i)) return; } golem._pathcount++; if (golem._pathcount > 8) golem._pathcount = 5; if (RandomWalk(i, Players[i]._pdir)) return; Direction md = left[golem._mdir]; bool ok = false; for (int j = 0; j < 8 && !ok; j++) { md = right[md]; ok = DirOK(i, md); } if (ok) M_WalkDir(i, md); } void DeleteMonsterList() { for (int i = 0; i < MAX_PLRS; i++) { auto &golem = Monsters[i]; if (!golem._mDelFlag) continue; golem.position.tile = GolemHoldingCell; golem.position.future = { 0, 0 }; golem.position.old = { 0, 0 }; golem._mDelFlag = false; } for (int i = MAX_PLRS; i < ActiveMonsterCount;) { if (Monsters[ActiveMonsters[i]]._mDelFlag) { if (pcursmonst == ActiveMonsters[i]) // Unselect monster if player highlighted it pcursmonst = -1; DeleteMonster(i); } else { i++; } } } void ProcessMonsters() { DeleteMonsterList(); assert(ActiveMonsterCount >= 0 && ActiveMonsterCount <= MAXMONSTERS); for (int i = 0; i < ActiveMonsterCount; i++) { int mi = ActiveMonsters[i]; auto &monster = Monsters[mi]; bool raflag = false; if (gbIsMultiplayer) { SetRndSeed(monster._mAISeed); monster._mAISeed = AdvanceRndSeed(); } if ((monster._mFlags & MFLAG_NOHEAL) == 0 && monster._mhitpoints < monster._mmaxhp && monster._mhitpoints >> 6 > 0) { if (monster.mLevel > 1) { monster._mhitpoints += monster.mLevel / 2; } else { monster._mhitpoints += monster.mLevel; } } int mx = monster.position.tile.x; int my = monster.position.tile.y; if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0 && monster._msquelch == 0) { if (monster.MType->mtype == MT_CLEAVER) { PlaySFX(USFX_CLEAVER); } if (monster.MType->mtype == MT_NAKRUL) { if (sgGameInitInfo.bCowQuest != 0) { PlaySFX(USFX_NAKRUL6); } else { if (IsUberRoomOpened) PlaySFX(USFX_NAKRUL4); else PlaySFX(USFX_NAKRUL5); } } if (monster.MType->mtype == MT_DEFILER) PlaySFX(USFX_DEFILER8); UpdateEnemy(monster); } if ((monster._mFlags & MFLAG_TARGETS_MONSTER) != 0) { assert(monster._menemy >= 0 && monster._menemy < MAXMONSTERS); monster.position.last = Monsters[monster._menemy].position.future; monster.enemyPosition = monster.position.last; } else { assert(monster._menemy >= 0 && monster._menemy < MAX_PLRS); auto &player = Players[monster._menemy]; monster.enemyPosition = player.position.future; if ((dFlags[mx][my] & BFLAG_VISIBLE) != 0) { monster._msquelch = UINT8_MAX; monster.position.last = player.position.future; } else if (monster._msquelch != 0 && monster.MType->mtype != MT_DIABLO) { /// BUGFIX: change '_mAi' to 'MType->mtype' monster._msquelch--; } } do { if ((monster._mFlags & MFLAG_SEARCH) == 0 || !AiPlanPath(mi)) { AiProc[monster._mAi](mi); } switch (monster._mmode) { case MM_STAND: raflag = MonsterIdle(monster); break; case MM_WALK: case MM_WALK2: case MM_WALK3: raflag = MonsterWalk(mi, monster._mmode); break; case MM_ATTACK: raflag = MonsterAttack(mi); break; case MM_GOTHIT: raflag = MonsterGotHit(monster); break; case MM_DEATH: raflag = MonsterDeath(mi); break; case MM_SATTACK: raflag = MonsterSpecialAttack(mi); break; case MM_FADEIN: raflag = MonsterFadein(monster); break; case MM_FADEOUT: raflag = MonsterFadeout(monster); break; case MM_RATTACK: raflag = MonaterRangedAttack(mi); break; case MM_SPSTAND: raflag = MonsterSpecialStand(monster); break; case MM_RSPATTACK: raflag = MonsterRangedSpecialAttack(mi); break; case MM_DELAY: raflag = MonsterDelay(monster); break; case MM_CHARGE: raflag = false; break; case MM_STONE: raflag = MonsterPetrified(monster); break; case MM_HEAL: raflag = MonsterHeal(monster); break; case MM_TALK: raflag = MonsterTalk(monster); break; } if (raflag) { GroupUnity(monster); } } while (raflag); if (monster._mmode != MM_STONE) { monster.AnimInfo.ProcessAnimation((monster._mFlags & MFLAG_LOCK_ANIMATION) != 0, (monster._mFlags & MFLAG_ALLOW_SPECIAL) != 0); } } DeleteMonsterList(); } void FreeMonsters() { for (int i = 0; i < LevelMonsterTypeCount; i++) { int mtype = LevelMonsterTypes[i].mtype; for (int j = 0; j < 6; j++) { if (animletter[j] != 's' || MonsterData[mtype].has_special) { LevelMonsterTypes[i].Anims[j].CMem = nullptr; } } } FreeMissiles2(); } bool DirOK(int i, Direction mdir) { assert(i >= 0 && i < MAXMONSTERS); auto &monster = Monsters[i]; Point position = monster.position.tile; Point futurePosition = position + mdir; if (futurePosition.y < 0 || futurePosition.y >= MAXDUNY || futurePosition.x < 0 || futurePosition.x >= MAXDUNX || !IsTileAvailable(monster, futurePosition)) return false; if (mdir == DIR_E) { if (IsTileSolid(position + DIR_SE) || (dFlags[position.x + 1][position.y] & BFLAG_MONSTLR) != 0) return false; } else if (mdir == DIR_W) { if (IsTileSolid(position + DIR_SW) || (dFlags[position.x][position.y + 1] & BFLAG_MONSTLR) != 0) return false; } else if (mdir == DIR_N) { if (IsTileSolid(position + DIR_NE) || IsTileSolid(position + DIR_NW)) return false; } else if (mdir == DIR_S) if (IsTileSolid(position + DIR_SW) || IsTileSolid(position + DIR_SE)) return false; if (monster.leaderRelation == LeaderRelation::Leashed) { return futurePosition.WalkingDistance(Monsters[monster.leader].position.future) < 4; } if (monster._uniqtype == 0 || UniqMonst[monster._uniqtype - 1].monsterPack != UniqueMonsterPack::Leashed) return true; int mcount = 0; for (int x = futurePosition.x - 3; x <= futurePosition.x + 3; x++) { for (int y = futurePosition.y - 3; y <= futurePosition.y + 3; y++) { if (y < 0 || y >= MAXDUNY || x < 0 || x >= MAXDUNX) continue; int mi = dMonster[x][y]; if (mi == 0) continue; auto &minion = Monsters[(mi < 0) ? -(mi + 1) : (mi - 1)]; if (minion.leaderRelation == LeaderRelation::Leashed && minion.leader == i && minion.position.future == Point { x, y }) { mcount++; } } } return mcount == monster.packsize; } bool PosOkMissile(Point position) { return !nMissileTable[dPiece[position.x][position.y]] && (dFlags[position.x][position.y] & BFLAG_MONSTLR) == 0; } bool LineClearMissile(Point startPoint, Point endPoint) { return LineClear(PosOkMissile, startPoint, endPoint); } bool LineClear(const std::function<bool(Point)> &clear, Point startPoint, Point endPoint) { Point position = startPoint; int dx = endPoint.x - position.x; int dy = endPoint.y - position.y; if (abs(dx) > abs(dy)) { if (dx < 0) { std::swap(position, endPoint); dx = -dx; dy = -dy; } int d; int yincD; int dincD; int dincH; if (dy > 0) { d = 2 * dy - dx; dincD = 2 * dy; dincH = 2 * (dy - dx); yincD = 1; } else { d = 2 * dy + dx; dincD = 2 * dy; dincH = 2 * (dx + dy); yincD = -1; } bool done = false; while (!done && position != endPoint) { if ((d <= 0) ^ (yincD < 0)) { d += dincD; } else { d += dincH; position.y += yincD; } position.x++; done = position != startPoint && !clear(position); } } else { if (dy < 0) { std::swap(position, endPoint); dy = -dy; dx = -dx; } int d; int xincD; int dincD; int dincH; if (dx > 0) { d = 2 * dx - dy; dincD = 2 * dx; dincH = 2 * (dx - dy); xincD = 1; } else { d = 2 * dx + dy; dincD = 2 * dx; dincH = 2 * (dy + dx); xincD = -1; } bool done = false; while (!done && position != endPoint) { if ((d <= 0) ^ (xincD < 0)) { d += dincD; } else { d += dincH; position.x += xincD; } position.y++; done = position != startPoint && !clear(position); } } return position == endPoint; } void SyncMonsterAnim(MonsterStruct &monster) { monster.MType = &LevelMonsterTypes[monster._mMTidx]; monster.MData = LevelMonsterTypes[monster._mMTidx].MData; if (monster._uniqtype != 0) monster.mName = _(UniqMonst[monster._uniqtype - 1].mName); else monster.mName = _(monster.MData->mName); int mdir = monster._mdir; MonsterGraphic graphic = MonsterGraphic::Stand; switch (monster._mmode) { case MM_STAND: case MM_DELAY: case MM_TALK: break; case MM_WALK: case MM_WALK2: case MM_WALK3: graphic = MonsterGraphic::Walk; break; case MM_ATTACK: case MM_RATTACK: graphic = MonsterGraphic::Attack; break; case MM_GOTHIT: graphic = MonsterGraphic::GotHit; break; case MM_DEATH: graphic = MonsterGraphic::Death; break; case MM_SATTACK: case MM_FADEIN: case MM_FADEOUT: case MM_SPSTAND: case MM_RSPATTACK: case MM_HEAL: graphic = MonsterGraphic::Special; break; case MM_CHARGE: graphic = MonsterGraphic::Attack; monster.AnimInfo.CurrentFrame = 1; monster.AnimInfo.NumberOfFrames = monster.MType->GetAnimData(MonsterGraphic::Attack).Frames; break; default: monster.AnimInfo.CurrentFrame = 1; monster.AnimInfo.NumberOfFrames = monster.MType->GetAnimData(MonsterGraphic::Stand).Frames; break; } if (monster.MType->GetAnimData(graphic).CelSpritesForDirections[mdir]) monster.AnimInfo.pCelSprite = &*monster.MType->GetAnimData(graphic).CelSpritesForDirections[mdir]; else monster.AnimInfo.pCelSprite = nullptr; } void M_FallenFear(Point position) { for (int i = 0; i < ActiveMonsterCount; i++) { auto &monster = Monsters[ActiveMonsters[i]]; if (monster._mAi != AI_FALLEN) continue; if (position.WalkingDistance(monster.position.tile) >= 5) continue; if (monster._mhitpoints >> 6 <= 0) continue; int rundist; switch (monster.MType->mtype) { case MT_RFALLSP: case MT_RFALLSD: rundist = 7; break; case MT_DFALLSP: case MT_DFALLSD: rundist = 5; break; case MT_YFALLSP: case MT_YFALLSD: rundist = 3; break; case MT_BFALLSP: case MT_BFALLSD: rundist = 2; break; default: continue; } monster._mgoal = MGOAL_RETREAT; monster._mgoalvar1 = rundist; monster._mgoalvar2 = GetDirection(position, monster.position.tile); } } void PrintMonstHistory(int mt) { if (sgOptions.Gameplay.bShowMonsterType) { strcpy(tempstr, fmt::format(_("Type: {:s} Kills: {:d}"), GetMonsterTypeText(MonsterData[mt]), MonsterKillCounts[mt]).c_str()); } else { strcpy(tempstr, fmt::format(_("Total kills: {:d}"), MonsterKillCounts[mt]).c_str()); } AddPanelString(tempstr); if (MonsterKillCounts[mt] >= 30) { int minHP = MonsterData[mt].mMinHP; int maxHP = MonsterData[mt].mMaxHP; if (!gbIsHellfire && mt == MT_DIABLO) { minHP -= 2000; maxHP -= 2000; } if (!gbIsMultiplayer) { minHP /= 2; maxHP /= 2; } if (minHP < 1) minHP = 1; if (maxHP < 1) maxHP = 1; int hpBonusNightmare = 1; int hpBonusHell = 3; if (gbIsHellfire) { hpBonusNightmare = (!gbIsMultiplayer ? 50 : 100); hpBonusHell = (!gbIsMultiplayer ? 100 : 200); } if (sgGameInitInfo.nDifficulty == DIFF_NIGHTMARE) { minHP = 3 * minHP + hpBonusNightmare; maxHP = 3 * maxHP + hpBonusNightmare; } else if (sgGameInitInfo.nDifficulty == DIFF_HELL) { minHP = 4 * minHP + hpBonusHell; maxHP = 4 * maxHP + hpBonusHell; } strcpy(tempstr, fmt::format(_("Hit Points: {:d}-{:d}"), minHP, maxHP).c_str()); AddPanelString(tempstr); } if (MonsterKillCounts[mt] >= 15) { int res = (sgGameInitInfo.nDifficulty != DIFF_HELL) ? MonsterData[mt].mMagicRes : MonsterData[mt].mMagicRes2; if ((res & (RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING)) == 0) { strcpy(tempstr, _("No magic resistance")); AddPanelString(tempstr); } else { if ((res & (RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING)) != 0) { strcpy(tempstr, _("Resists: ")); if ((res & RESIST_MAGIC) != 0) strcat(tempstr, _("Magic ")); if ((res & RESIST_FIRE) != 0) strcat(tempstr, _("Fire ")); if ((res & RESIST_LIGHTNING) != 0) strcat(tempstr, _("Lightning ")); tempstr[strlen(tempstr) - 1] = '\0'; AddPanelString(tempstr); } if ((res & (IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING)) != 0) { strcpy(tempstr, _("Immune: ")); if ((res & IMMUNE_MAGIC) != 0) strcat(tempstr, _("Magic ")); if ((res & IMMUNE_FIRE) != 0) strcat(tempstr, _("Fire ")); if ((res & IMMUNE_LIGHTNING) != 0) strcat(tempstr, _("Lightning ")); tempstr[strlen(tempstr) - 1] = '\0'; AddPanelString(tempstr); } } } } void PrintUniqueHistory() { auto &monster = Monsters[pcursmonst]; if (sgOptions.Gameplay.bShowMonsterType) { strcpy(tempstr, fmt::format(_("Type: {:s}"), GetMonsterTypeText(*monster.MData)).c_str()); AddPanelString(tempstr); } int res = monster.mMagicRes & (RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING | IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING); if (res == 0) { strcpy(tempstr, _("No resistances")); AddPanelString(tempstr); strcpy(tempstr, _("No Immunities")); } else { if ((res & (RESIST_MAGIC | RESIST_FIRE | RESIST_LIGHTNING)) != 0) strcpy(tempstr, _("Some Magic Resistances")); else strcpy(tempstr, _("No resistances")); AddPanelString(tempstr); if ((res & (IMMUNE_MAGIC | IMMUNE_FIRE | IMMUNE_LIGHTNING)) != 0) { strcpy(tempstr, _("Some Magic Immunities")); } else { strcpy(tempstr, _("No Immunities")); } } AddPanelString(tempstr); } void PlayEffect(MonsterStruct &monster, int mode) { #ifndef NOSOUND if (Players[MyPlayerId].pLvlLoad != 0) { return; } int sndIdx = GenerateRnd(2); if (!gbSndInited || !gbSoundOn || gbBufferMsgs != 0) { return; } int mi = monster._mMTidx; TSnd *snd = LevelMonsterTypes[mi].Snds[mode][sndIdx].get(); if (snd == nullptr || snd->isPlaying()) { return; } int lVolume = 0; int lPan = 0; if (!CalculateSoundPosition(monster.position.tile, &lVolume, &lPan)) return; snd_play_snd(snd, lVolume, lPan); #endif } void MissToMonst(int i, Point position) { assert(i >= 0 && i < MAXMISSILES); MissileStruct *miss = &Missiles[i]; int m = miss->_misource; assert(m >= 0 && m < MAXMONSTERS); auto &monster = Monsters[m]; Point oldPosition = miss->position.tile; dMonster[position.x][position.y] = m + 1; monster._mdir = static_cast<Direction>(miss->_mimfnum); monster.position.tile = position; M_StartStand(monster, monster._mdir); if (monster.MType->mtype < MT_INCIN || monster.MType->mtype > MT_HELLBURN) { if ((monster._mFlags & MFLAG_TARGETS_MONSTER) == 0) M_StartHit(m, -1, 0); else MonsterHitMonster(m, -1, 0); } else { StartFadein(monster, monster._mdir, false); } if ((monster._mFlags & MFLAG_TARGETS_MONSTER) == 0) { int pnum = dPlayer[oldPosition.x][oldPosition.y] - 1; if (dPlayer[oldPosition.x][oldPosition.y] > 0) { if (monster.MType->mtype != MT_GLOOM && (monster.MType->mtype < MT_INCIN || monster.MType->mtype > MT_HELLBURN)) { MonsterAttackPlayer(m, dPlayer[oldPosition.x][oldPosition.y] - 1, 500, monster.mMinDamage2, monster.mMaxDamage2); if (pnum == dPlayer[oldPosition.x][oldPosition.y] - 1 && (monster.MType->mtype < MT_NSNAKE || monster.MType->mtype > MT_GSNAKE)) { auto &player = Players[pnum]; if (player._pmode != PM_GOTHIT && player._pmode != PM_DEATH) StartPlrHit(pnum, 0, true); Point newPosition = oldPosition + monster._mdir; if (PosOkPlayer(player, newPosition)) { player.position.tile = newPosition; FixPlayerLocation(pnum, player._pdir); FixPlrWalkTags(pnum); dPlayer[newPosition.x][newPosition.y] = pnum + 1; SetPlayerOld(player); } } } } return; } if (dMonster[oldPosition.x][oldPosition.y] > 0) { if (monster.MType->mtype != MT_GLOOM && (monster.MType->mtype < MT_INCIN || monster.MType->mtype > MT_HELLBURN)) { MonsterAttackMonster(m, dMonster[oldPosition.x][oldPosition.y] - 1, 500, monster.mMinDamage2, monster.mMaxDamage2); if (monster.MType->mtype < MT_NSNAKE || monster.MType->mtype > MT_GSNAKE) { Point newPosition = oldPosition + monster._mdir; if (IsTileAvailable(Monsters[dMonster[oldPosition.x][oldPosition.y] - 1], newPosition)) { m = dMonster[oldPosition.x][oldPosition.y]; dMonster[newPosition.x][newPosition.y] = m; dMonster[oldPosition.x][oldPosition.y] = 0; m--; monster.position.tile = newPosition; monster.position.future = newPosition; } } } } } /** * @brief Check that the given tile is available to the monster */ bool IsTileAvailable(const MonsterStruct &monster, Point position) { if (!IsTileAvailable(position)) return false; return IsTileSafe(monster, position); } bool IsSkel(int mt) { return (mt >= MT_WSKELAX && mt <= MT_XSKELAX) || (mt >= MT_WSKELBW && mt <= MT_XSKELBW) || (mt >= MT_WSKELSD && mt <= MT_XSKELSD); } bool IsGoat(int mt) { return (mt >= MT_NGOATMC && mt <= MT_GGOATMC) || (mt >= MT_NGOATBW && mt <= MT_GGOATBW); } bool SpawnSkeleton(int ii, Point position) { if (ii == -1) return false; if (IsTileAvailable(position)) { Direction dir = GetDirection(position, position); // TODO useless calculation ActivateSpawn(ii, position, dir); return true; } bool monstok[3][3]; bool savail = false; int yy = 0; for (int j = position.y - 1; j <= position.y + 1; j++) { int xx = 0; for (int k = position.x - 1; k <= position.x + 1; k++) { monstok[xx][yy] = IsTileAvailable({ k, j }); savail = savail || monstok[xx][yy]; xx++; } yy++; } if (!savail) { return false; } int rs = GenerateRnd(15) + 1; int x2 = 0; int y2 = 0; while (rs > 0) { if (monstok[x2][y2]) rs--; if (rs > 0) { x2++; if (x2 == 3) { x2 = 0; y2++; if (y2 == 3) y2 = 0; } } } Point spawn = position + Displacement { x2 - 1, y2 - 1 }; Direction dir = GetDirection(spawn, position); ActivateSpawn(ii, spawn, dir); return true; } int PreSpawnSkeleton() { int skel = AddSkeleton({ 0, 0 }, DIR_S, false); if (skel != -1) M_StartStand(Monsters[skel], DIR_S); return skel; } void TalktoMonster(MonsterStruct &monster) { auto &player = Players[monster._menemy]; monster._mmode = MM_TALK; if (monster._mAi != AI_SNOTSPIL && monster._mAi != AI_LACHDAN) { return; } if (Quests[Q_LTBANNER].IsAvailable() && Quests[Q_LTBANNER]._qvar1 == 2) { if (player.TryRemoveInvItemById(IDI_BANNER)) { Quests[Q_LTBANNER]._qactive = QUEST_DONE; monster.mtalkmsg = TEXT_BANNER12; monster._mgoal = MGOAL_INQUIRING; } } if (Quests[Q_VEIL].IsAvailable() && monster.mtalkmsg >= TEXT_VEIL9) { if (player.TryRemoveInvItemById(IDI_GLDNELIX)) { monster.mtalkmsg = TEXT_VEIL11; monster._mgoal = MGOAL_INQUIRING; } } } void SpawnGolum(int i, Point position, int mi) { auto &missile = Missiles[mi]; assert(i >= 0 && i < MAX_PLRS); auto &player = Players[i]; auto &golem = Monsters[i]; dMonster[position.x][position.y] = i + 1; golem.position.tile = position; golem.position.future = position; golem.position.old = position; golem._pathcount = 0; golem._mmaxhp = 2 * (320 * missile._mispllvl + player._pMaxMana / 3); golem._mhitpoints = golem._mmaxhp; golem.mArmorClass = 25; golem.mHit = 5 * (missile._mispllvl + 8) + 2 * player._pLevel; golem.mMinDamage = 2 * (missile._mispllvl + 4); golem.mMaxDamage = 2 * (missile._mispllvl + 8); golem._mFlags |= MFLAG_GOLEM; StartSpecialStand(golem, DIR_S); UpdateEnemy(golem); if (i == MyPlayerId) { NetSendCmdGolem( golem.position.tile.x, golem.position.tile.y, golem._mdir, golem._menemy, golem._mhitpoints, currlevel); } } bool CanTalkToMonst(const MonsterStruct &monster) { return IsAnyOf(monster._mgoal, MGOAL_INQUIRING, MGOAL_TALKING); } bool CheckMonsterHit(MonsterStruct &monster, bool *ret) { if (monster._mAi == AI_GARG && (monster._mFlags & MFLAG_ALLOW_SPECIAL) != 0) { monster._mFlags &= ~MFLAG_ALLOW_SPECIAL; monster._mmode = MM_SATTACK; *ret = true; return true; } if (monster.MType->mtype >= MT_COUNSLR && monster.MType->mtype <= MT_ADVOCATE) { if (monster._mgoal != MGOAL_NORMAL) { *ret = false; return true; } } return false; } int encode_enemy(MonsterStruct &monster) { if ((monster._mFlags & MFLAG_TARGETS_MONSTER) != 0) return monster._menemy + MAX_PLRS; return monster._menemy; } void decode_enemy(MonsterStruct &monster, int enemy) { if (enemy < MAX_PLRS) { monster._mFlags &= ~MFLAG_TARGETS_MONSTER; monster._menemy = enemy; monster.enemyPosition = Players[enemy].position.future; } else { monster._mFlags |= MFLAG_TARGETS_MONSTER; enemy -= MAX_PLRS; monster._menemy = enemy; monster.enemyPosition = Monsters[enemy].position.future; } } void MonsterStruct::CheckStandAnimationIsLoaded(Direction mdir) { if (_mmode == MM_STAND || _mmode == MM_TALK) { _mdir = mdir; AnimInfo.pCelSprite = &*MType->GetAnimData(MonsterGraphic::Stand).CelSpritesForDirections[mdir]; } } void MonsterStruct::Petrify() { _mmode = MM_STONE; AnimInfo.IsPetrified = true; } bool MonsterStruct::IsWalking() const { switch (_mmode) { case MM_WALK: case MM_WALK2: case MM_WALK3: return true; default: return false; } } } // namespace devilution
29.471364
249
0.642456
[ "render" ]
8b38ba48cecac8a8c29d30d51566caf3d8b7549d
10,266
cpp
C++
yuusti/main.cpp
manarimo/ICFPC2021
f9a84a2ed312ac843056820db2349f97ac01c72c
[ "MIT" ]
null
null
null
yuusti/main.cpp
manarimo/ICFPC2021
f9a84a2ed312ac843056820db2349f97ac01c72c
[ "MIT" ]
null
null
null
yuusti/main.cpp
manarimo/ICFPC2021
f9a84a2ed312ac843056820db2349f97ac01c72c
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cmath> #include <vector> #include <algorithm> #include <fstream> #include <iostream> #include <set> #include "../cpp-lib/problem.h" #include "../cpp-lib/geo.h" #ifndef X #define X first #define Y second #endif using namespace std; using namespace manarimo; problem_t problem; bool stretch(const number &d1, const number &d2, const number epsilon) { return abs((d1 * 1. / d2 - 1)) * 1000000. < (epsilon + 1e-9); } int dfs(const vector<vector<double>> &fig_dist, const vector<vector<E>> &graph, const vector<P> hole, const vector<number> &hole_d, const vector<number> &edge_d, int v, int i, vector<int> &used, vector<int> &pos, number epsilon, int start, vector<vector<int>> &result, int threshold) { i %= hole_d.size(); if (i == start) { pos.push_back(v); result.push_back(pos); return pos.size(); } int best = pos.size(); if (pos.size() > threshold) { result.push_back(pos); } used[v] = true; pos.push_back(v); for (auto e: graph[v]) { int to = e.first; if (used[to]) continue; number len = edge_d[e.second]; if (stretch(hole_d[i], len, epsilon)) { bool valid = true; // TODO edakari naosu // int n = (i + hole.size() - start) % hole.size(); // for (int j = 0; j < n; ++j) { // int jj = (j + start) % hole.size(); // // cerr << endl << d(hole[jj], hole[i]) << endl; // cerr << fig_dist[pos[j]][to] << endl; // if (d(hole[jj], hole[i]) > fig_dist[pos[j]][to]) valid = false; // } if (valid) best = max(best, dfs(fig_dist, graph, hole, hole_d, edge_d, to, i + 1, used, pos, epsilon, start, result, threshold)); } } used[v] = false; pos.pop_back(); return best; } int place_triangle_dfs(problem_t &problem, const vector<vector<E>> &graph, const vector<P> &valid_points, vector<P> &figure, const number epsilon, vector<int> &relocated, vector<int> &connected, vector<P> &best_figure, int assigned = 0, int best_assigned = 0, int last_target = -1) { if (assigned > best_assigned) { best_assigned = assigned; best_figure = figure; } // find target int target = -1; int most_connected = 1; if (last_target != -1) { for (int i = 0; i < graph[last_target].size(); ++i) { int to = graph[last_target][i].first; if (relocated[to]) continue; if (most_connected < connected[to]) { most_connected = connected[to]; target = to; } } } for (int i = 0; i < connected.size(); ++i) { if (relocated[i]) continue; if (most_connected < connected[i]) { most_connected = connected[i]; target = i; } } if (target == -1) return assigned; cout << "Assigned: " << assigned << " Next target: " << target << " connected: " << connected[target] << endl; vector<pair<int, P>> adjacent; for (int i = 0; i < graph[target].size(); ++i) { int to = graph[target][i].first; ++connected[to]; if (relocated[to]) { adjacent.emplace_back(to, figure[to]); } } relocated[target] = 1; // calculate candidate positions of the new point vector<P> candidates; for (const P &p : valid_points) { bool ok = true; for (auto adj: adjacent) { if (!ok) break; if (problem.is_edge_inside(p, adj.second) && (stretch(d(adj.second, p), d(problem.figure.vertices[adj.first], problem.figure.vertices[target]), epsilon))) { for (P cand: candidates) { // TODO: come up with better way of sieving candidates if (abs(cand.first - p.first) + abs(cand.second - p.second) < (problem.max_x - problem.min_x + problem.max_y - problem.min_y) / 20) { ok = false; } } } else { ok = false; } } if (ok && candidates.size() < 3) candidates.push_back(p); } cout << "Found " << candidates.size() << " candidates" << endl; P reserve = figure[target]; for (P candidate: candidates) { figure[target] = candidate; cout << "Check candidate: (" << candidate.X << ", " << candidate.Y << ")" << endl; best_assigned = max(best_assigned, place_triangle_dfs(problem, graph, valid_points, figure, epsilon, relocated, connected, best_figure, assigned + 1, best_assigned, target)); } figure[target] = reserve; if (candidates.empty()) { cout << "skip -> Assigned: " << assigned << " Next target: " << target << " connected: " << connected[target] << endl; best_assigned = max(best_assigned, place_triangle_dfs(problem, graph, valid_points, figure, epsilon, relocated, connected, best_figure, assigned, best_assigned, target)); } for (int i = 0; i < graph[target].size(); ++i) { int to = graph[target][i].first; --connected[to]; } relocated[target] = 0; cout << "end -> Assigned: " << assigned << " Next target: " << target << " connected: " << connected[target] << endl; return best_assigned; } int main() { load_problem(cin, problem); vector<P> hole = problem.hole; vector<E> edge = problem.figure.edges; vector<P> figure = problem.figure.vertices; number epsilon = problem.epsilon; int n = figure.size(); vector<vector<E>> graph(n); for (int i = 0; i < edge.size(); i++) { graph[edge[i].first].emplace_back(edge[i].second, i); graph[edge[i].second].emplace_back(edge[i].first, i); } cout << n << endl; vector<number> hole_d; cout << "hole num: " << hole.size() << endl; for (int i = 0; i < hole.size(); ++i) { hole_d.push_back(d(hole[i], hole[(i + 1) % hole.size()])); if (i == 0) { cout << "hole 0: " << hole[i].X << ' ' << hole[i].Y << endl; } } vector<number> edge_d; for (int i = 0; i < edge.size(); i++) { edge_d.push_back(d(figure[edge[i].first], figure[edge[i].second])); } vector<int> matched(hole_d.size()); for (int i = 0; i < edge_d.size(); ++i) { for (int j = 0; j < hole_d.size(); ++j) { if (stretch(hole_d[j], edge_d[i], epsilon)) { matched[j]++; } } } // calc maximum distance vector<vector<double>> dist(n, vector<double>(n, 1e18)); for (int i = 0; i < edge.size(); ++i) dist[edge[i].first][edge[i].second] = dist[edge[i].second][edge[i].first] = sqrt(edge_d[i]) * 1.1; for (int i = 0; i < n; ++i) dist[i][i] = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) for (int k = 0; k < n; ++k) dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k]); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) dist[i][j] *= dist[i][j]; vector<int> best_fit(hole_d.size()); for (int i = 0; i < best_fit.size(); i++) { best_fit[i] = -1; } vector<int> best_len(hole_d.size()); for (int i = 0; i < figure.size(); ++i) { for (int j = 0; j < hole_d.size(); ++j) { vector<int> used(figure.size()); vector<int> pos; vector<vector<int>> result; int threshold = 3; int len = dfs(dist, graph, hole, hole_d, edge_d, i, j + 1, used, pos, epsilon, j, result, threshold); if (len > threshold) { cout << "\n\n" << threshold + 1 << "-" << len << endl; cout << "start hole:" << (j + 1) % hole_d.size() << endl; for (int k = 0; k < result.size(); ++k) { for (int l = 0; l < result[k].size(); ++l) { cout << result[k][l] << (l == result[k].size() ? "\n" : " "); } if (len == result[k].size()) { for (int l = 0; l < result[k].size(); l++) { int ii = (j + 1 + l) % hole_d.size(); if (best_len[ii] < len) { best_fit[ii] = result[k][l]; best_len[ii] = len; } } } cout << endl; } } } } cout << "BEST FIT" << endl; set<int> vused; vector<int> relocated(n); bool warn = false; for (int i = 0; i < best_fit.size(); i++) { cout << best_fit[i] << " "; if (best_fit[i] != -1) { figure[best_fit[i]] = hole[i]; relocated[best_fit[i]] = 1; } if (best_fit[i] != -1 && vused.find(best_fit[i]) != vused.end()) warn = true; vused.insert(best_fit[i]); } vector<int> connected(n); for (int i = 0; i < n; ++i) { if (!relocated[i]) continue; for (int j = 0; j < graph[i].size(); ++j) { int to = graph[i][j].first; ++connected[to]; } } vector<P> valid_points; for (number x = problem.min_x; x < problem.max_x; ++x) { for (number y = problem.min_y; y < problem.max_y; ++y) { if (problem.is_point_inside(make_pair(x, y))) valid_points.emplace_back(x, y); } } vector<P> best_figure = figure; int best = place_triangle_dfs(problem, graph, valid_points, figure, epsilon, relocated, connected, best_figure); cout << "\nAssigned " << best << " vertices" << endl; cout << endl; problem.output(best_figure); cout << endl; if (warn) { cout << "!!! The same vertex is assigned to multiple corners !!!" << endl; return 0; } }
33.116129
153
0.488214
[ "vector" ]
8b3b42e0d2906591aeb6f6c7c89859f0a45018be
61,258
cc
C++
extensions/browser/updater/extension_downloader.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
extensions/browser/updater/extension_downloader.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
extensions/browser/updater/extension_downloader.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/updater/extension_downloader.h" #include <stddef.h> #include <utility> #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/location.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/task/post_task.h" #include "base/time/time.h" #include "base/version.h" #include "components/crx_file/crx_verifier.h" #include "components/signin/public/identity_manager/access_token_info.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h" #include "components/signin/public/identity_manager/scope_set.h" #include "components/update_client/update_query_params.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "extensions/browser/extension_file_task_runner.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/notification_types.h" #include "extensions/browser/updater/extension_cache.h" #include "extensions/browser/updater/extension_downloader_test_delegate.h" #include "extensions/browser/updater/request_queue_impl.h" #include "extensions/common/extension_updater_uma.h" #include "extensions/common/extension_urls.h" #include "extensions/common/verifier_formats.h" #include "net/base/backoff_entry.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/http/http_status_code.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/simple_url_loader.h" using base::Time; using base::TimeDelta; using update_client::UpdateQueryParams; namespace extensions { namespace { const net::BackoffEntry::Policy kDefaultBackoffPolicy = { // Number of initial errors (in sequence) to ignore before applying // exponential back-off rules. 0, // Initial delay for exponential back-off in ms. 2000, // Factor by which the waiting time will be multiplied. 2, // Fuzzing percentage. ex: 10% will spread requests randomly // between 90%-100% of the calculated time. 0.1, // Maximum amount of time we are willing to delay our request in ms. 600000, // Ten minutes. // Time to keep an entry from being discarded even when it // has no significant state, -1 to never discard. -1, // Don't use initial delay unless the last request was an error. false, }; const char kAuthUserQueryKey[] = "authuser"; const int kMaxAuthUserValue = 10; const int kMaxOAuth2Attempts = 3; const char kNotFromWebstoreInstallSource[] = "notfromwebstore"; const char kDefaultInstallSource[] = ""; const char kReinstallInstallSource[] = "reinstall"; const char kGoogleDotCom[] = "google.com"; const char kTokenServiceConsumerId[] = "extension_downloader"; const char kWebstoreOAuth2Scope[] = "https://www.googleapis.com/auth/chromewebstore.readonly"; ExtensionDownloaderTestDelegate* g_test_delegate = nullptr; #define RETRY_HISTOGRAM(name, retry_count, url) \ if ((url).DomainIs(kGoogleDotCom)) { \ UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions." name "RetryCountGoogleUrl", \ retry_count, \ 1, \ kMaxRetries, \ kMaxRetries + 1); \ } else { \ UMA_HISTOGRAM_CUSTOM_COUNTS("Extensions." name "RetryCountOtherUrl", \ retry_count, \ 1, \ kMaxRetries, \ kMaxRetries + 1); \ } bool ShouldRetryRequest(const network::SimpleURLLoader* loader) { DCHECK(loader); // Since HTTP errors are now presented as ERR_HTTP_RESPONSE_CODE_FAILURE // by default, this will let both network and HTTP errors through. if (loader->NetError() == net::OK) return false; // If it failed without receiving response headers, retry. if (!loader->ResponseInfo() || !loader->ResponseInfo()->headers) return true; // If a response code was received, only retry on 5xx codes (server errors). int response_code = loader->ResponseInfo()->headers->response_code(); return response_code >= 500 && response_code < 600; } bool ShouldRetryRequestForExtensionNotFoundInCache(const int net_error_code) { return net_error_code == net::ERR_INTERNET_DISCONNECTED; } // This parses and updates a URL query such that the value of the |authuser| // query parameter is incremented by 1. If parameter was not present in the URL, // it will be added with a value of 1. All other query keys and values are // preserved as-is. Returns |false| if the user index exceeds a hard-coded // maximum. bool IncrementAuthUserIndex(GURL* url) { int user_index = 0; std::string old_query = url->query(); std::vector<std::string> new_query_parts; url::Component query(0, old_query.length()); url::Component key, value; while (url::ExtractQueryKeyValue(old_query.c_str(), &query, &key, &value)) { std::string key_string = old_query.substr(key.begin, key.len); std::string value_string = old_query.substr(value.begin, value.len); if (key_string == kAuthUserQueryKey) { base::StringToInt(value_string, &user_index); } else { new_query_parts.push_back(base::StringPrintf( "%s=%s", key_string.c_str(), value_string.c_str())); } } if (user_index >= kMaxAuthUserValue) return false; new_query_parts.push_back( base::StringPrintf("%s=%d", kAuthUserQueryKey, user_index + 1)); std::string new_query_string = base::JoinString(new_query_parts, "&"); url::Component new_query(0, new_query_string.size()); url::Replacements<char> replacements; replacements.SetQuery(new_query_string.c_str(), new_query); *url = url->ReplaceComponents(replacements); return true; } } // namespace const char ExtensionDownloader::kUpdateInteractivityHeader[] = "X-Goog-Update-Interactivity"; const char ExtensionDownloader::kUpdateAppIdHeader[] = "X-Goog-Update-AppId"; const char ExtensionDownloader::kUpdateUpdaterHeader[] = "X-Goog-Update-Updater"; const char ExtensionDownloader::kUpdateInteractivityForeground[] = "fg"; const char ExtensionDownloader::kUpdateInteractivityBackground[] = "bg"; UpdateDetails::UpdateDetails(const std::string& id, const base::Version& version) : id(id), version(version) {} UpdateDetails::~UpdateDetails() = default; ExtensionDownloader::ExtensionFetch::ExtensionFetch() : credentials(CREDENTIALS_NONE) {} ExtensionDownloader::ExtensionFetch::ExtensionFetch( const std::string& id, const GURL& url, const std::string& package_hash, const std::string& version, const std::set<int>& request_ids, const ManifestFetchData::FetchPriority fetch_priority) : id(id), url(url), package_hash(package_hash), version(version), request_ids(request_ids), fetch_priority(fetch_priority), credentials(CREDENTIALS_NONE), oauth2_attempt_count(0) {} ExtensionDownloader::ExtensionFetch::~ExtensionFetch() = default; ExtensionDownloader::FetchDataGroupKey::FetchDataGroupKey() = default; ExtensionDownloader::FetchDataGroupKey::FetchDataGroupKey( const FetchDataGroupKey& other) = default; ExtensionDownloader::FetchDataGroupKey::FetchDataGroupKey( const int request_id, const GURL& update_url, const bool is_force_installed) : request_id(request_id), update_url(update_url), is_force_installed(is_force_installed) {} ExtensionDownloader::FetchDataGroupKey::~FetchDataGroupKey() = default; bool ExtensionDownloader::FetchDataGroupKey::operator<( const FetchDataGroupKey& other) const { return std::tie(request_id, update_url, is_force_installed) < std::tie(other.request_id, other.update_url, other.is_force_installed); } ExtensionDownloader::ExtraParams::ExtraParams() : is_corrupt_reinstall(false) {} ExtensionDownloader::ExtensionDownloader( ExtensionDownloaderDelegate* delegate, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, const crx_file::VerifierFormat crx_format_requirement, const base::FilePath& profile_path) : delegate_(delegate), url_loader_factory_(std::move(url_loader_factory)), profile_path_for_url_loader_factory_(profile_path), manifests_queue_( &kDefaultBackoffPolicy, base::BindRepeating(&ExtensionDownloader::CreateManifestLoader, base::Unretained(this))), extensions_queue_( &kDefaultBackoffPolicy, base::BindRepeating(&ExtensionDownloader::CreateExtensionLoader, base::Unretained(this))), extension_cache_(nullptr), identity_manager_(nullptr), crx_format_requirement_(crx_format_requirement) { DCHECK(delegate_); DCHECK(url_loader_factory_); } ExtensionDownloader::~ExtensionDownloader() = default; bool ExtensionDownloader::AddPendingExtension( const std::string& id, const GURL& update_url, mojom::ManifestLocation install_location, bool is_corrupt_reinstall, int request_id, ManifestFetchData::FetchPriority fetch_priority) { // Use a zero version to ensure that a pending extension will always // be updated, and thus installed (assuming all extensions have // non-zero versions). return AddPendingExtensionWithVersion( id, update_url, install_location, is_corrupt_reinstall, request_id, fetch_priority, base::Version("0.0.0.0"), Manifest::TYPE_UNKNOWN, std::string()); } bool ExtensionDownloader::AddPendingExtensionWithVersion( const std::string& id, const GURL& update_url, mojom::ManifestLocation install_location, bool is_corrupt_reinstall, int request_id, ManifestFetchData::FetchPriority fetch_priority, base::Version version, Manifest::Type type, const std::string& update_url_data) { DCHECK(version.IsValid()); ExtraParams extra; if (is_corrupt_reinstall) extra.is_corrupt_reinstall = true; if (!update_url_data.empty()) extra.update_url_data = update_url_data; delegate_->OnExtensionDownloadStageChanged( id, ExtensionDownloaderDelegate::Stage::PENDING); return AddExtensionData(id, version, type, install_location, update_url, extra, request_id, fetch_priority); } void ExtensionDownloader::StartAllPending(ExtensionCache* cache) { if (cache) { extension_cache_ = cache; extension_cache_->Start( base::BindOnce(&ExtensionDownloader::DoStartAllPending, weak_ptr_factory_.GetWeakPtr())); } else { DoStartAllPending(); } } void ExtensionDownloader::DoStartAllPending() { ReportStats(); url_stats_ = URLStats(); for (auto it = fetches_preparing_.begin(); it != fetches_preparing_.end(); ++it) { std::vector<std::unique_ptr<ManifestFetchData>>& list = it->second; for (size_t i = 0; i < list.size(); ++i) StartUpdateCheck(std::move(list[i])); } fetches_preparing_.clear(); } void ExtensionDownloader::SetIdentityManager( signin::IdentityManager* identity_manager) { identity_manager_ = identity_manager; } // static void ExtensionDownloader::set_test_delegate( ExtensionDownloaderTestDelegate* delegate) { g_test_delegate = delegate; } void ExtensionDownloader::SetBackoffPolicyForTesting( const net::BackoffEntry::Policy* backoff_policy) { manifests_queue_.set_backoff_policy(backoff_policy); } bool ExtensionDownloader::AddExtensionData( const std::string& id, const base::Version& version, Manifest::Type extension_type, mojom::ManifestLocation extension_location, const GURL& extension_update_url, const ExtraParams& extra, int request_id, ManifestFetchData::FetchPriority fetch_priority) { GURL update_url(extension_update_url); // Skip extensions with non-empty invalid update URLs. if (!update_url.is_empty() && !update_url.is_valid()) { DLOG(WARNING) << "Extension " << id << " has invalid update url " << update_url; delegate_->OnExtensionDownloadStageChanged( id, ExtensionDownloaderDelegate::Stage::FINISHED); return false; } // Make sure we use SSL for store-hosted extensions. if (extension_urls::IsWebstoreUpdateUrl(update_url) && !update_url.SchemeIsCryptographic()) update_url = extension_urls::GetWebstoreUpdateUrl(); // Skip extensions with empty IDs. if (id.empty()) { DLOG(WARNING) << "Found extension with empty ID"; delegate_->OnExtensionDownloadStageChanged( id, ExtensionDownloaderDelegate::Stage::FINISHED); return false; } if (update_url.DomainIs(kGoogleDotCom)) { url_stats_.google_url_count++; } else if (update_url.is_empty()) { url_stats_.no_url_count++; // Fill in default update URL. update_url = extension_urls::GetWebstoreUpdateUrl(); } else { url_stats_.other_url_count++; } switch (extension_type) { case Manifest::TYPE_THEME: ++url_stats_.theme_count; break; case Manifest::TYPE_EXTENSION: case Manifest::TYPE_USER_SCRIPT: ++url_stats_.extension_count; break; case Manifest::TYPE_HOSTED_APP: case Manifest::TYPE_LEGACY_PACKAGED_APP: ++url_stats_.app_count; break; case Manifest::TYPE_PLATFORM_APP: ++url_stats_.platform_app_count; break; case Manifest::TYPE_UNKNOWN: default: ++url_stats_.pending_count; break; } DCHECK(!update_url.is_empty()); DCHECK(update_url.is_valid()); std::string install_source = extension_urls::IsWebstoreUpdateUrl(update_url) ? kDefaultInstallSource : kNotFromWebstoreInstallSource; if (extra.is_corrupt_reinstall) install_source = kReinstallInstallSource; ManifestFetchData::PingData ping_data; ManifestFetchData::PingData* optional_ping_data = NULL; if (delegate_->GetPingDataForExtension(id, &ping_data)) optional_ping_data = &ping_data; // Find or create a ManifestFetchData to add this extension to. bool added = false; bool is_new_extension_force_installed = extension_location == mojom::ManifestLocation::kExternalPolicyDownload; FetchDataGroupKey key(request_id, update_url, is_new_extension_force_installed); auto existing_iter = fetches_preparing_.find(key); if (existing_iter != fetches_preparing_.end() && !existing_iter->second.empty()) { // Try to add to the ManifestFetchData at the end of the list. ManifestFetchData* existing_fetch = existing_iter->second.back().get(); if (existing_fetch->AddExtension( id, version.GetString(), optional_ping_data, extra.update_url_data, install_source, extension_location, fetch_priority)) { added = true; } } if (!added) { // Otherwise add a new element to the list, if the list doesn't exist or // if its last element is already full. std::unique_ptr<ManifestFetchData> fetch( CreateManifestFetchData(update_url, request_id, fetch_priority)); ManifestFetchData* fetch_ptr = fetch.get(); if (is_new_extension_force_installed) fetch_ptr->set_is_all_external_policy_download(); fetches_preparing_[key].push_back(std::move(fetch)); added = fetch_ptr->AddExtension(id, version.GetString(), optional_ping_data, extra.update_url_data, install_source, extension_location, fetch_priority); DCHECK(added); } return true; } void ExtensionDownloader::ReportStats() const { UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckExtension", url_stats_.extension_count); UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckTheme", url_stats_.theme_count); UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckApp", url_stats_.app_count); UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckPackagedApp", url_stats_.platform_app_count); UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckPending", url_stats_.pending_count); UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckGoogleUrl", url_stats_.google_url_count); UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckOtherUrl", url_stats_.other_url_count); UMA_HISTOGRAM_COUNTS_100("Extensions.UpdateCheckNoUrl", url_stats_.no_url_count); } void ExtensionDownloader::StartUpdateCheck( std::unique_ptr<ManifestFetchData> fetch_data) { if (g_test_delegate) { g_test_delegate->StartUpdateCheck(this, delegate_, std::move(fetch_data)); return; } const ExtensionIdSet extension_ids = fetch_data->GetExtensionIds(); if (!ExtensionsBrowserClient::Get()->IsBackgroundUpdateAllowed()) { NotifyExtensionsDownloadStageChanged( extension_ids, ExtensionDownloaderDelegate::Stage::FINISHED); NotifyExtensionsDownloadFailed( extension_ids, fetch_data->request_ids(), ExtensionDownloaderDelegate::Error::DISABLED); return; } RequestQueue<ManifestFetchData>::iterator i; for (i = manifests_queue_.begin(); i != manifests_queue_.end(); ++i) { if (fetch_data->full_url() == i->full_url()) { // This url is already scheduled to be fetched. NotifyExtensionsDownloadStageChanged( extension_ids, ExtensionDownloaderDelegate::Stage::QUEUED_FOR_MANIFEST); i->Merge(*fetch_data); return; } } if (manifests_queue_.active_request() && manifests_queue_.active_request()->full_url() == fetch_data->full_url()) { NotifyExtensionsDownloadStageChanged( extension_ids, ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST); manifests_queue_.active_request()->Merge(*fetch_data); } else { UMA_HISTOGRAM_COUNTS_1M( "Extensions.UpdateCheckUrlLength", fetch_data->full_url().possibly_invalid_spec().length()); NotifyExtensionsDownloadStageChanged( extension_ids, ExtensionDownloaderDelegate::Stage::QUEUED_FOR_MANIFEST); manifests_queue_.ScheduleRequest(std::move(fetch_data)); } } network::mojom::URLLoaderFactory* ExtensionDownloader::GetURLLoaderFactoryToUse( const GURL& url) { if (!url.SchemeIsFile()) { DCHECK(url_loader_factory_); return url_loader_factory_.get(); } // For file:// URL support, since we only issue "no-cors" requests with this // factory, we can pass nullptr for the second argument. file_url_loader_factory_.Bind(content::CreateFileURLLoaderFactory( profile_path_for_url_loader_factory_, nullptr /* shared_cors_origin_access_list */)); return file_url_loader_factory_.get(); } void ExtensionDownloader::CreateManifestLoader() { const ManifestFetchData* active_request = manifests_queue_.active_request(); const ExtensionIdSet extension_ids = active_request->GetExtensionIds(); NotifyExtensionsDownloadStageChanged( extension_ids, ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST); std::vector<base::StringPiece> id_vector(extension_ids.begin(), extension_ids.end()); std::string id_list = base::JoinString(id_vector, ","); VLOG(2) << "Fetching " << active_request->full_url() << " for " << id_list; VLOG(2) << "Update interactivity: " << (active_request->foreground_check() ? kUpdateInteractivityForeground : kUpdateInteractivityBackground); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("extension_manifest_fetcher", R"( semantics { sender: "Extension Downloader" description: "Fetches information about an extension manifest (using its " "update_url, which is usually Chrome Web Store) in order to update " "the extension." trigger: "An update timer indicates that it's time to update extensions, or " "a user triggers an extension update flow." data: "The extension id, version and install source (the cause of the " "update flow). The client's OS, architecture, language, Chromium " "version, channel and a flag stating whether the request " "originated in the foreground or the background. Authentication is " "used only for non-Chrome-Web-Store update_urls." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "This feature cannot be disabled. It is only enabled when the user " "has installed extensions." chrome_policy { ExtensionInstallBlocklist { policy_options {mode: MANDATORY} ExtensionInstallBlocklist: { entries: '*' } } } })"); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = active_request->full_url(), resource_request->load_flags = net::LOAD_DISABLE_CACHE; if (active_request->fetch_priority() == ManifestFetchData::FetchPriority::FOREGROUND) { resource_request->priority = net::MEDIUM; } // Send traffic-management headers to the webstore, and omit credentials. // https://bugs.chromium.org/p/chromium/issues/detail?id=647516 if (extension_urls::IsWebstoreUpdateUrl(active_request->full_url())) { resource_request->headers.SetHeader(kUpdateInteractivityHeader, active_request->foreground_check() ? kUpdateInteractivityForeground : kUpdateInteractivityBackground); resource_request->headers.SetHeader(kUpdateAppIdHeader, id_list); resource_request->headers.SetHeader( kUpdateUpdaterHeader, base::StringPrintf( "%s-%s", UpdateQueryParams::GetProdIdString(UpdateQueryParams::CRX), UpdateQueryParams::GetProdVersion().c_str())); resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; } else { // Non-webstore sources may require HTTP auth. resource_request->credentials_mode = network::mojom::CredentialsMode::kInclude; resource_request->site_for_cookies = net::SiteForCookies::FromUrl(active_request->full_url()); } manifest_loader_ = network::SimpleURLLoader::Create( std::move(resource_request), traffic_annotation); // Update checks can be interrupted if a network change is detected; this is // common for the retail mode AppPack on ChromeOS. Retrying once should be // enough to recover in those cases; let the fetcher retry up to 3 times // just in case. http://crosbug.com/130602 const int kMaxRetries = 3; manifest_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RetryMode::RETRY_ON_NETWORK_CHANGE); network::mojom::URLLoaderFactory* url_loader_factory_to_use = GetURLLoaderFactoryToUse(active_request->full_url()); manifest_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( url_loader_factory_to_use, base::BindOnce(&ExtensionDownloader::OnManifestLoadComplete, base::Unretained(this))); } void ExtensionDownloader::RetryManifestFetchRequest() { constexpr base::TimeDelta backoff_delay; NotifyExtensionsDownloadStageChanged( manifests_queue_.active_request()->GetExtensionIds(), ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST_RETRY); manifests_queue_.RetryRequest(backoff_delay); } void ExtensionDownloader::ReportManifestFetchFailure( ManifestFetchData* fetch_data, ExtensionDownloaderDelegate::Error error, const ExtensionDownloaderDelegate::FailureData& data) { const ExtensionIdSet extension_ids = fetch_data->GetExtensionIds(); NotifyExtensionsDownloadStageChanged( extension_ids, ExtensionDownloaderDelegate::Stage::FINISHED); NotifyExtensionsDownloadFailedWithFailureData( extension_ids, fetch_data->request_ids(), error, data); } void ExtensionDownloader::TryFetchingExtensionsFromCache( ManifestFetchData* fetch_data, ExtensionDownloaderDelegate::Error error, const int net_error, const int response_code, const base::Optional<ManifestInvalidFailureDataList>& manifest_invalid_errors) { const ExtensionIdSet extension_ids = fetch_data->GetExtensionIds(); ExtensionIdSet extensions_fetched_from_cache; for (const auto& extension_id : extension_ids) { // Extension is fetched here only in cases when we fail to fetch the update // manifest or parsing of update manifest failed. In such cases, we don't // have expected version and expected hash. Thus, passing empty hash and // version would not be a problem as we only check for the expected hash and // version if we have them. auto extension_fetch_data(std::make_unique<ExtensionFetch>( extension_id, fetch_data->base_url(), /*hash not fetched*/ "", /*version not fetched*/ "", fetch_data->request_ids(), fetch_data->fetch_priority())); base::Optional<base::FilePath> cached_crx_path = GetCachedExtension( *extension_fetch_data, /*manifest_fetch_failed*/ true); if (cached_crx_path) { delegate_->OnExtensionDownloadStageChanged( extension_id, ExtensionDownloaderDelegate::Stage::FINISHED); NotifyDelegateDownloadFinished(std::move(extension_fetch_data), true, cached_crx_path.value(), false); extensions_fetched_from_cache.insert(extension_id); } } // All the extensions were found in the cache, no need to retry any request or // report failure. if (extensions_fetched_from_cache.size() == extension_ids.size()) return; fetch_data->RemoveExtensions(extensions_fetched_from_cache, manifest_query_params_); if (ShouldRetryRequestForExtensionNotFoundInCache(net_error)) { RetryManifestFetchRequest(); return; } if (error == ExtensionDownloaderDelegate::Error::MANIFEST_FETCH_FAILED) { ExtensionDownloaderDelegate::FailureData failure_data( -net_error, (net_error == net::Error::ERR_HTTP_RESPONSE_CODE_FAILURE) ? base::Optional<int>(response_code) : base::nullopt, manifests_queue_.active_request_failure_count()); ReportManifestFetchFailure(fetch_data, error, failure_data); return; } DCHECK(manifest_invalid_errors); ManifestInvalidFailureDataList errors_for_remaining_extensions; for (const auto& manifest_invalid_error : manifest_invalid_errors.value()) { if (!extensions_fetched_from_cache.count(manifest_invalid_error.first)) errors_for_remaining_extensions.push_back(manifest_invalid_error); } NotifyExtensionsDownloadStageChanged( fetch_data->GetExtensionIds(), ExtensionDownloaderDelegate::Stage::FINISHED); NotifyExtensionsManifestInvalidFailure(errors_for_remaining_extensions, fetch_data->request_ids()); } void ExtensionDownloader::RetryRequestOrHandleFailureOnManifestFetchFailure( const network::SimpleURLLoader* loader, const int response_code) { bool all_force_installed_extensions = manifests_queue_.active_request()->is_all_external_policy_download(); const int net_error = manifest_loader_->NetError(); const int request_failure_count = manifests_queue_.active_request_failure_count(); // If the device is offline, do not retry for force installed extensions, // try installing it from cache. Try fetching from cache only on first attempt // in this case, because we will retry the request only if there was no entry // in cache corresponding to this extension and there is no point in trying to // fetch extension from cache again. if (net_error == net::ERR_INTERNET_DISCONNECTED && all_force_installed_extensions && request_failure_count == 0) { TryFetchingExtensionsFromCache( manifests_queue_.active_request(), ExtensionDownloaderDelegate::Error::MANIFEST_FETCH_FAILED, net_error, response_code, base::nullopt /*manifest_invalid_errors*/); return; } if (ShouldRetryRequest(loader) && request_failure_count < kMaxRetries) { RetryManifestFetchRequest(); return; } const GURL url = loader->GetFinalURL(); RETRY_HISTOGRAM("ManifestFetchFailure", request_failure_count, url); if (all_force_installed_extensions) { TryFetchingExtensionsFromCache( manifests_queue_.active_request(), ExtensionDownloaderDelegate::Error::MANIFEST_FETCH_FAILED, net_error, response_code, base::nullopt /*manifest_invalid_errors*/); } else { ExtensionDownloaderDelegate::FailureData failure_data( -net_error, (net_error == net::Error::ERR_HTTP_RESPONSE_CODE_FAILURE) ? base::Optional<int>(response_code) : base::nullopt, request_failure_count); ReportManifestFetchFailure( manifests_queue_.active_request(), ExtensionDownloaderDelegate::Error::MANIFEST_FETCH_FAILED, failure_data); } } void ExtensionDownloader::OnManifestLoadComplete( std::unique_ptr<std::string> response_body) { const GURL url = manifest_loader_->GetFinalURL(); DCHECK(manifests_queue_.active_request()); int response_code = -1; if (manifest_loader_->ResponseInfo() && manifest_loader_->ResponseInfo()->headers) response_code = manifest_loader_->ResponseInfo()->headers->response_code(); VLOG(2) << response_code << " " << url; const int request_failure_count = manifests_queue_.active_request_failure_count(); // We want to try parsing the manifest, and if it indicates updates are // available, we want to fire off requests to fetch those updates. if (response_body && !response_body->empty()) { RETRY_HISTOGRAM("ManifestFetchSuccess", request_failure_count, url); VLOG(2) << "beginning manifest parse for " << url; NotifyExtensionsDownloadStageChanged( manifests_queue_.active_request()->GetExtensionIds(), ExtensionDownloaderDelegate::Stage::PARSING_MANIFEST); auto callback = base::BindOnce(&ExtensionDownloader::HandleManifestResults, weak_ptr_factory_.GetWeakPtr(), manifests_queue_.reset_active_request()); ParseUpdateManifest(*response_body, std::move(callback)); } else { VLOG(1) << "Failed to fetch manifest '" << url.possibly_invalid_spec() << "' response code:" << response_code; RetryRequestOrHandleFailureOnManifestFetchFailure(manifest_loader_.get(), response_code); } manifest_loader_.reset(); file_url_loader_factory_.reset(); manifests_queue_.reset_active_request(); // If we have any pending manifest requests, fire off the next one. manifests_queue_.StartNextRequest(); } void ExtensionDownloader::HandleManifestResults( std::unique_ptr<ManifestFetchData> fetch_data, std::unique_ptr<UpdateManifestResults> results, const base::Optional<ManifestParseFailure>& error) { if (!results) { VLOG(2) << "parsing manifest failed (" << fetch_data->full_url() << ")"; DCHECK(error.has_value()); ManifestInvalidFailureDataList manifest_invalid_errors; const ExtensionIdSet extension_ids = fetch_data->GetExtensionIds(); manifest_invalid_errors.reserve(extension_ids.size()); // If the manifest parsing failed for all the extensions with a common // error, add all extensions in the list with that error. for (const auto& extension_id : extension_ids) { manifest_invalid_errors.push_back(std::make_pair( extension_id, ExtensionDownloaderDelegate::FailureData(error.value().error))); } TryFetchingExtensionsFromCache( fetch_data.get(), ExtensionDownloaderDelegate::Error::MANIFEST_INVALID, 0 /*net_error_code*/, 0 /*response_code*/, manifest_invalid_errors); return; } else { VLOG(2) << "parsing manifest succeeded (" << fetch_data->full_url() << ")"; } const ExtensionIdSet extension_ids = fetch_data->GetExtensionIds(); NotifyExtensionsDownloadStageChanged( extension_ids, ExtensionDownloaderDelegate::Stage::MANIFEST_LOADED); std::vector<UpdateManifestResult*> to_update; std::set<std::string> no_updates; ManifestInvalidFailureDataList errors; // Examine the parsed manifest and kick off fetches of any new crx files. DetermineUpdates(*fetch_data, *results, &to_update, &no_updates, &errors); for (const UpdateManifestResult* update : to_update) { const std::string& extension_id = update->extension_id; GURL crx_url = update->crx_url; NotifyUpdateFound(extension_id, update->version); if (fetch_data->is_all_external_policy_download() && crx_url.is_empty()) { DCHECK_EQ(fetch_data->fetch_priority(), ManifestFetchData::FetchPriority::FOREGROUND); } FetchUpdatedExtension( std::make_unique<ExtensionFetch>( extension_id, crx_url, update->package_hash, update->version, fetch_data->request_ids(), fetch_data->fetch_priority()), update->info); } // If the manifest response included a <daystart> element, we want to save // that value for any extensions which had sent a ping in the request. if (fetch_data->base_url().DomainIs(kGoogleDotCom) && results->daystart_elapsed_seconds >= 0) { Time day_start = Time::Now() - TimeDelta::FromSeconds(results->daystart_elapsed_seconds); for (const ExtensionId& id : extension_ids) { ExtensionDownloaderDelegate::PingResult& result = ping_results_[id]; result.did_ping = fetch_data->DidPing(id, ManifestFetchData::ROLLCALL); result.day_start = day_start; } } NotifyExtensionsDownloadStageChanged( no_updates, ExtensionDownloaderDelegate::Stage::FINISHED); NotifyExtensionsDownloadFailed( no_updates, fetch_data->request_ids(), ExtensionDownloaderDelegate::Error::NO_UPDATE_AVAILABLE); ExtensionIdSet extension_ids_with_errors; for (const auto& error : errors) extension_ids_with_errors.insert(error.first); NotifyExtensionsDownloadStageChanged( extension_ids_with_errors, ExtensionDownloaderDelegate::Stage::FINISHED); NotifyExtensionsManifestInvalidFailure(errors, fetch_data->request_ids()); } ExtensionDownloader::UpdateAvailability ExtensionDownloader::GetUpdateAvailability( const std::string& extension_id, const std::vector<const UpdateManifestResult*>& possible_candidates, UpdateManifestResult** update_result_out) const { const bool is_extension_pending = delegate_->IsExtensionPending(extension_id); std::string extension_version; if (!is_extension_pending) { // If we're not installing pending extension, we can only update // extensions that have already existed in the system. if (!delegate_->GetExtensionExistingVersion(extension_id, &extension_version)) { VLOG(2) << extension_id << " is not installed"; return UpdateAvailability::kBadUpdateSpecification; } VLOG(2) << extension_id << " is at '" << extension_version << "'"; } bool has_noupdate = false; for (const UpdateManifestResult* update : possible_candidates) { const std::string& update_version_str = update->version; if (VLOG_IS_ON(2)) { if (update_version_str.empty()) VLOG(2) << "Manifest indicates " << extension_id << " has no update (info: " << update->info.value_or("no info") << ")"; else VLOG(2) << "Manifest indicates " << extension_id << " latest version is '" << update_version_str << "'"; } if (!is_extension_pending) { // If we're not installing pending extension, and the update // version is the same or older than what's already installed, // we don't want it. if (update_version_str.empty()) { // If update manifest doesn't have version number => no update. VLOG(2) << extension_id << " has empty version"; has_noupdate = true; continue; } const base::Version update_version(update_version_str); if (!update_version.IsValid()) { VLOG(2) << extension_id << " has invalid version '" << update_version_str << "'"; continue; } const base::Version existing_version(extension_version); if (update_version.CompareTo(existing_version) <= 0) { VLOG(2) << extension_id << " version is not older than '" << update_version_str << "'"; has_noupdate = true; continue; } } // If the update specifies a browser minimum version, do we qualify? if (update->browser_min_version.length() > 0 && !ExtensionsBrowserClient::Get()->IsMinBrowserVersionSupported( update->browser_min_version)) { // TODO(asargent) - We may want this to show up in the extensions UI // eventually. (http://crbug.com/12547). DLOG(WARNING) << "Updated version of extension " << extension_id << " available, but requires chrome version " << update->browser_min_version; has_noupdate = true; continue; } // Stop checking as soon as an update for |extension_id| is found. VLOG(2) << "Will try to update " << extension_id; *update_result_out = const_cast<UpdateManifestResult*>(update); return UpdateAvailability::kAvailable; } return has_noupdate ? UpdateAvailability::kNoUpdate : UpdateAvailability::kBadUpdateSpecification; } void ExtensionDownloader::DetermineUpdates( const ManifestFetchData& fetch_data, const UpdateManifestResults& possible_updates, std::vector<UpdateManifestResult*>* to_update, std::set<std::string>* no_updates, ManifestInvalidFailureDataList* errors) { DCHECK_NE(nullptr, to_update); DCHECK_NE(nullptr, no_updates); DCHECK_NE(nullptr, errors); // Group successful possible updates by extension IDs. const std::map<std::string, std::vector<const UpdateManifestResult*>> update_groups = possible_updates.GroupSuccessfulByID(); // Contains IDs of extensions which neither have successful update entry nor // are already inserted into |errors|. ExtensionIdSet extension_errors; const ExtensionIdSet extension_ids = fetch_data.GetExtensionIds(); // For each extensions in the current batch, greedily find an update from // |possible_updates|. for (const auto& extension_id : extension_ids) { const auto it = update_groups.find(extension_id); if (it == update_groups.end()) { VLOG(2) << "Manifest doesn't have an update entry for " << extension_id; extension_errors.insert(extension_id); continue; } const std::vector<const UpdateManifestResult*>& possible_candidates = it->second; DCHECK(!possible_candidates.empty()); VLOG(2) << "Manifest has " << possible_candidates.size() << " update entries for " << extension_id; UpdateManifestResult* update_result = nullptr; UpdateAvailability update_availability = GetUpdateAvailability( extension_id, possible_candidates, &update_result); switch (update_availability) { case UpdateAvailability::kAvailable: DCHECK_NE(nullptr, update_result); to_update->push_back(update_result); break; case UpdateAvailability::kNoUpdate: no_updates->insert(extension_id); break; case UpdateAvailability::kBadUpdateSpecification: errors->emplace_back(extension_id, ManifestInvalidError::BAD_UPDATE_SPECIFICATION); break; } } for (const auto& possible_update : possible_updates.update_list) { const ExtensionId& id = possible_update.extension_id; if (!extension_errors.count(id)) continue; DCHECK(possible_update.parse_error); ManifestInvalidError error_type = possible_update.parse_error.value().error; // Report any error corresponding to an extension. errors->emplace_back( id, error_type == ManifestInvalidError::BAD_APP_STATUS ? ExtensionDownloaderDelegate::FailureData( error_type, possible_update.app_status) : ExtensionDownloaderDelegate::FailureData(error_type)); extension_errors.erase(id); } // For the remaining extensions, we have missing ids. for (const auto& id : extension_errors) { errors->emplace_back(id, ExtensionDownloaderDelegate::FailureData( ManifestInvalidError::MISSING_APP_ID)); } } base::Optional<base::FilePath> ExtensionDownloader::GetCachedExtension( const ExtensionFetch& fetch_data, bool manifest_fetch_failed) { if (!extension_cache_) { delegate_->OnExtensionDownloadCacheStatusRetrieved( fetch_data.id, ExtensionDownloaderDelegate::CacheStatus::CACHE_DISABLED); return base::nullopt; } std::string version; if (!extension_cache_->GetExtension(fetch_data.id, fetch_data.package_hash, nullptr, &version)) { delegate_->OnExtensionDownloadCacheStatusRetrieved( fetch_data.id, ExtensionDownloaderDelegate::CacheStatus::CACHE_MISS); return base::nullopt; } // If manifest fetch is failed, we need not verify the version of the cache as // we will try to install the version present in the cache. if (!manifest_fetch_failed && fetch_data.version != base::Version(version)) { delegate_->OnExtensionDownloadCacheStatusRetrieved( fetch_data.id, ExtensionDownloaderDelegate::CacheStatus::CACHE_OUTDATED); return base::nullopt; } delegate_->OnExtensionDownloadCacheStatusRetrieved( fetch_data.id, manifest_fetch_failed ? ExtensionDownloaderDelegate::CacheStatus:: CACHE_HIT_ON_MANIFEST_FETCH_FAILURE : ExtensionDownloaderDelegate::CacheStatus::CACHE_HIT); base::FilePath crx_path; // Now get .crx file path. // TODO(https://crbug.com/1018271#c2) This has a side-effect in extension // cache implementation: extension in the cache will be marked as recently // used. extension_cache_->GetExtension(fetch_data.id, fetch_data.package_hash, &crx_path, &version); return std::move(crx_path); } // Begins (or queues up) download of an updated extension. void ExtensionDownloader::FetchUpdatedExtension( std::unique_ptr<ExtensionFetch> fetch_data, base::Optional<std::string> info) { if (!fetch_data->url.is_valid()) { // TODO(asargent): This can sometimes be invalid. See crbug.com/130881. DLOG(WARNING) << "Invalid URL: '" << fetch_data->url.possibly_invalid_spec() << "' for extension " << fetch_data->id; delegate_->OnExtensionDownloadStageChanged( fetch_data->id, ExtensionDownloaderDelegate::Stage::FINISHED); if (fetch_data->url.is_empty()) { // We expect to receive initialised |info| from the manifest parser in // case of no updates status in the update manifest. ExtensionDownloaderDelegate::FailureData data(info.value_or("")); NotifyExtensionsDownloadFailedWithFailureData( {fetch_data->id}, fetch_data->request_ids, ExtensionDownloaderDelegate::Error::CRX_FETCH_URL_EMPTY, data); } else { NotifyExtensionsDownloadFailed( {fetch_data->id}, fetch_data->request_ids, ExtensionDownloaderDelegate::Error::CRX_FETCH_URL_INVALID); } return; } for (RequestQueue<ExtensionFetch>::iterator iter = extensions_queue_.begin(); iter != extensions_queue_.end(); ++iter) { if (iter->id == fetch_data->id || iter->url == fetch_data->url) { delegate_->OnExtensionDownloadStageChanged( fetch_data->id, ExtensionDownloaderDelegate::Stage::QUEUED_FOR_CRX); iter->request_ids.insert(fetch_data->request_ids.begin(), fetch_data->request_ids.end()); return; // already scheduled } } if (extensions_queue_.active_request() && extensions_queue_.active_request()->url == fetch_data->url) { delegate_->OnExtensionDownloadStageChanged( fetch_data->id, ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX); extensions_queue_.active_request()->request_ids.insert( fetch_data->request_ids.begin(), fetch_data->request_ids.end()); return; } base::Optional<base::FilePath> cached_crx_path = GetCachedExtension(*fetch_data, /*manifest_fetch_failed*/ false); if (cached_crx_path) { delegate_->OnExtensionDownloadStageChanged( fetch_data->id, ExtensionDownloaderDelegate::Stage::FINISHED); NotifyDelegateDownloadFinished(std::move(fetch_data), true, cached_crx_path.value(), false); } else { delegate_->OnExtensionDownloadStageChanged( fetch_data->id, ExtensionDownloaderDelegate::Stage::QUEUED_FOR_CRX); extensions_queue_.ScheduleRequest(std::move(fetch_data)); } } void ExtensionDownloader::NotifyDelegateDownloadFinished( std::unique_ptr<ExtensionFetch> fetch_data, bool from_cache, const base::FilePath& crx_path, bool file_ownership_passed) { // Dereference required params before passing a scoped_ptr. const ExtensionId& id = fetch_data->id; const std::string& package_hash = fetch_data->package_hash; const GURL& url = fetch_data->url; const base::Version& version = fetch_data->version; const std::set<int>& request_ids = fetch_data->request_ids; const crx_file::VerifierFormat required_format = extension_urls::IsWebstoreUpdateUrl(fetch_data->url) ? GetWebstoreVerifierFormat(false) : crx_format_requirement_; CRXFileInfo crx_info(crx_path, required_format); crx_info.expected_hash = package_hash; crx_info.extension_id = id; crx_info.expected_version = version; delegate_->OnExtensionDownloadFinished( crx_info, file_ownership_passed, url, ping_results_[id], request_ids, from_cache ? base::BindOnce(&ExtensionDownloader::CacheInstallDone, weak_ptr_factory_.GetWeakPtr(), std::move(fetch_data)) : ExtensionDownloaderDelegate::InstallCallback()); if (!from_cache) ping_results_.erase(id); } void ExtensionDownloader::CacheInstallDone( std::unique_ptr<ExtensionFetch> fetch_data, bool should_download) { ping_results_.erase(fetch_data->id); if (should_download) { // Resume download from cached manifest data. extensions_queue_.ScheduleRequest(std::move(fetch_data)); } } void ExtensionDownloader::CreateExtensionLoader() { const ExtensionFetch* fetch = extensions_queue_.active_request(); delegate_->OnExtensionDownloadStageChanged( fetch->id, ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX); extension_loader_resource_request_ = std::make_unique<network::ResourceRequest>(); extension_loader_resource_request_->url = fetch->url; int load_flags = net::LOAD_DISABLE_CACHE; bool is_secure = fetch->url.SchemeIsCryptographic(); extension_loader_resource_request_->load_flags = load_flags; if (fetch->credentials != ExtensionFetch::CREDENTIALS_COOKIES || !is_secure) { extension_loader_resource_request_->credentials_mode = network::mojom::CredentialsMode::kOmit; } else { extension_loader_resource_request_->site_for_cookies = net::SiteForCookies::FromUrl(fetch->url); } if (fetch->credentials == ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN && is_secure) { if (access_token_.empty()) { // We should try OAuth2, but we have no token cached. This // ExtensionLoader will be started once the token fetch is complete, // in either OnTokenFetchSuccess or OnTokenFetchFailure. DCHECK(identity_manager_); signin::ScopeSet webstore_scopes; webstore_scopes.insert(kWebstoreOAuth2Scope); // It is safe to use Unretained(this) here given that the callback // will not be invoked if this object is deleted. access_token_fetcher_ = std::make_unique<signin::PrimaryAccountAccessTokenFetcher>( kTokenServiceConsumerId, identity_manager_, webstore_scopes, base::BindOnce(&ExtensionDownloader::OnAccessTokenFetchComplete, base::Unretained(this)), signin::PrimaryAccountAccessTokenFetcher::Mode::kImmediate); return; } extension_loader_resource_request_->headers.SetHeader( net::HttpRequestHeaders::kAuthorization, base::StringPrintf("Bearer %s", access_token_.c_str())); } VLOG(2) << "Starting load of " << fetch->url << " for " << fetch->id; StartExtensionLoader(); } void ExtensionDownloader::StartExtensionLoader() { net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("extension_crx_fetcher", R"( semantics { sender: "Extension Downloader" description: "Downloads an extension's crx file in order to update the " "extension, using update_url from the extension's manifest which " "is usually Chrome WebStore." trigger: "An update check indicates an extension update is available." data: "URL and required data to specify the extension to download. " "OAuth2 token is also sent if connection is secure and to Google." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "This feature cannot be disabled. It is only enabled when the user " "has installed extensions and it needs updating." chrome_policy { ExtensionInstallBlacklist { policy_options {mode: MANDATORY} ExtensionInstallBlacklist: { entries: '*' } } } })"); last_extension_loader_resource_request_headers_for_testing_ = extension_loader_resource_request_->headers; last_extension_loader_load_flags_for_testing_ = extension_loader_resource_request_->load_flags; const ExtensionFetch* active_request = extensions_queue_.active_request(); if (active_request->fetch_priority == ManifestFetchData::FetchPriority::FOREGROUND) { extension_loader_resource_request_->priority = net::MEDIUM; } network::mojom::URLLoaderFactory* url_loader_factory_to_use = GetURLLoaderFactoryToUse(extension_loader_resource_request_->url); extension_loader_ = network::SimpleURLLoader::Create( std::move(extension_loader_resource_request_), traffic_annotation); const int kMaxRetries = 3; extension_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RetryMode::RETRY_ON_NETWORK_CHANGE); extension_loader_->DownloadToTempFile( url_loader_factory_to_use, base::BindOnce(&ExtensionDownloader::OnExtensionLoadComplete, base::Unretained(this))); } void ExtensionDownloader::OnExtensionLoadComplete(base::FilePath crx_path) { GURL url = extension_loader_->GetFinalURL(); int net_error = extension_loader_->NetError(); int response_code = -1; if (extension_loader_->ResponseInfo() && extension_loader_->ResponseInfo()->headers) { response_code = extension_loader_->ResponseInfo()->headers->response_code(); } const base::TimeDelta& backoff_delay = base::TimeDelta::FromMilliseconds(0); ExtensionFetch& active_request = *extensions_queue_.active_request(); const ExtensionId& id = active_request.id; if (!crx_path.empty()) { RETRY_HISTOGRAM("CrxFetchSuccess", extensions_queue_.active_request_failure_count(), url); std::unique_ptr<ExtensionFetch> fetch_data = extensions_queue_.reset_active_request(); delegate_->OnExtensionDownloadStageChanged( id, ExtensionDownloaderDelegate::Stage::FINISHED); NotifyDelegateDownloadFinished(std::move(fetch_data), false, crx_path, true); } else if (IterateFetchCredentialsAfterFailure(&active_request, response_code)) { delegate_->OnExtensionDownloadStageChanged( id, ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX_RETRY); extensions_queue_.RetryRequest(backoff_delay); delegate_->OnExtensionDownloadRetryForTests(); } else { const std::set<int>& request_ids = active_request.request_ids; const ExtensionDownloaderDelegate::PingResult& ping = ping_results_[id]; VLOG(1) << "Failed to fetch extension '" << url.possibly_invalid_spec() << "' response code:" << response_code; if (ShouldRetryRequest(extension_loader_.get()) && extensions_queue_.active_request_failure_count() < kMaxRetries) { delegate_->OnExtensionDownloadStageChanged( id, ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX_RETRY); extensions_queue_.RetryRequest(backoff_delay); delegate_->OnExtensionDownloadRetryForTests(); } else { RETRY_HISTOGRAM("CrxFetchFailure", extensions_queue_.active_request_failure_count(), url); delegate_->OnExtensionDownloadStageChanged( id, ExtensionDownloaderDelegate::Stage::FINISHED); ExtensionDownloaderDelegate::FailureData failure_data( -net_error, (net_error == net::Error::ERR_HTTP_RESPONSE_CODE_FAILURE) ? base::Optional<int>(response_code) : base::nullopt, extensions_queue_.active_request_failure_count()); delegate_->OnExtensionDownloadFailed( id, ExtensionDownloaderDelegate::Error::CRX_FETCH_FAILED, ping, request_ids, failure_data); } ping_results_.erase(id); extensions_queue_.reset_active_request(); } extension_loader_.reset(); file_url_loader_factory_.reset(); // If there are any pending downloads left, start the next one. extensions_queue_.StartNextRequest(); } void ExtensionDownloader::NotifyExtensionsManifestInvalidFailure( const ManifestInvalidFailureDataList& errors, const std::set<int>& request_ids) { for (const auto& error_data : errors) { const ExtensionId& extension_id = error_data.first; ExtensionDownloaderDelegate::FailureData data = error_data.second; auto ping_iter = ping_results_.find(extension_id); delegate_->OnExtensionDownloadFailed( extension_id, ExtensionDownloaderDelegate::Error::MANIFEST_INVALID, ping_iter == ping_results_.end() ? ExtensionDownloaderDelegate::PingResult() : ping_iter->second, request_ids, data); ping_results_.erase(extension_id); } } void ExtensionDownloader::NotifyExtensionsDownloadStageChanged( ExtensionIdSet extension_ids, ExtensionDownloaderDelegate::Stage stage) { for (const auto& it : extension_ids) { delegate_->OnExtensionDownloadStageChanged(it, stage); } } void ExtensionDownloader::NotifyExtensionsDownloadFailed( ExtensionIdSet extension_ids, std::set<int> request_ids, ExtensionDownloaderDelegate::Error error) { NotifyExtensionsDownloadFailedWithFailureData( std::move(extension_ids), std::move(request_ids), error, ExtensionDownloaderDelegate::FailureData()); } void ExtensionDownloader::NotifyExtensionsDownloadFailedWithFailureData( ExtensionIdSet extension_ids, std::set<int> request_ids, ExtensionDownloaderDelegate::Error error, const ExtensionDownloaderDelegate::FailureData& data) { for (const auto& it : extension_ids) { auto ping_iter = ping_results_.find(it); delegate_->OnExtensionDownloadFailed( it, error, ping_iter == ping_results_.end() ? ExtensionDownloaderDelegate::PingResult() : ping_iter->second, request_ids, data); ping_results_.erase(it); } } void ExtensionDownloader::NotifyUpdateFound(const std::string& id, const std::string& version) { UpdateDetails updateInfo(id, base::Version(version)); content::NotificationService::current()->Notify( extensions::NOTIFICATION_EXTENSION_UPDATE_FOUND, content::NotificationService::AllBrowserContextsAndSources(), content::Details<UpdateDetails>(&updateInfo)); } bool ExtensionDownloader::IterateFetchCredentialsAfterFailure( ExtensionFetch* fetch, int response_code) { bool auth_failure = response_code == net::HTTP_UNAUTHORIZED || response_code == net::HTTP_FORBIDDEN; if (!auth_failure) { return false; } // Here we decide what to do next if the server refused to authorize this // fetch. switch (fetch->credentials) { case ExtensionFetch::CREDENTIALS_NONE: if (fetch->url.DomainIs(kGoogleDotCom) && identity_manager_) { fetch->credentials = ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN; } else { fetch->credentials = ExtensionFetch::CREDENTIALS_COOKIES; } return true; case ExtensionFetch::CREDENTIALS_OAUTH2_TOKEN: fetch->oauth2_attempt_count++; // OAuth2 may fail due to an expired access token, in which case we // should invalidate the token and try again. if (response_code == net::HTTP_UNAUTHORIZED && fetch->oauth2_attempt_count <= kMaxOAuth2Attempts) { DCHECK(identity_manager_); signin::ScopeSet webstore_scopes; webstore_scopes.insert(kWebstoreOAuth2Scope); identity_manager_->RemoveAccessTokenFromCache( identity_manager_->GetPrimaryAccountId(signin::ConsentLevel::kSync), webstore_scopes, access_token_); access_token_.clear(); return true; } // Either there is no Gaia identity available, the active identity // doesn't have access to this resource, or the server keeps returning // 401s and we've retried too many times. Fall back on cookies. if (access_token_.empty() || response_code == net::HTTP_FORBIDDEN || fetch->oauth2_attempt_count > kMaxOAuth2Attempts) { fetch->credentials = ExtensionFetch::CREDENTIALS_COOKIES; return true; } // Something else is wrong. Time to give up. return false; case ExtensionFetch::CREDENTIALS_COOKIES: if (response_code == net::HTTP_FORBIDDEN) { // Try the next session identity, up to some maximum. return IncrementAuthUserIndex(&fetch->url); } return false; default: NOTREACHED(); } NOTREACHED(); return false; } void ExtensionDownloader::OnAccessTokenFetchComplete( GoogleServiceAuthError error, signin::AccessTokenInfo token_info) { access_token_fetcher_.reset(); if (error.state() != GoogleServiceAuthError::NONE) { // If we fail to get an access token, kick the pending fetch and let it fall // back on cookies. StartExtensionLoader(); return; } access_token_ = token_info.token; extension_loader_resource_request_->headers.SetHeader( net::HttpRequestHeaders::kAuthorization, base::StringPrintf("Bearer %s", access_token_.c_str())); StartExtensionLoader(); } ManifestFetchData* ExtensionDownloader::CreateManifestFetchData( const GURL& update_url, int request_id, ManifestFetchData::FetchPriority fetch_priority) { ManifestFetchData::PingMode ping_mode = ManifestFetchData::NO_PING; if (update_url.DomainIs(ping_enabled_domain_.c_str())) ping_mode = ManifestFetchData::PING_WITH_ENABLED_STATE; return new ManifestFetchData(update_url, request_id, brand_code_, manifest_query_params_, ping_mode, fetch_priority); } } // namespace extensions
41.168011
91
0.702112
[ "object", "vector" ]
8b3e6965ada4b3037c6b91ab1b62412bb7b29f52
3,890
hpp
C++
Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/cartesian/point_in_box.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
24
2015-08-25T05:35:37.000Z
2020-10-24T14:21:59.000Z
Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/cartesian/point_in_box.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
97
2015-08-25T16:11:16.000Z
2019-03-17T00:54:32.000Z
Pods/GeoFeatures/GeoFeatures/boost/geometry/strategies/cartesian/point_in_box.hpp
xarvey/Yuuuuuge
9f4ec32f81cf813ea630ba2c44eb03970c56dad3
[ "Apache-2.0" ]
9
2015-08-26T03:11:38.000Z
2018-03-21T07:16:29.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_POINT_IN_BOX_HPP #define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_POINT_IN_BOX_HPP #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/coordinate_dimension.hpp> #include <boost/geometry/strategies/covered_by.hpp> #include <boost/geometry/strategies/within.hpp> namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace strategy { namespace within { struct within_range { template <typename Value1, typename Value2> static inline bool apply(Value1 const& value, Value2 const& min_value, Value2 const& max_value) { return value > min_value && value < max_value; } }; struct covered_by_range { template <typename Value1, typename Value2> static inline bool apply(Value1 const& value, Value2 const& min_value, Value2 const& max_value) { return value >= min_value && value <= max_value; } }; template < typename SubStrategy, typename Point, typename Box, std::size_t Dimension, std::size_t DimensionCount > struct relate_point_box_loop { static inline bool apply(Point const& point, Box const& box) { if (! SubStrategy::apply(get<Dimension>(point), get<min_corner, Dimension>(box), get<max_corner, Dimension>(box)) ) { return false; } return relate_point_box_loop < SubStrategy, Point, Box, Dimension + 1, DimensionCount >::apply(point, box); } }; template < typename SubStrategy, typename Point, typename Box, std::size_t DimensionCount > struct relate_point_box_loop<SubStrategy, Point, Box, DimensionCount, DimensionCount> { static inline bool apply(Point const& , Box const& ) { return true; } }; template < typename Point, typename Box, typename SubStrategy = within_range > struct point_in_box { static inline bool apply(Point const& point, Box const& box) { return relate_point_box_loop < SubStrategy, Point, Box, 0, dimension<Point>::type::value >::apply(point, box); } }; } // namespace within #ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS namespace within { namespace services { template <typename Point, typename Box> struct default_strategy < point_tag, box_tag, point_tag, areal_tag, cartesian_tag, cartesian_tag, Point, Box > { typedef within::point_in_box<Point, Box> type; }; }} // namespace within::services namespace covered_by { namespace services { template <typename Point, typename Box> struct default_strategy < point_tag, box_tag, point_tag, areal_tag, cartesian_tag, cartesian_tag, Point, Box > { typedef within::point_in_box < Point, Box, within::covered_by_range > type; }; }} // namespace covered_by::services #endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS }}} // namespace geofeatures_boost::geometry::strategy #endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_POINT_IN_BOX_HPP
22.485549
137
0.664524
[ "geometry" ]
8b3fd8bfc27b083ca51e836381ef63c204196d19
7,370
cc
C++
src/agent/jvm_eval_call_stack.cc
henrybell/cloud-debug-java
387a904d58260637c2433c2191395fd3d93cd765
[ "Apache-2.0" ]
null
null
null
src/agent/jvm_eval_call_stack.cc
henrybell/cloud-debug-java
387a904d58260637c2433c2191395fd3d93cd765
[ "Apache-2.0" ]
null
null
null
src/agent/jvm_eval_call_stack.cc
henrybell/cloud-debug-java
387a904d58260637c2433c2191395fd3d93cd765
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "jvm_eval_call_stack.h" #include <algorithm> #include "common.h" #include "jni_utils.h" #include "jvmti_buffer.h" DEFINE_FLAG( int32, cdbg_max_stack_depth, 20, "Maximum number of stack frames to unwind"); namespace devtools { namespace cdbg { void JvmEvalCallStack::Read(jthread thread, std::vector<JvmFrame>* result) { jvmtiError err = JVMTI_ERROR_NONE; result->clear(); // Block JvmtiOnCompiledMethodUnload as long as this function is executing. // This is to make sure Java methods don't get unloaded while this function // is executing. absl::MutexLock jmethods_reader_lock(&jmethods_mu_); // Load call stack through JVMTI. jint frames_count = 0; std::unique_ptr<jvmtiFrameInfo[]> frames( new jvmtiFrameInfo[base::GetFlag(FLAGS_cdbg_max_stack_depth)]); err = jvmti()->GetStackTrace( thread, 0, base::GetFlag(FLAGS_cdbg_max_stack_depth), frames.get(), &frames_count); if (err != JVMTI_ERROR_NONE) { LOG(ERROR) << "Failed to get stack trace, error: " << err; return; } // Evaluate all the call frames. for (int i = 0; i < frames_count; ++i) { result->push_back({ frames[i], DecodeFrame(frames[i]) }); } } const JvmEvalCallStack::FrameInfo& JvmEvalCallStack::ResolveCallFrameKey( int key) const { absl::MutexLock data_reader_lock(&data_mu_); DCHECK((key >= 0) && (key < frames_.size())); // The FrameInfo is immutable and never gets deleted (as long as this // instance is alive). Therefore it is safe to return pointer to it. return *frames_[key]; } int JvmEvalCallStack::InjectFrame(const FrameInfo& frame_info) { absl::MutexLock lock(&data_mu_); frames_.push_back(std::unique_ptr<FrameInfo>(new FrameInfo(frame_info))); return frames_.size() - 1; } // Note: JNIEnv* is not available through jni() call. void JvmEvalCallStack::JvmtiOnCompiledMethodUnload(jmethodID method) { absl::MutexLock jmethods_writer_lock(&jmethods_mu_); absl::MutexLock data_writer_lock(&data_mu_); method_cache_.erase(method); } int JvmEvalCallStack::DecodeFrame(const jvmtiFrameInfo& frame_info) { absl::MutexLock data_writer_lock(&data_mu_); // Fetch or load method information. auto in = method_cache_.insert( std::make_pair(frame_info.method, MethodCache())); MethodCache& method_cache = in.first->second; if (in.second) { // The method was not in cache, need to load it. LoadMethodCache(frame_info.method, &method_cache); } // Check whether the current frame location is already in cache. auto it_frames_cache = method_cache.frames_cache.find(frame_info.location); if (it_frames_cache == method_cache.frames_cache.end()) { FrameInfo* fi = new FrameInfo(); fi->class_signature = method_cache.class_signature; fi->class_generic = method_cache.class_generic; fi->method_name = method_cache.method_name; fi->source_file_name = method_cache.source_file_name; fi->line_number = GetMethodLocationLineNumber(frame_info); frames_.push_back(std::unique_ptr<FrameInfo>(fi)); const int key = frames_.size() - 1; it_frames_cache = method_cache.frames_cache.insert( method_cache.frames_cache.end(), std::make_pair(frame_info.location, key)); } return it_frames_cache->second; } void JvmEvalCallStack::LoadMethodCache( jmethodID method, MethodCache* method_cache) { jvmtiError err = JVMTI_ERROR_NONE; // Read method name. JvmtiBuffer<char> method_name; err = jvmti()->GetMethodName( method, method_name.ref(), nullptr, nullptr); if (err == JVMTI_ERROR_NONE) { method_cache->method_name = method_name.get(); } else { LOG(ERROR) << "GetMethodName failed, error: " << err; } // Read class information. jclass method_class = nullptr; err = jvmti()->GetMethodDeclaringClass(method, &method_class); if (err != JVMTI_ERROR_NONE) { LOG(ERROR) << "GetMethodDeclaringClass failed, error: " << err; method_class = nullptr; } JniLocalRef method_class_ref(method_class); if (method_class != nullptr) { // Class signature. JvmtiBuffer<char> class_signature; JvmtiBuffer<char> class_generic; err = jvmti()->GetClassSignature( method_class, class_signature.ref(), class_generic.ref()); if (err == JVMTI_ERROR_NONE) { method_cache->class_signature = class_signature.get(); if (class_generic.get() != nullptr) { method_cache->class_generic = class_generic.get(); } } else { LOG(ERROR) << "GetClassSignature failed, error: " << err; } // Source file name. JvmtiBuffer<char> source_file_name; jvmtiError err = jvmti()->GetSourceFileName( method_class, source_file_name.ref()); if (err == JVMTI_ERROR_NONE) { method_cache->source_file_name = source_file_name.get(); } else if (err == JVMTI_ERROR_ABSENT_INFORMATION) { LOG(WARNING) << "Class doesn't have source file debugging information"; } else if (err != JVMTI_ERROR_NONE) { LOG(ERROR) << "GetSourceFileName failed, error: " << err; } } } int JvmEvalCallStack::GetMethodLocationLineNumber( const jvmtiFrameInfo& frame_info) { jvmtiError err = JVMTI_ERROR_NONE; // Get the line numbers corresponding to the code statements of the method. jint line_entires_count = 0; JvmtiBuffer<jvmtiLineNumberEntry> line_entries; err = jvmti()->GetLineNumberTable( frame_info.method, &line_entires_count, line_entries.ref()); if (err == JVMTI_ERROR_NATIVE_METHOD) { return -1; } if (err == JVMTI_ERROR_ABSENT_INFORMATION) { LOG(WARNING) << "Class doesn't have line number debugging information"; return -1; } if (err != JVMTI_ERROR_NONE) { LOG(ERROR) << "GetLineNumberTable failed, error: " << err; return -1; } if (line_entires_count == 0) { LOG(WARNING) << "GetLineNumberTable returned empty set"; return -1; } // Find line_entries.start_location that is closest to frame_info.location // from the right side. The line numbers table is not necessarily sorted. const jvmtiLineNumberEntry* frame_entry = std::min_element( line_entries.get(), line_entries.get() + line_entires_count, [&frame_info] ( const jvmtiLineNumberEntry& e1, const jvmtiLineNumberEntry& e2) -> bool { // Cast to uint64 to overflow negative numbers. const uint64 diff1 = static_cast<uint64>(frame_info.location - e1.start_location); const uint64 diff2 = static_cast<uint64>(frame_info.location - e2.start_location); return diff1 < diff2; }); return frame_entry->line_number; } } // namespace cdbg } // namespace devtools
29.838057
77
0.694437
[ "vector" ]
8b43670b09445d0b28ea727d37a3e2c1a35263c3
20,635
cc
C++
src/builder.cc
marian-nmt/sentencepiece
c307b874deb5ea896db8f93506e173353e66d4d3
[ "Apache-2.0" ]
null
null
null
src/builder.cc
marian-nmt/sentencepiece
c307b874deb5ea896db8f93506e173353e66d4d3
[ "Apache-2.0" ]
5
2018-11-26T16:42:10.000Z
2021-08-02T10:51:04.000Z
src/builder.cc
marian-nmt/sentencepiece
c307b874deb5ea896db8f93506e173353e66d4d3
[ "Apache-2.0" ]
8
2020-09-03T10:46:11.000Z
2021-05-21T07:36:18.000Z
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License.! #include "builder.h" #include <algorithm> #include <functional> #include <utility> #include "filesystem.h" #include "third_party/absl/strings/str_join.h" #include "third_party/absl/strings/str_replace.h" #include "third_party/absl/strings/str_split.h" #include "third_party/absl/strings/strip.h" #ifdef ENABLE_NFKC_COMPILE #include <unicode/errorcode.h> #include <unicode/locid.h> #include <unicode/normlzr.h> #include <unicode/numfmt.h> #include <unicode/rbnf.h> #include <unicode/utypes.h> #endif // ENABLE_NFKC_COMPILE #include <set> #include "case_encoder.h" #include "normalization_rule.h" #include "normalizer.h" #include "third_party/darts_clone/darts.h" #include "util.h" namespace sentencepiece { namespace normalizer { namespace { constexpr int kMaxUnicode = 0x10FFFF; static constexpr char kDefaultNormalizerName[] = "nfkc"; #ifdef ENABLE_NFKC_COMPILE // Normalize `input` with ICU's normalizer with `mode`. Builder::Chars UnicodeNormalize(UNormalizationMode mode, const Builder::Chars &input) { const std::string utf8 = string_util::UnicodeTextToUTF8(input); CHECK(!utf8.empty()); icu::UnicodeString ustr = icu::UnicodeString::fromUTF8(utf8.c_str()); UErrorCode status = U_ZERO_ERROR; icu::UnicodeString dst; icu::Normalizer::normalize(ustr, mode, 0, dst, status); CHECK(U_SUCCESS(status)); std::string normalized; normalized.reserve(dst.length() * 3); dst.toUTF8String(normalized); return string_util::UTF8ToUnicodeText(normalized); } Builder::Chars ToNFKD(const Builder::Chars &input) { return UnicodeNormalize(UNORM_NFKD, input); } Builder::Chars ToNFKC(const Builder::Chars &input) { return UnicodeNormalize(UNORM_NFKC, input); } Builder::Chars ToNFC(const Builder::Chars &input) { return UnicodeNormalize(UNORM_NFC, input); } Builder::Chars ToNFD(const Builder::Chars &input) { return UnicodeNormalize(UNORM_NFD, input); } // Given an NFKD-normalized string, returns a set of all strings which are // normalized into the same `nfkd`. `norm2orig` is the normalized to // un-normalized character mapping. std::vector<Builder::Chars> ExpandUnnormalized( const Builder::Chars &nfkd, const std::map<char32, std::set<char32>> &norm2orig) { CHECK(!nfkd.empty()); std::vector<Builder::Chars> results; for (const auto c : port::FindOrDie(norm2orig, nfkd[0])) { results.push_back({c}); } for (size_t i = 1; i < nfkd.size(); ++i) { const auto &orig = port::FindOrDie(norm2orig, nfkd[i]); std::vector<Builder::Chars> new_results; for (const auto &r : results) { for (const auto c : orig) { new_results.emplace_back(r); new_results.back().push_back(c); } } results = std::move(new_results); } CHECK_EQ(nfkd.size(), results[0].size()); return results; } #endif // Normalizes `src` with `chars_map` and returns normalized Chars. // `max_len` specifies the maximum length of the key in `chars_map`. Builder::Chars Normalize(const Builder::CharsMap &chars_map, const Builder::Chars &src, int max_len) { CHECK_GE(max_len, 1); Builder::Chars normalized; for (size_t i = 0; i < src.size();) { Builder::CharsMap::const_iterator it = chars_map.end(); const size_t slice = std::min<size_t>(i + max_len, src.size()); // starts with the longest prefix. Builder::Chars key(src.begin() + i, src.begin() + slice); while (!key.empty()) { it = chars_map.find(key); if (it != chars_map.end()) { break; } key.pop_back(); // remove the last character. } // Consumes one character when no rule is found. if (it == chars_map.end()) { normalized.push_back(src[i]); ++i; } else { std::copy(it->second.begin(), it->second.end(), std::back_inserter(normalized)); i += it->first.size(); } } return normalized; } } // namespace // static util::Status Builder::CompileCharsMap(const CharsMap &chars_map, std::string *output) { CHECK_OR_RETURN(output); CHECK_OR_RETURN(!chars_map.empty()); LOG(INFO) << "Loading CharsMap of size=" << chars_map.size(); // Aggregates the same target strings to save footprint. std::map<Chars, int> normalized2pos; for (const auto &p : chars_map) { normalized2pos[p.second] = 0; } std::string normalized; for (auto &p : normalized2pos) { p.second = normalized.size(); // stores the pointer (position). const std::string utf8_out = string_util::UnicodeTextToUTF8(p.first); CHECK_OR_RETURN(string_util::IsStructurallyValid(utf8_out)); normalized += utf8_out; normalized += '\0'; } std::vector<std::pair<std::string, int>> kv; // key-value of Trie. for (const auto &p : chars_map) { // The value of Trie stores the pointer to the normalized string. const std::string utf8_in = string_util::UnicodeTextToUTF8(p.first); CHECK_OR_RETURN(!utf8_in.empty()); CHECK_OR_RETURN(string_util::IsStructurallyValid(utf8_in)); kv.emplace_back(utf8_in, port::FindOrDie(normalized2pos, p.second)); } std::sort(kv.begin(), kv.end()); std::vector<const char *> key(kv.size()); std::vector<int> value(kv.size()); for (size_t i = 0; i < kv.size(); ++i) { key[i] = kv[i].first.c_str(); value[i] = kv[i].second; } Darts::DoubleArray trie; CHECK_EQ_OR_RETURN(0, trie.build(key.size(), const_cast<char **>(&key[0]), nullptr, &value[0])) << "cannot build double-array"; int max_nodes_size = 0; std::vector<Darts::DoubleArray::result_pair_type> results( 2 * Normalizer::kMaxTrieResultsSize); for (const char *str : key) { const int num_nodes = trie.commonPrefixSearch(str, results.data(), results.size(), strlen(str)); max_nodes_size = std::max(num_nodes, max_nodes_size); } CHECK_LT_OR_RETURN(max_nodes_size, Normalizer::kMaxTrieResultsSize) << "This charmaps contain many shared prefix. " << "The number of shared prefix must be less than " << Normalizer::kMaxTrieResultsSize; absl::string_view trie_blob(static_cast<const char *>(trie.array()), trie.size() * trie.unit_size()); *output = Normalizer::EncodePrecompiledCharsMap(trie_blob, normalized); LOG(INFO) << "Generated normalizer blob. size=" << output->size(); return util::OkStatus(); } // static util::Status Builder::DecompileCharsMap(absl::string_view blob, Builder::CharsMap *chars_map) { CHECK_OR_RETURN(chars_map); chars_map->clear(); absl::string_view trie_blob, normalized; std::string buf; RETURN_IF_ERROR(Normalizer::DecodePrecompiledCharsMap(blob, &trie_blob, &normalized, &buf)); Darts::DoubleArray trie; trie.set_array(const_cast<char *>(trie_blob.data()), trie_blob.size() / trie.unit_size()); std::string key; std::function<void(size_t, size_t)> traverse; // Given a Trie node at `node_pos` and the key position at `key_position`, // Expands children nodes from `node_pos`. // When leaf nodes are found, stores them into `chars_map`. traverse = [&traverse, &key, &trie, &normalized, &chars_map]( size_t node_pos, size_t key_pos) -> void { for (int c = 0; c <= 255; ++c) { key.push_back(static_cast<char>(c)); size_t copied_node_pos = node_pos; size_t copied_key_pos = key_pos; // Note: `copied_(node|key)_pos` are non-const references. // They store the new positions after node traversal. const Darts::DoubleArray::result_type result = trie.traverse( key.data(), copied_node_pos, copied_key_pos, key.size()); if (result >= -1) { // node exists. if (result >= 0) { // has a value after transition. const absl::string_view value = normalized.data() + result; Chars key_chars, value_chars; for (const auto c : string_util::UTF8ToUnicodeText(key)) key_chars.push_back(c); for (const auto c : string_util::UTF8ToUnicodeText(value)) value_chars.push_back(c); (*chars_map)[key_chars] = value_chars; } // Recursively traverse. traverse(copied_node_pos, copied_key_pos); } key.pop_back(); } }; traverse(0, 0); return util::OkStatus(); } // static util::Status Builder::GetPrecompiledCharsMap(const std::string &name, std::string *output) { CHECK_OR_RETURN(output); if (name == "identity") { output->clear(); return util::OkStatus(); } std::string result; for (size_t i = 0; i < kNormalizationRules_size; ++i) { const auto *blob = &kNormalizationRules_blob[i]; if (blob->name == name) { output->assign(blob->data, blob->size); return util::OkStatus(); } } return util::StatusBuilder(util::StatusCode::kNotFound, GTL_LOC) << "No precompiled charsmap is found: " << name; } // static util::Status Builder::BuildNFKCMap(CharsMap *chars_map) { #ifdef ENABLE_NFKC_COMPILE LOG(INFO) << "Running BuildNFKCMap"; // Set of fully NFKD decomposed characters. std::set<Builder::Chars> nfkd_decomposed; // Fully normalized one character to unnormalized one character map. std::map<char32, std::set<char32>> norm2orig; Builder::CharsMap nfkc_map; // The final NFKC mapping. constexpr int kMaxUnicode = 0x10FFFF; for (char32 cp = 1; cp <= kMaxUnicode; ++cp) { if (!U_IS_UNICODE_CHAR(cp)) { continue; } // Aggregates single character to fully NFKC normalized characters. const auto nfkc = ToNFKC({cp}); if (nfkc.size() >= 2 || (nfkc.size() == 1 && nfkc[0] != cp)) { nfkc_map[{cp}] = nfkc; } const auto nfkd = ToNFKD({cp}); if (nfkd.size() == 1) { // Aggregates reverse mapping from normalized to unnormalized character. norm2orig[nfkd[0]].insert(cp); } else { // One character is decomposed into multiple characters. nfkd_decomposed.insert(nfkd); } } for (const auto &nfkd : nfkd_decomposed) { const auto nfkc = ToNFC(nfkd); // This case is already covered by single-character to NFKC mapping. if (nfkc == nfkd) { continue; } // Expand all possible sequences which are normalized into the same // `nfkd`. for (const auto &nfkd_orig : ExpandUnnormalized(nfkd, norm2orig)) { if (nfkd_orig != nfkc) { nfkc_map[nfkd_orig] = nfkc; } } } RETURN_IF_ERROR(RemoveRedundantMap(&nfkc_map)); *chars_map = std::move(nfkc_map); #else LOG(ERROR) << "NFKC compile is not enabled." << " rebuild with ./configure --enable-nfkc-compile"; #endif return util::OkStatus(); } util::Status Builder::BuildNmtNFKCMap(CharsMap *chars_map) { #ifdef ENABLE_NFKC_COMPILE LOG(INFO) << "Running BuildNmtNFKCMap"; CharsMap nfkc_map; RETURN_IF_ERROR(Builder::BuildNFKCMap(&nfkc_map)); // Other code points considered as whitespace. nfkc_map[{0x0009}] = {0x20}; // TAB nfkc_map[{0x000A}] = {0x20}; // LINE FEED nfkc_map[{0x000C}] = {0x20}; // FORM FEED nfkc_map[{0x000D}] = {0x20}; // CARRIAGE RETURN nfkc_map[{0x1680}] = {0x20}; // OGHAM SPACE MARK nfkc_map[{0x200B}] = {0x20}; // ZERO WIDTH SPACE nfkc_map[{0x200E}] = {0x20}; // LEFT-TO-RIGHT MARK nfkc_map[{0x200F}] = {0x20}; // RIGHT-TO-LEFT MARK nfkc_map[{0x2028}] = {0x20}; // LINE SEPARATOR nfkc_map[{0x2029}] = {0x20}; // PARAGRAPH SEPARATOR nfkc_map[{0x2581}] = {0x20}; // LOWER ONE EIGHT BLOCK nfkc_map[{0xFEFF}] = {0x20}; // ZERO WIDTH NO-BREAK nfkc_map[{0xFFFD}] = {0x20}; // REPLACEMENT CHARACTER nfkc_map[{0x200C}] = {0x20}; // ZERO WIDTH NON-JOINER nfkc_map[{0x200D}] = {0x20}; // ZERO WIDTH JOINER // Ascii Control characters nfkc_map[{0x0001}] = {}; nfkc_map[{0x0002}] = {}; nfkc_map[{0x0003}] = {}; nfkc_map[{0x0004}] = {}; nfkc_map[{0x0005}] = {}; nfkc_map[{0x0006}] = {}; nfkc_map[{0x0007}] = {}; nfkc_map[{0x0008}] = {}; nfkc_map[{0x000B}] = {}; nfkc_map[{0x000E}] = {}; nfkc_map[{0x000F}] = {}; nfkc_map[{0x0010}] = {}; nfkc_map[{0x0011}] = {}; nfkc_map[{0x0012}] = {}; nfkc_map[{0x0013}] = {}; nfkc_map[{0x0014}] = {}; nfkc_map[{0x0015}] = {}; nfkc_map[{0x0016}] = {}; nfkc_map[{0x0017}] = {}; nfkc_map[{0x0018}] = {}; nfkc_map[{0x0019}] = {}; nfkc_map[{0x001A}] = {}; nfkc_map[{0x001B}] = {}; nfkc_map[{0x001C}] = {}; nfkc_map[{0x001D}] = {}; nfkc_map[{0x001E}] = {}; nfkc_map[{0x001F}] = {}; // <control-007F>..<control-009F> nfkc_map[{0x007F}] = {}; nfkc_map[{0x008F}] = {}; nfkc_map[{0x009F}] = {}; // Do not normalize FULL_WIDTH TILDE, since FULL_WIDTH TILDE // and HALF_WIDTH TILDE are used differently in Japanese. nfkc_map.erase({0xFF5E}); RETURN_IF_ERROR(RemoveRedundantMap(&nfkc_map)); *chars_map = std::move(nfkc_map); #else LOG(ERROR) << "NFKC compile is not enabled." << " rebuild with ./configure --enable-nfkc-compile"; #endif return util::OkStatus(); } // static util::Status Builder::MergeUnicodeCaseFoldMap(Builder::CharsMap *chars_map) { #ifdef ENABLE_NFKC_COMPILE for (auto &c : *chars_map) { std::vector<char32> trg; for (char32 c : c.second) trg.push_back(u_foldCase(c, U_FOLD_CASE_DEFAULT)); c.second = trg; } constexpr int kMaxUnicode = 0x10FFFF; for (char32 cp = 1; cp <= kMaxUnicode; ++cp) { if (!U_IS_UNICODE_CHAR(cp)) { continue; } if (chars_map->find({cp}) != chars_map->end()) continue; const char32 trg = u_foldCase(cp, U_FOLD_CASE_DEFAULT); if (trg != cp) (*chars_map)[{cp}] = {trg}; } RETURN_IF_ERROR(RemoveRedundantMap(chars_map)); #endif return util::OkStatus(); } // static util::Status Builder::BuildNFKC_CFMap(CharsMap *chars_map) { #ifdef ENABLE_NFKC_COMPILE CharsMap nfkc_map; RETURN_IF_ERROR(Builder::BuildNFKCMap(&nfkc_map)); RETURN_IF_ERROR(Builder::MergeUnicodeCaseFoldMap(&nfkc_map)); *chars_map = std::move(nfkc_map); #else LOG(ERROR) << "NFKC_CF compile is not enabled." << " rebuild with ./configure --enable-nfkc-compile"; #endif return util::OkStatus(); } // static util::Status Builder::BuildNmtNFKC_CFMap(CharsMap *chars_map) { #ifdef ENABLE_NFKC_COMPILE CharsMap nfkc_map; RETURN_IF_ERROR(Builder::BuildNmtNFKCMap(&nfkc_map)); RETURN_IF_ERROR(Builder::MergeUnicodeCaseFoldMap(&nfkc_map)); *chars_map = std::move(nfkc_map); #else LOG(ERROR) << "NMT_NFKC_CF compile is not enabled." << " rebuild with ./configure --enable-nfkc-compile"; #endif return util::OkStatus(); } util::Status Builder::BuildUncaserMap(Builder::CharsMap *chars_map) { #ifdef ENABLE_NFKC_COMPILE LOG(INFO) << "Running BuildUncaserMap"; constexpr char32 ucMarker = (char32)normalizer::cUppercase; constexpr char32 ncMarker = (char32)normalizer::cPunctuation; constexpr int kMaxUnicode = 0x10FFFF; for (char32 cp = 1; cp <= kMaxUnicode; ++cp) { if (!U_IS_UNICODE_CHAR(cp)) { continue; } if(u_ispunct(cp)) (*chars_map)[{cp}] = {ncMarker, cp}; if(u_isupper(cp)) { const char32 trg = u_foldCase(cp, U_FOLD_CASE_DEFAULT); if (trg != cp && u_islower(trg)) (*chars_map)[{cp}] = {ucMarker, trg}; } } LOG(INFO) << "Character map size for Uncaser: " << chars_map->size(); RETURN_IF_ERROR(RemoveRedundantMap(chars_map)); #endif return util::OkStatus(); } util::Status Builder::BuildRecaserMap(Builder::CharsMap *chars_map) { #ifdef ENABLE_NFKC_COMPILE LOG(INFO) << "Running BuildRecaserMap"; constexpr char32 ucMarker = (char32)normalizer::cUppercase; constexpr char32 tcMarker = (char32)normalizer::cTitlecase; constexpr int kMaxUnicode = 0x10FFFF; for (char32 cp = 1; cp <= kMaxUnicode; ++cp) { if (!U_IS_UNICODE_CHAR(cp)) { continue; } if(u_isupper(cp)) { const char32 trg = u_foldCase(cp, U_FOLD_CASE_DEFAULT); if (trg != cp && u_islower(trg)) { if(chars_map->find({ucMarker, trg}) == chars_map->end()) (*chars_map)[{ucMarker, trg}] = {cp}; if(chars_map->find({tcMarker, trg}) == chars_map->end()) (*chars_map)[{tcMarker, trg}] = {cp}; } } } RETURN_IF_ERROR(RemoveRedundantMap(chars_map)); #endif return util::OkStatus(); } // static util::Status Builder::ComposeCharsMaps(const Builder::CharsMap &outer_chars_map, Builder::CharsMap *chars_map, bool add_rest) { for(auto& cp : *chars_map) { auto found = outer_chars_map.find(cp.second); if(found != outer_chars_map.end()) cp.second = found->second; } if(add_rest) { for(auto& cp : outer_chars_map) { auto found = chars_map->find(cp.first); if(found == chars_map->end()) (*chars_map)[cp.first] = cp.second; } } return util::OkStatus(); } // static util::Status Builder::LoadCharsMap(absl::string_view filename, CharsMap *chars_map) { LOG(INFO) << "Loading mapping file: " << filename.data(); CHECK_OR_RETURN(chars_map); auto input = filesystem::NewReadableFile(filename); RETURN_IF_ERROR(input->status()); std::string line; chars_map->clear(); while (input->ReadLine(&line)) { std::vector<std::string> fields = absl::StrSplit(line, '\t', absl::AllowEmpty()); CHECK_GE(fields.size(), 1); if (fields.size() == 1) fields.push_back(""); // Deletion rule. std::vector<char32> src, trg; for (auto s : absl::StrSplit(fields[0], ' ')) { if (s.empty()) continue; absl::ConsumePrefix(&s, "U+"); src.push_back(string_util::HexToInt<char32>(s)); } for (auto s : absl::StrSplit(fields[1], ' ')) { if (s.empty()) continue; absl::ConsumePrefix(&s, "U+"); trg.push_back(string_util::HexToInt<char32>(s)); } CHECK_OR_RETURN(!src.empty()); (*chars_map)[src] = trg; } return util::OkStatus(); } // static util::Status Builder::SaveCharsMap(absl::string_view filename, const Builder::CharsMap &chars_map) { auto output = filesystem::NewWritableFile(filename); RETURN_IF_ERROR(output->status()); for (const auto &c : chars_map) { std::vector<std::string> src, trg; string_util::UnicodeText srcu, trgu; for (char32 v : c.first) { src.push_back(string_util::IntToHex(v)); srcu.push_back(v); } for (char32 v : c.second) { trg.push_back(string_util::IntToHex(v)); trgu.push_back(v); } std::string line = absl::StrJoin(src, " ") + "\t" + absl::StrJoin(trg, " ") + "\t# " + string_util::UnicodeTextToUTF8(c.first) + " => " + string_util::UnicodeTextToUTF8(c.second); line = absl::StrReplaceAll( line, {{"\b", " "}, {"\v", " "}, {"\f", " "}, {"\n", " "}, {"\r", " "}}); output->WriteLine(line); } return util::OkStatus(); } // static util::Status Builder::RemoveRedundantMap(CharsMap *chars_map) { CHECK_OR_RETURN(chars_map); CharsMap new_chars_map; size_t max_len = 0; for (const auto &p : *chars_map) { max_len = std::max(p.first.size(), max_len); if (p.first.size() == 1) { new_chars_map.insert(p); } } CHECK_GT_OR_RETURN(max_len, 0); // Checks whether the rules with size of `len` can be normalized by // the rules with size of [1 .. len - 1]. for (size_t len = 2; len <= max_len; ++len) { for (const auto &p : *chars_map) { if (p.first.size() == len && p.second != Normalize(new_chars_map, p.first, len - 1)) { new_chars_map.insert(p); } } } // Verify all characters in `chars_map` are normalized by `new_chars_map`. for (const auto &p : *chars_map) { CHECK_EQ_OR_RETURN(p.second, Normalize(new_chars_map, p.first, max_len)); } *chars_map = std::move(new_chars_map); return util::OkStatus(); } } // namespace normalizer } // namespace sentencepiece
31.455793
127
0.641192
[ "vector" ]
8b453e129c4e4841ed3a1903fe0c9910e07fc414
6,526
cc
C++
services/network/test/test_url_loader_client.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
services/network/test/test_url_loader_client.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
services/network/test/test_url_loader_client.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/network/test/test_url_loader_client.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "testing/gtest/include/gtest/gtest.h" namespace network { TestURLLoaderClient::TestURLLoaderClient() : binding_(this) {} TestURLLoaderClient::~TestURLLoaderClient() {} void TestURLLoaderClient::OnReceiveResponse( const ResourceResponseHead& response_head, mojom::DownloadedTempFilePtr downloaded_file) { EXPECT_FALSE(has_received_response_); EXPECT_FALSE(has_received_cached_metadata_); EXPECT_FALSE(has_received_completion_); has_received_response_ = true; response_head_ = response_head; downloaded_file_ = std::move(downloaded_file); if (quit_closure_for_on_receive_response_) quit_closure_for_on_receive_response_.Run(); } void TestURLLoaderClient::OnReceiveRedirect( const net::RedirectInfo& redirect_info, const ResourceResponseHead& response_head) { EXPECT_FALSE(has_received_cached_metadata_); EXPECT_FALSE(response_body_.is_valid()); EXPECT_FALSE(has_received_response_); // Use ClearHasReceivedRedirect to accept more redirects. EXPECT_FALSE(has_received_redirect_); EXPECT_FALSE(has_received_completion_); has_received_redirect_ = true; redirect_info_ = redirect_info; response_head_ = response_head; if (quit_closure_for_on_receive_redirect_) quit_closure_for_on_receive_redirect_.Run(); } void TestURLLoaderClient::OnDataDownloaded(int64_t data_length, int64_t encoded_data_length) { EXPECT_TRUE(has_received_response_); EXPECT_FALSE(has_received_completion_); has_data_downloaded_ = true; download_data_length_ += data_length; encoded_download_data_length_ += encoded_data_length; if (quit_closure_for_on_data_downloaded_) quit_closure_for_on_data_downloaded_.Run(); } void TestURLLoaderClient::OnReceiveCachedMetadata( const std::vector<uint8_t>& data) { EXPECT_FALSE(has_received_cached_metadata_); EXPECT_TRUE(has_received_response_); EXPECT_FALSE(has_received_completion_); has_received_cached_metadata_ = true; cached_metadata_ = std::string(reinterpret_cast<const char*>(data.data()), data.size()); if (quit_closure_for_on_receive_cached_metadata_) quit_closure_for_on_receive_cached_metadata_.Run(); } void TestURLLoaderClient::OnTransferSizeUpdated(int32_t transfer_size_diff) { EXPECT_TRUE(has_received_response_); EXPECT_FALSE(has_received_completion_); EXPECT_GT(transfer_size_diff, 0); body_transfer_size_ += transfer_size_diff; } void TestURLLoaderClient::OnUploadProgress( int64_t current_position, int64_t total_size, OnUploadProgressCallback ack_callback) { EXPECT_TRUE(ack_callback); EXPECT_FALSE(has_received_response_); EXPECT_FALSE(has_received_completion_); EXPECT_LT(0, current_position); EXPECT_LE(current_position, total_size); has_received_upload_progress_ = true; current_upload_position_ = current_position; total_upload_size_ = total_size; std::move(ack_callback).Run(); } void TestURLLoaderClient::OnStartLoadingResponseBody( mojo::ScopedDataPipeConsumerHandle body) { EXPECT_TRUE(has_received_response_); EXPECT_FALSE(has_received_completion_); response_body_ = std::move(body); if (quit_closure_for_on_start_loading_response_body_) quit_closure_for_on_start_loading_response_body_.Run(); } void TestURLLoaderClient::OnComplete(const URLLoaderCompletionStatus& status) { EXPECT_FALSE(has_received_completion_); has_received_completion_ = true; completion_status_ = status; if (quit_closure_for_on_complete_) quit_closure_for_on_complete_.Run(); } mojom::DownloadedTempFilePtr TestURLLoaderClient::TakeDownloadedTempFile() { return std::move(downloaded_file_); } void TestURLLoaderClient::ClearHasReceivedRedirect() { has_received_redirect_ = false; } mojom::URLLoaderClientPtr TestURLLoaderClient::CreateInterfacePtr() { mojom::URLLoaderClientPtr client_ptr; binding_.Bind(mojo::MakeRequest(&client_ptr)); binding_.set_connection_error_handler(base::BindOnce( &TestURLLoaderClient::OnConnectionError, base::Unretained(this))); return client_ptr; } void TestURLLoaderClient::Unbind() { binding_.Unbind(); response_body_.reset(); } void TestURLLoaderClient::RunUntilResponseReceived() { if (has_received_response_) return; base::RunLoop run_loop; quit_closure_for_on_receive_response_ = run_loop.QuitClosure(); run_loop.Run(); quit_closure_for_on_receive_response_.Reset(); } void TestURLLoaderClient::RunUntilRedirectReceived() { if (has_received_redirect_) return; base::RunLoop run_loop; quit_closure_for_on_receive_redirect_ = run_loop.QuitClosure(); run_loop.Run(); quit_closure_for_on_receive_redirect_.Reset(); } void TestURLLoaderClient::RunUntilDataDownloaded() { if (has_data_downloaded_) return; base::RunLoop run_loop; quit_closure_for_on_data_downloaded_ = run_loop.QuitClosure(); run_loop.Run(); quit_closure_for_on_data_downloaded_.Reset(); } void TestURLLoaderClient::RunUntilCachedMetadataReceived() { if (has_received_cached_metadata_) return; base::RunLoop run_loop; quit_closure_for_on_receive_cached_metadata_ = run_loop.QuitClosure(); run_loop.Run(); quit_closure_for_on_receive_cached_metadata_.Reset(); } void TestURLLoaderClient::RunUntilResponseBodyArrived() { if (response_body_.is_valid()) return; base::RunLoop run_loop; quit_closure_for_on_start_loading_response_body_ = run_loop.QuitClosure(); run_loop.Run(); quit_closure_for_on_start_loading_response_body_.Reset(); } void TestURLLoaderClient::RunUntilComplete() { if (has_received_completion_) return; base::RunLoop run_loop; quit_closure_for_on_complete_ = run_loop.QuitClosure(); run_loop.Run(); quit_closure_for_on_complete_.Reset(); } void TestURLLoaderClient::RunUntilConnectionError() { if (has_received_connection_error_) return; base::RunLoop run_loop; quit_closure_for_on_connection_error_ = run_loop.QuitClosure(); run_loop.Run(); quit_closure_for_on_connection_error_.Reset(); } void TestURLLoaderClient::OnConnectionError() { if (has_received_connection_error_) return; has_received_connection_error_ = true; if (quit_closure_for_on_connection_error_) quit_closure_for_on_connection_error_.Run(); } } // namespace network
32.467662
79
0.799111
[ "vector" ]
8b4731d587728780f3fac9bf6364236d976aecf6
4,137
cpp
C++
api/python/MachO/objects/pyExportInfo.cpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
1
2022-02-26T00:28:52.000Z
2022-02-26T00:28:52.000Z
api/python/MachO/objects/pyExportInfo.cpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
null
null
null
api/python/MachO/objects/pyExportInfo.cpp
rafael-santiago/LIEF
f230094d5877dd63d40915dc944c53c2a4be5ed9
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include <string> #include <sstream> #include "LIEF/MachO/hash.hpp" #include "LIEF/MachO/ExportInfo.hpp" #include "LIEF/MachO/Symbol.hpp" #include "LIEF/MachO/DylibCommand.hpp" #include "pyMachO.hpp" #include "pyIterators.hpp" namespace LIEF { namespace MachO { template<class T> using getter_t = T (ExportInfo::*)(void) const; template<class T> using no_const_getter_t = T (ExportInfo::*)(void); template<class T> using setter_t = void (ExportInfo::*)(T); template<> void create<ExportInfo>(py::module& m) { py::class_<ExportInfo, LIEF::Object>(m, "ExportInfo", R"delim( Class that provides an interface over the Dyld export info This class does not represent a structure that exists in the Mach-O format specification but provides a *view* on an entry of the Dyld export trie. )delim") .def_property_readonly("node_offset", static_cast<getter_t<uint64_t>>(&ExportInfo::node_offset), "Original offset in the export Trie") .def_property_readonly("kind", static_cast<getter_t<EXPORT_SYMBOL_KINDS>>(&ExportInfo::kind), "The export's kind: regular, thread local, absolute, ... (" RST_CLASS_REF(lief.MachO.EXPORT_SYMBOL_KINDS) ")") .def_property_readonly("flags_list", static_cast<getter_t<ExportInfo::flag_list_t>>(&ExportInfo::flags_list), "Return flags as a list of " RST_CLASS_REF(lief.MachO.EXPORT_SYMBOL_KINDS) "") .def_property("flags", static_cast<getter_t<uint64_t>>(&ExportInfo::flags), static_cast<setter_t<uint64_t>>(&ExportInfo::flags), "Some information (" RST_CLASS_REF(lief.MachO.EXPORT_SYMBOL_FLAGS) ") about the export (like weak export, reexport, ...)") .def_property("address", static_cast<getter_t<uint64_t>>(&ExportInfo::address), static_cast<setter_t<uint64_t>>(&ExportInfo::address), "The address of the export") .def_property_readonly("alias", static_cast<no_const_getter_t<Symbol*>>(&ExportInfo::alias), "" RST_CLASS_REF(lief.MachO.Symbol) " alias if the current symbol is re-exported", py::return_value_policy::reference) .def_property_readonly("alias_library", static_cast<no_const_getter_t<DylibCommand*>>(&ExportInfo::alias_library), "If the current symbol has an alias, it returns the " RST_CLASS_REF(lief.MachO.DylibCommand) " " " command associated with", py::return_value_policy::reference) .def_property_readonly("has_symbol", &ExportInfo::has_symbol, "``True`` if the export info has a " RST_CLASS_REF(lief.MachO.Symbol) " associated with") .def("has", &ExportInfo::has, "Check if the flag " RST_CLASS_REF(lief.MachO.EXPORT_SYMBOL_FLAGS) " given in first parameter is present" "flag"_a) .def_property_readonly("symbol", static_cast<Symbol* (ExportInfo::*)(void)>(&ExportInfo::symbol), "" RST_CLASS_REF(lief.MachO.Symbol) " associated with the export if any, or None ", py::return_value_policy::reference) .def("__eq__", &ExportInfo::operator==) .def("__ne__", &ExportInfo::operator!=) .def("__hash__", [] (const ExportInfo& export_info) { return Hash::hash(export_info); }) .def("__str__", [] (const ExportInfo& export_info) { std::ostringstream stream; stream << export_info; std::string str = stream.str(); return str; }); } } }
33.909836
130
0.681412
[ "object" ]
8b4d4aee3013ca6b8f4a193f249f96332f89982c
3,037
cpp
C++
codeforces/624_div3/d.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
3
2019-06-25T06:17:38.000Z
2019-07-13T15:18:51.000Z
codeforces/624_div3/d.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
codeforces/624_div3/d.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
#pragma region template 2.4 #include <bits/stdc++.h> using namespace std; template <typename T> using pq_asc = priority_queue<T, vector<T>, greater<T>>; typedef long long ll; typedef vector<ll> vi; typedef vector<vi> vvi; typedef pair<ll, ll> ii; typedef vector<ii> vii; typedef vector<string> vs; #define REP(i, n) for (ll i = 0; i < (n); ++i) #define REP1(i, n) for (ll i = 1; i <= (n); ++i) #define FOR(i, a) for (auto &i : a) #define CH(f, x, y) x = f(x, y) #define IN(T, x) \ T x; \ cin >> x; #define AIN(T, a, n) \ vector<T> a(n); \ FOR(i, a) \ cin >> i; #define A2IN(T1, a, T2, b, n) \ vector<T1> a(n); \ vector<T2> b(n); \ REP(i, n) \ cin >> a[i] >> b[i]; #define OUT(x) cout << (x) << endl; #define FOUT(x) cout << fixed << setprecision(15) << (x) << endl; #define ALL(a) (a).begin(), (a).end() #define SORT(a) sort(ALL(a)) #define RSORT(a) \ SORT(a); \ reverse(ALL(a)) #define DUMP(x) cout << #x << " = " << (x) << endl; #define DUMPA(a) \ cout << #a << " = {"; \ JOUT(ALL(a), ", ", cout) << "}" << endl; template <typename T> ostream &JOUT(T s, T e, string sep = " ", ostream &os = cout) { if (s != e) { os << *s; ++s; } while (s != e) { os << sep << *s; ++s; } return os; } ostream &YES(bool cond, string yes = "Yes", string no = "No", ostream &os = cout) { if (cond) { os << yes << endl; } else { os << no << endl; } return os; } template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { os << '(' << p.first << ", " << p.second << ')'; return os; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << '['; JOUT(ALL(v), ", ", os) << ']'; return os; } const ll INF = 1e18; const ll MOD = 1e9 + 7; #pragma endregion template void solve() { IN(ll, a); IN(ll, b); IN(ll, c); ll ans = INF; ll A, B, C; REP1(j, 2 * c) { ll i = 1; for (ll x = 1; x * x <= j; ++x) { if (j % x == 0 and abs(x - a) < abs(i - a)) { i = x; } if (j % x == 0 and abs(j / x - a) < abs(i - a)) { i = j / x; } } ll k; if (c % j == 0) { k = c; } else if (j < c) { if (c % j < j - c % j) { k = c - c % j; } else { k = c + j - c % j; } } else { k = j; } ll cost = abs(a - i) + abs(b - j) + abs(c - k); if (cost < ans) { ans = cost; A = i; B = j; C = k; } } OUT(ans); cout << A << ' ' << B << ' ' << C << endl; } int main() { IN(ll, t); REP(i, t) { solve(); } }
20.38255
81
0.390517
[ "vector" ]
8b4e0bbbbda5e6e0439cc9cfaee84d93d66609a4
20,462
cpp
C++
src/host/output.cpp
Terminal/Terminal
ceb6fe66e18671670974ac40cd1bc55d4102c8ce
[ "MIT" ]
1
2020-04-30T20:14:44.000Z
2020-04-30T20:14:44.000Z
src/host/output.cpp
Terminal/Terminal
ceb6fe66e18671670974ac40cd1bc55d4102c8ce
[ "MIT" ]
null
null
null
src/host/output.cpp
Terminal/Terminal
ceb6fe66e18671670974ac40cd1bc55d4102c8ce
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" #include "_output.h" #include "output.h" #include "handle.h" #include "getset.h" #include "misc.h" #include "../interactivity/inc/ServiceLocator.hpp" #include "../types/inc/Viewport.hpp" #include "../types/inc/convert.hpp" #pragma hdrstop using namespace Microsoft::Console::Types; using namespace Microsoft::Console::Interactivity; // This routine figures out what parameters to pass to CreateScreenBuffer based on the data from STARTUPINFO and the // registry defaults, and then calls CreateScreenBuffer. [[nodiscard]] NTSTATUS DoCreateScreenBuffer() { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); FontInfo fiFont(gci.GetFaceName(), static_cast<BYTE>(gci.GetFontFamily()), gci.GetFontWeight(), gci.GetFontSize(), gci.GetCodePage()); // For East Asian version, we want to get the code page from the registry or shell32, so we can specify console // codepage by console.cpl or shell32. The default codepage is OEMCP. gci.CP = gci.GetCodePage(); gci.OutputCP = gci.GetCodePage(); gci.Flags |= CONSOLE_USE_PRIVATE_FLAGS; NTSTATUS Status = SCREEN_INFORMATION::CreateInstance(gci.GetWindowSize(), fiFont, gci.GetScreenBufferSize(), gci.GetDefaultAttributes(), TextAttribute{ gci.GetPopupFillAttribute() }, gci.GetCursorSize(), &gci.ScreenBuffers); // TODO: MSFT 9355013: This needs to be resolved. We increment it once with no handle to ensure it's never cleaned up // and one always exists for the renderer (and potentially other functions.) // It's currently a load-bearing piece of code. http://osgvsowi/9355013 if (NT_SUCCESS(Status)) { gci.ScreenBuffers[0].IncrementOriginalScreenBuffer(); } return Status; } // Routine Description: // - This routine copies a rectangular region from the screen buffer to the screen buffer. // Arguments: // - screenInfo - reference to screen info // - source - rectangle in source buffer to copy // - targetOrigin - upper left coordinates of new location rectangle static void _CopyRectangle(SCREEN_INFORMATION& screenInfo, const Viewport& source, const COORD targetOrigin) { const auto sourceOrigin = source.Origin(); // 0. If the source and the target are the same... we have nothing to do. Leave. if (sourceOrigin == targetOrigin) { return; } // 1. If we're copying entire rows of the buffer and moving them directly up or down, // then we can send a rotate command to the underlying buffer to just adjust the // row locations instead of copying or moving anything. { const auto bufferSize = screenInfo.GetBufferSize().Dimensions(); const auto sourceFullRows = source.Width() == bufferSize.X; const auto verticalCopyOnly = source.Left() == 0 && targetOrigin.X == 0; if (sourceFullRows && verticalCopyOnly) { const auto delta = targetOrigin.Y - source.Top(); screenInfo.GetTextBuffer().ScrollRows(source.Top(), source.Height(), gsl::narrow<SHORT>(delta)); return; } } // 2. We can move any other scenario in-place without copying. We just have to carefully // choose which direction we walk through filling up the target so it doesn't accidentally // erase the source material before it can be copied/moved to the new location. { const auto target = Viewport::FromDimensions(targetOrigin, source.Dimensions()); const auto walkDirection = Viewport::DetermineWalkDirection(source, target); auto sourcePos = source.GetWalkOrigin(walkDirection); auto targetPos = target.GetWalkOrigin(walkDirection); do { const auto data = OutputCell(*screenInfo.GetCellDataAt(sourcePos)); screenInfo.Write(OutputCellIterator({ &data, 1 }), targetPos); source.WalkInBounds(sourcePos, walkDirection); } while (target.WalkInBounds(targetPos, walkDirection)); } } // Routine Description: // - This routine reads a sequence of attributes from the screen buffer. // Arguments: // - screenInfo - reference to screen buffer information. // - coordRead - Screen buffer coordinate to begin reading from. // - amountToRead - the number of elements to read // Return Value: // - vector of attribute data std::vector<WORD> ReadOutputAttributes(const SCREEN_INFORMATION& screenInfo, const COORD coordRead, const size_t amountToRead) { // Short circuit. If nothing to read, leave early. if (amountToRead == 0) { return {}; } // Short circuit, if reading out of bounds, leave early. if (!screenInfo.GetBufferSize().IsInBounds(coordRead)) { return {}; } // Get iterator to the position we should start reading at. auto it = screenInfo.GetCellDataAt(coordRead); // Count up the number of cells we've attempted to read. ULONG amountRead = 0; // Prepare the return value string. std::vector<WORD> retVal; // Reserve the number of cells. If we have >U+FFFF, it will auto-grow later and that's OK. retVal.reserve(amountToRead); // While we haven't read enough cells yet and the iterator is still valid (hasn't reached end of buffer) while (amountRead < amountToRead && it) { // If the first thing we read is trailing, pad with a space. // OR If the last thing we read is leading, pad with a space. if ((amountRead == 0 && it->DbcsAttr().IsTrailing()) || (amountRead == (amountToRead - 1) && it->DbcsAttr().IsLeading())) { retVal.push_back(it->TextAttr().GetLegacyAttributes()); } else { retVal.push_back(it->TextAttr().GetLegacyAttributes() | it->DbcsAttr().GeneratePublicApiAttributeFormat()); } amountRead++; it++; } return retVal; } // Routine Description: // - This routine reads a sequence of unicode characters from the screen buffer // Arguments: // - screenInfo - reference to screen buffer information. // - coordRead - Screen buffer coordinate to begin reading from. // - amountToRead - the number of elements to read // Return Value: // - wstring std::wstring ReadOutputStringW(const SCREEN_INFORMATION& screenInfo, const COORD coordRead, const size_t amountToRead) { // Short circuit. If nothing to read, leave early. if (amountToRead == 0) { return {}; } // Short circuit, if reading out of bounds, leave early. if (!screenInfo.GetBufferSize().IsInBounds(coordRead)) { return {}; } // Get iterator to the position we should start reading at. auto it = screenInfo.GetCellDataAt(coordRead); // Count up the number of cells we've attempted to read. ULONG amountRead = 0; // Prepare the return value string. std::wstring retVal; retVal.reserve(amountToRead); // Reserve the number of cells. If we have >U+FFFF, it will auto-grow later and that's OK. // While we haven't read enough cells yet and the iterator is still valid (hasn't reached end of buffer) while (amountRead < amountToRead && it) { // If the first thing we read is trailing, pad with a space. // OR If the last thing we read is leading, pad with a space. if ((amountRead == 0 && it->DbcsAttr().IsTrailing()) || (amountRead == (amountToRead - 1) && it->DbcsAttr().IsLeading())) { retVal += UNICODE_SPACE; } else { // Otherwise, add anything that isn't a trailing cell. (Trailings are duplicate copies of the leading.) if (!it->DbcsAttr().IsTrailing()) { retVal += it->Chars(); } } amountRead++; it++; } return retVal; } // Routine Description: // - This routine reads a sequence of ascii characters from the screen buffer // Arguments: // - screenInfo - reference to screen buffer information. // - coordRead - Screen buffer coordinate to begin reading from. // - amountToRead - the number of elements to read // Return Value: // - string of char data std::string ReadOutputStringA(const SCREEN_INFORMATION& screenInfo, const COORD coordRead, const size_t amountToRead) { const auto wstr = ReadOutputStringW(screenInfo, coordRead, amountToRead); const auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); return ConvertToA(gci.OutputCP, wstr); } void ScreenBufferSizeChange(const COORD coordNewSize) { const CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); try { gci.pInputBuffer->Write(std::make_unique<WindowBufferSizeEvent>(coordNewSize)); } catch (...) { LOG_HR(wil::ResultFromCaughtException()); } } // Routine Description: // - This is simply a notifier method to let accessibility and renderers know that a region of the buffer // has been copied/moved to another location in a block fashion. // Arguments: // - screenInfo - The relevant screen buffer where data was moved // - source - The viewport describing the region where data was copied from // - fill - The viewport describing the area that was filled in with the fill character (uncovered area) // - target - The viewport describing the region where data was copied to static void _ScrollScreen(SCREEN_INFORMATION& screenInfo, const Viewport& source, const Viewport& fill, const Viewport& target) { if (screenInfo.IsActiveScreenBuffer()) { IAccessibilityNotifier* pNotifier = ServiceLocator::LocateAccessibilityNotifier(); if (pNotifier != nullptr) { pNotifier->NotifyConsoleUpdateScrollEvent(target.Origin().X - source.Left(), target.Origin().Y - source.RightInclusive()); } } // Get the render target and send it commands. // It will figure out whether or not we're active and where the messages need to go. auto& render = screenInfo.GetRenderTarget(); // Redraw anything in the target area render.TriggerRedraw(target); // Also redraw anything that was filled. render.TriggerRedraw(fill); } // Routine Description: // - This routine is a special-purpose scroll for use by AdjustCursorPosition. // Arguments: // - screenInfo - reference to screen buffer info. // Return Value: // - true if we succeeded in scrolling the buffer, otherwise false (if we're out of memory) bool StreamScrollRegion(SCREEN_INFORMATION& screenInfo) { // Rotate the circular buffer around and wipe out the previous final line. bool fSuccess = screenInfo.GetTextBuffer().IncrementCircularBuffer(); if (fSuccess) { // Trigger a graphical update if we're active. if (screenInfo.IsActiveScreenBuffer()) { COORD coordDelta = { 0 }; coordDelta.Y = -1; IAccessibilityNotifier* pNotifier = ServiceLocator::LocateAccessibilityNotifier(); if (pNotifier) { // Notify accessibility that a scroll has occurred. pNotifier->NotifyConsoleUpdateScrollEvent(coordDelta.X, coordDelta.Y); } if (ServiceLocator::LocateGlobals().pRender != nullptr) { ServiceLocator::LocateGlobals().pRender->TriggerScroll(&coordDelta); } } } return fSuccess; } // Routine Description: // - This routine copies ScrollRectangle to DestinationOrigin then fills in ScrollRectangle with Fill. // - The scroll region is copied to a third buffer, the scroll region is filled, then the original contents of the scroll region are copied to the destination. // Arguments: // - screenInfo - reference to screen buffer info. // - scrollRectGiven - Region to copy/move (source and size) // - clipRectGiven - Optional clip region to contain buffer change effects // - destinationOriginGiven - Upper left corner of target region. // - fillCharGiven - Character to fill source region with. // - fillAttrsGiven - Attribute to fill source region with. // NOTE: Throws exceptions void ScrollRegion(SCREEN_INFORMATION& screenInfo, const SMALL_RECT scrollRectGiven, const std::optional<SMALL_RECT> clipRectGiven, const COORD destinationOriginGiven, const wchar_t fillCharGiven, const TextAttribute fillAttrsGiven) { // ------ 1. PREP SOURCE ------ // Set up the source viewport. auto source = Viewport::FromInclusive(scrollRectGiven); const auto originalSourceOrigin = source.Origin(); // Alright, let's make sure that our source fits inside the buffer. const auto buffer = screenInfo.GetBufferSize(); source = Viewport::Intersect(source, buffer); // If the source is no longer valid, then there's nowhere we can copy from // and also nowhere we can fill. We're done. Return early. if (!source.IsValid()) { return; } // ------ 2. PREP CLIP ------ // Now figure out our clipping area. If we have clipping specified, it will limit // the area that can be affected (targeted or filling) throughout this operation. // If there was no clip rect, we'll clip to the entire buffer size. auto clip = Viewport::FromInclusive(clipRectGiven.value_or(buffer.ToInclusive())); // OK, make sure that the clip rectangle also fits inside the buffer clip = Viewport::Intersect(buffer, clip); // ------ 3. PREP FILL ------ // Then think about fill. We will fill in any area of the source that we copied from // with the fill character as long as it falls inside the clip region (the area // that is allowed to be affected). auto fill = Viewport::Intersect(clip, source); // If fill is no longer valid, then there is no area that we're allowed to write to // within the buffer. So we can just exit early. if (!fill.IsValid()) { return; } // Determine the cell we will use to fill in any revealed/uncovered space. // We generally use exactly what was given to us. OutputCellIterator fillData(fillCharGiven, fillAttrsGiven); // However, if the character is null and we were given a null attribute (represented as legacy 0), // then we'll just fill with spaces and whatever the buffer's default colors are. if (fillCharGiven == UNICODE_NULL && fillAttrsGiven.IsLegacy() && fillAttrsGiven.GetLegacyAttributes() == 0) { fillData = OutputCellIterator(UNICODE_SPACE, screenInfo.GetAttributes()); } // ------ 4. PREP TARGET ------ // Now it's time to think about the target. We're only given the origin of the target // because it is assumed that it will have the same relative dimensions as the original source. auto targetOrigin = destinationOriginGiven; // However, if we got to this point, we may have clipped the source because some part of it // fell outside of the buffer. // Apply any delta between the original source rectangle's origin and its current position to // the target origin. { auto currentSourceOrigin = source.Origin(); targetOrigin.X += currentSourceOrigin.X - originalSourceOrigin.X; targetOrigin.Y += currentSourceOrigin.Y - originalSourceOrigin.Y; } // And now the target viewport is the same size as the source viewport but at the different position. auto target = Viewport::FromDimensions(targetOrigin, source.Dimensions()); // However, this might mean that the target is falling outside of the region we're allowed to edit // (the clip area). So we need to reduce the target to only inside the clip. // But backup the original target origin first, because we need to know how it has changed. const auto originalTargetOrigin = target.Origin(); target = Viewport::Intersect(clip, target); // OK, if the target became smaller than before, we need to also adjust the source accordingly // so we don't waste time loading up/copying things that have no place to go within the target. { const auto currentTargetOrigin = target.Origin(); auto sourceOrigin = source.Origin(); sourceOrigin.X += currentTargetOrigin.X - originalTargetOrigin.X; sourceOrigin.Y += currentTargetOrigin.Y - originalTargetOrigin.Y; source = Viewport::FromDimensions(sourceOrigin, target.Dimensions()); } // ------ 5. COPY ------ // If the target region is valid, let's do this. if (target.IsValid()) { // Perform the copy from the source to the target. _CopyRectangle(screenInfo, source, target.Origin()); // Notify the renderer and accessibility as to what moved and where. _ScrollScreen(screenInfo, source, fill, target); } // ------ 6. FILL ------ // Now fill in anything that wasn't already touched by the copy above. // Fill as a single viewport represents the entire region we were allowed to // write into. But since we already copied, filling the whole thing might // overwrite what we just placed at the target. // So use the special subtraction function to get the viewports that fall // within the fill area but outside of the target area. const auto remaining = Viewport::Subtract(fill, target); // Apply the fill data to each of the viewports we're given here. for (size_t i = 0; i < remaining.size(); i++) { const auto& view = remaining.at(i); screenInfo.WriteRect(fillData, view); } } void SetActiveScreenBuffer(SCREEN_INFORMATION& screenInfo) { CONSOLE_INFORMATION& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); gci.pCurrentScreenBuffer = &screenInfo; // initialize cursor screenInfo.GetTextBuffer().GetCursor().SetIsOn(false); // set font screenInfo.RefreshFontWithRenderer(); // Empty input buffer. gci.pInputBuffer->FlushAllButKeys(); // Set window size. screenInfo.PostUpdateWindowSize(); gci.ConsoleIme.RefreshAreaAttributes(); // Write data to screen. WriteToScreen(screenInfo, screenInfo.GetViewport()); } // Routine Description: // - Dispatches final close event to connected clients or will run down and exit (and never return) if all clients // are already gone. // - NOTE: MUST BE CALLED UNDER LOCK. We don't want clients joining or leaving while we're telling them to close and running down. // Arguments: // - <none> // Return Value: // - <none> // TODO: MSFT 9450717 This should join the ProcessList class when CtrlEvents become moved into the server. https://osgvsowi/9450717 void CloseConsoleProcessState() { auto& gci = ServiceLocator::LocateGlobals().getConsoleInformation(); FAIL_FAST_IF(!(gci.IsConsoleLocked())); // If there are no connected processes, sending control events is pointless as there's no one do send them to. In // this case we'll just exit conhost. // N.B. We can get into this state when a process has a reference to the console but hasn't connected. For example, // when it's created suspended and never resumed. if (gci.ProcessHandleList.IsEmpty()) { ServiceLocator::RundownAndExit(STATUS_SUCCESS); } HandleCtrlEvent(CTRL_CLOSE_EVENT); }
40.599206
160
0.645098
[ "render", "vector" ]
8b4f3110cd1196273ddea254ec5b0aab59b15de5
1,737
cpp
C++
test/cpp/callbackcontext.cpp
kkoopa/nan
347fd3a313c6e65ce9fa8b9c1accea59b65c864c
[ "MIT" ]
1
2021-03-23T05:27:10.000Z
2021-03-23T05:27:10.000Z
test/cpp/callbackcontext.cpp
kkoopa/nan
347fd3a313c6e65ce9fa8b9c1accea59b65c864c
[ "MIT" ]
null
null
null
test/cpp/callbackcontext.cpp
kkoopa/nan
347fd3a313c6e65ce9fa8b9c1accea59b65c864c
[ "MIT" ]
null
null
null
/********************************************************************* * NAN - Native Abstractions for Node.js * * Copyright (c) 2018 NAN contributors * * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> ********************************************************************/ #include <nan.h> #include "sleep.h" using namespace Nan; // NOLINT(build/namespaces) class DelayRequest : public AsyncResource { public: DelayRequest(int milliseconds_, v8::Local<v8::Function> callback_) : AsyncResource("nan:test.DelayRequest"), callback(callback_), milliseconds(milliseconds_) { request.data = this; } ~DelayRequest() {} Callback callback; uv_work_t request; int milliseconds; }; void Delay(uv_work_t* req) { DelayRequest *delay_request = static_cast<DelayRequest*>(req->data); Sleep(delay_request->milliseconds); } void AfterDelay(uv_work_t* req, int status) { HandleScope scope; DelayRequest *delay_request = static_cast<DelayRequest*>(req->data); v8::Local<v8::Object> target = New<v8::Object>(); // Run the callback in the async context. delay_request->callback.Call(target, 0, NULL, delay_request); delete delay_request; } NAN_METHOD(Delay) { int delay = To<int>(info[0]).FromJust(); v8::Local<v8::Function> cb = To<v8::Function>(info[1]).ToLocalChecked(); DelayRequest* delay_request = new DelayRequest(delay, cb); uv_queue_work( uv_default_loop() , &delay_request->request , Delay , reinterpret_cast<uv_after_work_cb>(AfterDelay)); } NAN_MODULE_INIT(Init) { Set(target, New<v8::String>("delay").ToLocalChecked(), GetFunction(New<v8::FunctionTemplate>(Delay)).ToLocalChecked()); } NODE_MODULE(asyncresource, Init)
26.318182
74
0.650547
[ "object" ]
332c45a472c2cabdfa4885d85fee2949b27aa486
14,757
cc
C++
src/frontend/xgboost.cc
fengjixuchui/treelite
b376bd6df12e39e1ef1410cc62832170bdd6ea88
[ "Apache-2.0" ]
null
null
null
src/frontend/xgboost.cc
fengjixuchui/treelite
b376bd6df12e39e1ef1410cc62832170bdd6ea88
[ "Apache-2.0" ]
null
null
null
src/frontend/xgboost.cc
fengjixuchui/treelite
b376bd6df12e39e1ef1410cc62832170bdd6ea88
[ "Apache-2.0" ]
null
null
null
/*! * Copyright (c) 2017-2020 by Contributors * \file xgboost.cc * \brief Frontend for xgboost model * \author Hyunsu Cho */ #include <dmlc/data.h> #include <dmlc/memory_io.h> #include <treelite/frontend.h> #include <treelite/tree.h> #include <algorithm> #include <memory> #include <queue> #include <cstring> namespace { treelite::Model ParseStream(dmlc::Stream* fi); } // anonymous namespace namespace treelite { namespace frontend { DMLC_REGISTRY_FILE_TAG(xgboost); Model LoadXGBoostModel(const char* filename) { std::unique_ptr<dmlc::Stream> fi(dmlc::Stream::Create(filename, "r")); return ParseStream(fi.get()); } Model LoadXGBoostModel(const void* buf, size_t len) { dmlc::MemoryFixedSizeStream fs(const_cast<void*>(buf), len); return ParseStream(&fs); } } // namespace frontend } // namespace treelite /* auxiliary data structures to interpret xgboost model file */ namespace { typedef float bst_float; struct ProbToMargin { static float Sigmoid(float global_bias) { return -logf(1.0f / global_bias - 1.0f); } static float Exponential(float global_bias) { return logf(global_bias); } }; /* peekable input stream implemented with a ring buffer */ class PeekableInputStream { public: const size_t MAX_PEEK_WINDOW = 1024; // peek up to 1024 bytes explicit PeekableInputStream(dmlc::Stream* fi) : istm_(fi), buf_(MAX_PEEK_WINDOW + 1), begin_ptr_(0), end_ptr_(0) {} inline size_t Read(void* ptr, size_t size) { const size_t bytes_buffered = BytesBuffered(); char* cptr = static_cast<char*>(ptr); if (size <= bytes_buffered) { // all content already buffered; consume buffer if (begin_ptr_ + size < MAX_PEEK_WINDOW + 1) { std::memcpy(cptr, &buf_[begin_ptr_], size); begin_ptr_ += size; } else { std::memcpy(cptr, &buf_[begin_ptr_], MAX_PEEK_WINDOW + 1 - begin_ptr_); std::memcpy(cptr + MAX_PEEK_WINDOW + 1 - begin_ptr_, &buf_[0], size + begin_ptr_ - MAX_PEEK_WINDOW - 1); begin_ptr_ = size + begin_ptr_ - MAX_PEEK_WINDOW - 1; } return size; } else { // consume buffer entirely and read more bytes const size_t bytes_to_read = size - bytes_buffered; if (begin_ptr_ <= end_ptr_) { std::memcpy(cptr, &buf_[begin_ptr_], bytes_buffered); } else { std::memcpy(cptr, &buf_[begin_ptr_], MAX_PEEK_WINDOW + 1 - begin_ptr_); std::memcpy(cptr + MAX_PEEK_WINDOW + 1 - begin_ptr_, &buf_[0], bytes_buffered + begin_ptr_ - MAX_PEEK_WINDOW - 1); } begin_ptr_ = end_ptr_; return bytes_buffered + istm_->Read(cptr + bytes_buffered, bytes_to_read); } } inline size_t PeekRead(void* ptr, size_t size) { CHECK_LE(size, MAX_PEEK_WINDOW) << "PeekableInputStream allows peeking up to " << MAX_PEEK_WINDOW << " bytes"; char* cptr = static_cast<char*>(ptr); const size_t bytes_buffered = BytesBuffered(); /* fill buffer with additional bytes, up to size */ if (size > bytes_buffered) { const size_t bytes_to_read = size - bytes_buffered; if (end_ptr_ + bytes_to_read < MAX_PEEK_WINDOW + 1) { CHECK_EQ(istm_->Read(&buf_[end_ptr_], bytes_to_read), bytes_to_read) << "Failed to peek " << size << " bytes"; end_ptr_ += bytes_to_read; } else { CHECK_EQ(istm_->Read(&buf_[end_ptr_], MAX_PEEK_WINDOW + 1 - end_ptr_) + istm_->Read(&buf_[0], bytes_to_read + end_ptr_ - MAX_PEEK_WINDOW - 1), bytes_to_read) << "Ill-formed XGBoost model: Failed to peek " << size << " bytes"; end_ptr_ = bytes_to_read + end_ptr_ - MAX_PEEK_WINDOW - 1; } } /* copy buffer into ptr without emptying buffer */ if (begin_ptr_ <= end_ptr_) { // usual case std::memcpy(cptr, &buf_[begin_ptr_], end_ptr_ - begin_ptr_); } else { // context wrapped around the end std::memcpy(cptr, &buf_[begin_ptr_], MAX_PEEK_WINDOW + 1 - begin_ptr_); std::memcpy(cptr + MAX_PEEK_WINDOW + 1 - begin_ptr_, &buf_[0], end_ptr_); } return size; } private: dmlc::Stream* istm_; std::vector<char> buf_; size_t begin_ptr_, end_ptr_; inline size_t BytesBuffered() { if (begin_ptr_ <= end_ptr_) { // usual case return end_ptr_ - begin_ptr_; } else { // context wrapped around the end return MAX_PEEK_WINDOW + 1 + end_ptr_ - begin_ptr_; } } }; template <typename T> inline void CONSUME_BYTES(const T& fi, size_t size) { static std::vector<char> dummy(500); if (size > dummy.size()) dummy.resize(size); CHECK_EQ(fi->Read(&dummy[0], size), size) << "Ill-formed XGBoost model format: cannot read " << size << " bytes from the file"; } struct LearnerModelParam { bst_float base_score; // global bias unsigned num_feature; int num_class; int contain_extra_attrs; int contain_eval_metrics; uint32_t major_version; uint32_t minor_version; int pad2[27]; }; static_assert(sizeof(LearnerModelParam) == 136, "This is the size defined in XGBoost."); struct GBTreeModelParam { int num_trees; int num_roots; int num_feature; int pad1; int64_t pad2; int num_output_group; int size_leaf_vector; int pad3[32]; }; struct TreeParam { int num_roots; int num_nodes; int num_deleted; int max_depth; int num_feature; int size_leaf_vector; int reserved[31]; }; struct NodeStat { bst_float loss_chg; bst_float sum_hess; bst_float base_weight; int leaf_child_cnt; }; class XGBTree { public: class Node { public: Node() : sindex_(0) { // assert compact alignment static_assert(sizeof(Node) == 4 * sizeof(int) + sizeof(Info), "Node: 64 bit align"); } inline int cleft() const { return this->cleft_; } inline int cright() const { return this->cright_; } inline int cdefault() const { return this->default_left() ? this->cleft() : this->cright(); } inline unsigned split_index() const { return sindex_ & ((1U << 31) - 1U); } inline bool default_left() const { return (sindex_ >> 31) != 0; } inline bool is_leaf() const { return cleft_ == -1; } inline bst_float leaf_value() const { return (this->info_).leaf_value; } inline bst_float split_cond() const { return (this->info_).split_cond; } inline int parent() const { return parent_ & ((1U << 31) - 1); } inline bool is_root() const { return parent_ == -1; } inline void set_leaf(bst_float value) { (this->info_).leaf_value = value; this->cleft_ = -1; this->cright_ = -1; } inline void set_split(unsigned split_index, bst_float split_cond, bool default_left = false) { if (default_left) split_index |= (1U << 31); this->sindex_ = split_index; (this->info_).split_cond = split_cond; } private: friend class XGBTree; union Info { bst_float leaf_value; bst_float split_cond; }; int parent_; int cleft_, cright_; unsigned sindex_; Info info_; inline bool is_deleted() const { return sindex_ == std::numeric_limits<unsigned>::max(); } inline void set_parent(int pidx, bool is_left_child = true) { if (is_left_child) pidx |= (1U << 31); this->parent_ = pidx; } }; private: TreeParam param; std::vector<Node> nodes; std::vector<NodeStat> stats; inline int AllocNode() { int nd = param.num_nodes++; CHECK_LT(param.num_nodes, std::numeric_limits<int>::max()) << "number of nodes in the tree exceed 2^31"; nodes.resize(param.num_nodes); return nd; } public: /*! \brief get node given nid */ inline Node& operator[](int nid) { return nodes[nid]; } /*! \brief get node given nid */ inline const Node& operator[](int nid) const { return nodes[nid]; } /*! \brief get node statistics given nid */ inline NodeStat& Stat(int nid) { return stats[nid]; } /*! \brief get node statistics given nid */ inline const NodeStat& Stat(int nid) const { return stats[nid]; } inline void Init() { param.num_nodes = 1; nodes.resize(1); nodes[0].set_leaf(0.0f); nodes[0].set_parent(-1); } inline void AddChilds(int nid) { int pleft = this->AllocNode(); int pright = this->AllocNode(); nodes[nid].cleft_ = pleft; nodes[nid].cright_ = pright; nodes[nodes[nid].cleft() ].set_parent(nid, true); nodes[nodes[nid].cright()].set_parent(nid, false); } inline void Load(PeekableInputStream* fi) { CHECK_EQ(fi->Read(&param, sizeof(TreeParam)), sizeof(TreeParam)) << "Ill-formed XGBoost model file: can't read TreeParam"; nodes.resize(param.num_nodes); stats.resize(param.num_nodes); CHECK_NE(param.num_nodes, 0) << "Ill-formed XGBoost model file: a tree can't be empty"; CHECK_EQ(fi->Read(dmlc::BeginPtr(nodes), sizeof(Node) * nodes.size()), sizeof(Node) * nodes.size()) << "Ill-formed XGBoost model file: cannot read specified number of nodes"; CHECK_EQ(fi->Read(dmlc::BeginPtr(stats), sizeof(NodeStat) * stats.size()), sizeof(NodeStat) * stats.size()) << "Ill-formed XGBoost model file: cannot read specified number of nodes"; if (param.size_leaf_vector != 0) { uint64_t len; CHECK_EQ(fi->Read(&len, sizeof(len)), sizeof(len)) << "Ill-formed XGBoost model file"; if (len > 0) { CONSUME_BYTES(fi, sizeof(bst_float) * len); } } CHECK_EQ(param.num_roots, 1) << "Invalid XGBoost model file: treelite does not support trees " << "with multiple roots"; } }; inline treelite::Model ParseStream(dmlc::Stream* fi) { std::vector<XGBTree> xgb_trees_; LearnerModelParam mparam_; // model parameter GBTreeModelParam gbm_param_; // GBTree training parameter std::string name_gbm_; std::string name_obj_; /* 1. Parse input stream */ std::unique_ptr<PeekableInputStream> fp(new PeekableInputStream(fi)); // backward compatible header check. std::string header; header.resize(4); if (fp->PeekRead(&header[0], 4) == 4) { CHECK_NE(header, "bs64") << "Ill-formed XGBoost model file: Base64 format no longer supported"; if (header == "binf") { CONSUME_BYTES(fp, 4); } } // read parameter CHECK_EQ(fp->Read(&mparam_, sizeof(mparam_)), sizeof(mparam_)) << "Ill-formed XGBoost model file: corrupted header"; { uint64_t len; CHECK_EQ(fp->Read(&len, sizeof(len)), sizeof(len)) << "Ill-formed XGBoost model file: corrupted header"; if (len != 0) { name_obj_.resize(len); CHECK_EQ(fp->Read(&name_obj_[0], len), len) << "Ill-formed XGBoost model file: corrupted header"; } } { uint64_t len; CHECK_EQ(fp->Read(&len, sizeof(len)), sizeof(len)) << "Ill-formed XGBoost model file: corrupted header"; name_gbm_.resize(len); if (len > 0) { CHECK_EQ(fp->Read(&name_gbm_[0], len), len) << "Ill-formed XGBoost model file: corrupted header"; } } /* loading GBTree */ CHECK_EQ(name_gbm_, "gbtree") << "Invalid XGBoost model file: " << "Gradient booster must be gbtree type."; CHECK_EQ(fp->Read(&gbm_param_, sizeof(gbm_param_)), sizeof(gbm_param_)) << "Invalid XGBoost model file: corrupted GBTree parameters"; for (int i = 0; i < gbm_param_.num_trees; ++i) { xgb_trees_.emplace_back(); xgb_trees_.back().Load(fp.get()); } CHECK_EQ(gbm_param_.num_roots, 1) << "multi-root trees not supported"; // Before XGBoost 1.0.0, the global bias saved in model is a transformed value. After // 1.0 it's the original value provided by user. bool need_transform_to_margin = mparam_.major_version >= 1; /* 2. Export model */ treelite::Model model; model.num_feature = mparam_.num_feature; model.num_output_group = std::max(mparam_.num_class, 1); model.random_forest_flag = false; // set global bias model.param.global_bias = static_cast<float>(mparam_.base_score); std::vector<std::string> exponential_family { "count:poisson", "reg:gamma", "reg:tweedie" }; if (need_transform_to_margin) { if (name_obj_ == "reg:logistic" || name_obj_ == "binary:logistic") { model.param.global_bias = ProbToMargin::Sigmoid(model.param.global_bias); } else if (std::find(exponential_family.cbegin() , exponential_family.cend(), name_obj_) != exponential_family.cend()) { model.param.global_bias = ProbToMargin::Exponential(model.param.global_bias); } } // set correct prediction transform function, depending on objective function if (name_obj_ == "multi:softmax") { model.param.pred_transform = "max_index"; } else if (name_obj_ == "multi:softprob") { model.param.pred_transform = "softmax"; } else if (name_obj_ == "reg:logistic" || name_obj_ == "binary:logistic") { model.param.pred_transform = "sigmoid"; model.param.sigmoid_alpha = 1.0f; } else if (std::find(exponential_family.cbegin() , exponential_family.cend(), name_obj_) != exponential_family.cend()) { model.param.pred_transform = "exponential"; } else { model.param.pred_transform = "identity"; } // traverse trees for (const auto& xgb_tree : xgb_trees_) { model.trees.emplace_back(); treelite::Tree& tree = model.trees.back(); tree.Init(); // assign node ID's so that a breadth-wise traversal would yield // the monotonic sequence 0, 1, 2, ... // deleted nodes will be excluded std::queue<std::pair<int, int>> Q; // (old ID, new ID) pair Q.push({0, 0}); while (!Q.empty()) { int old_id, new_id; std::tie(old_id, new_id) = Q.front(); Q.pop(); const XGBTree::Node& node = xgb_tree[old_id]; const NodeStat stat = xgb_tree.Stat(old_id); if (node.is_leaf()) { const bst_float leaf_value = node.leaf_value(); tree[new_id].set_leaf(static_cast<treelite::tl_float>(leaf_value)); } else { const bst_float split_cond = node.split_cond(); tree.AddChilds(new_id); tree[new_id].set_numerical_split(node.split_index(), static_cast<treelite::tl_float>(split_cond), node.default_left(), treelite::Operator::kLT); tree[new_id].set_gain(stat.loss_chg); Q.push({node.cleft(), tree[new_id].cleft()}); Q.push({node.cright(), tree[new_id].cright()}); } tree[new_id].set_sum_hess(stat.sum_hess); } } return model; } } // anonymous namespace
31.667382
92
0.636579
[ "vector", "model", "transform" ]
3330fa5cad08b13bdb2d27d26e80fdf8d18afc6b
44,255
cc
C++
tensorflow_text/core/kernels/sentence_fragmenter_v2_test.cc
fsx950223/text
24ea0a43ef21a33c3f3f2f526530d23ad3ff7d90
[ "Apache-2.0" ]
1
2020-10-10T14:10:07.000Z
2020-10-10T14:10:07.000Z
tensorflow_text/core/kernels/sentence_fragmenter_v2_test.cc
fsx950223/text
24ea0a43ef21a33c3f3f2f526530d23ad3ff7d90
[ "Apache-2.0" ]
1
2021-02-24T01:09:21.000Z
2021-02-24T01:09:21.000Z
tensorflow_text/core/kernels/sentence_fragmenter_v2_test.cc
fsx950223/text
24ea0a43ef21a33c3f3f2f526530d23ad3ff7d90
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 TF.Text Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tensorflow_text/core/kernels/sentence_fragmenter_v2.h" #include <string> #include <vector> #include <gtest/gtest.h> #include "absl/strings/string_view.h" #include "icu4c/source/common/unicode/uchar.h" #include "icu4c/source/common/unicode/umachine.h" #include "icu4c/source/common/unicode/unistr.h" namespace tensorflow { namespace text { namespace { class SentenceBreakingUtilsParamTest : public ::testing::TestWithParam<UChar> { protected: std::string StringFromUnicodeChar(UChar32 input) { std::string result; icu::UnicodeString test_unicode_string(input); test_unicode_string.toUTF8String(result); return result; } }; class SentenceBreakingUtilsStringParamTest : public ::testing::TestWithParam<const char*> {}; class IsTerminalPuncParamTest : public SentenceBreakingUtilsParamTest {}; class IsTerminalPuncTest : public ::testing::Test {}; const UChar is_terminal_punc_test_cases[] = { 0x055C, // Armenian exclamation mark 0x055E, // Armenian question mark 0x0589, // Armenian full stop 0x061F, // Arabic question mark 0x06D4, // Arabic full stop 0x0700, // Syriabc end of paragraph 0x0701, // Syriac supralinear full stop 0x0702, // Syriac sublinear full stop 0x1362, // Ethiopic full stop 0x1367, // Ethiopic question mark 0x1368, // Ethiopic paragraph separator 0x104A, // Myanmar sign little section 0x104B, // Myanmar sign section 0x166E, // Canadian syllabics full stop 0x17d4, // Khmer sign khan 0x1803, // Mongolian full stop 0x1809, // Mongolian Manchu full stop 0x1944, // Limbu exclamation mark 0x1945, // Limbu question mark 0x203C, // double exclamation mark 0x203D, // interrobang 0x2047, // double question mark 0x2048, // question exclamation mark 0x2049, // exclamation question mark 0x3002, // ideographic full stop 0x037E, // Greek question mark 0xFE52, // small full stop 0xFE56, // small question mark 0xFE57, // small exclamation mark 0xFF01, // fullwidth exclamation mark 0xFF0E, // fullwidth full stop 0xFF1F, // fullwidth question mark 0xFF61, // halfwidth ideographic full stop 0x2026, // ellipsis 0x0964, 0x0965, // Devanagari danda..Devanagari double }; TEST_P(IsTerminalPuncParamTest, IsTerminalPunc) { std::string test_string = StringFromUnicodeChar(GetParam()); int offset; EXPECT_TRUE(IsTerminalPunc(test_string, &offset)); } INSTANTIATE_TEST_SUITE_P(IsTerminalPuncTest, IsTerminalPuncParamTest, ::testing::ValuesIn(is_terminal_punc_test_cases)); TEST_F(IsTerminalPuncTest, IsMultiCharEllipseTerminalPunc) { std::string test_string = "..."; int offset; EXPECT_TRUE(IsTerminalPunc(test_string, &offset)); } TEST_F(IsTerminalPuncTest, TestMultiUnicodeChars) { std::string test_string = "never gonna let you decode"; int offset; EXPECT_FALSE(IsTerminalPunc(test_string, &offset)); } struct ClosePuncOffsetPairs { const UChar close_punc; const int offset; }; class SentenceBreakingUtilsClosePuncPairParamTest : public ::testing::TestWithParam<ClosePuncOffsetPairs> { protected: std::string StringFromUnicodeChar(UChar32 input) { std::string result; icu::UnicodeString test_unicode_string(input); test_unicode_string.toUTF8String(result); return result; } }; class ClosePuncParamTest : public SentenceBreakingUtilsClosePuncPairParamTest { }; const ClosePuncOffsetPairs close_punc_test_cases[] = { {0x29, 1}, {0x5D, 1}, {0x3E, 1}, {0x7D, 1}, {0x207E, 3}, // superscript right parenthesis {0x208E, 3}, // subscript right parenthesis {0x27E7, 3}, // mathematical right white square bracket {0x27E9, 3}, // mathematical right angle bracket {0x27EB, 3}, // mathematical right double angle bracket {0x2984, 3}, // right white curly bracket {0x2986, 3}, // right white parenthesis {0x2988, 3}, // Z notation right image bracket {0x298A, 3}, // Z notation right binding bracket {0x298C, 3}, // right square bracket with underbar {0x298E, 3}, // right square bracket with tick in top corner {0x2990, 3}, // right square bracket with tick in bottom corner {0x2992, 3}, // right angle bracket with dot {0x2994, 3}, // right arc greater-than bracket {0x2996, 3}, // double right arc less-than bracket {0x2998, 3}, // right black tortoise shell bracket {0x29D9, 3}, // right wiggly fence {0x29DB, 3}, // right double wiggly fence {0x29FD, 3}, // right-pointing curved angle bracket {0x3009, 3}, // CJK right angle bracket {0x300B, 3}, // CJK right double angle bracket {0x3011, 3}, // CJK right black lenticular bracket {0x3015, 3}, // CJK right tortoise shell bracket {0x3017, 3}, // CJK right white lenticular bracket {0x3019, 3}, // CJK right white tortoise shell bracket {0x301B, 3}, // CJK right white square bracket {0xFD3F, 3}, // Ornate right parenthesis {0xFE5A, 3}, // small right parenthesis {0xFE5C, 3}, // small right curly bracket {0xFF09, 3}, // fullwidth right parenthesis {0xFF3D, 3}, // fullwidth right square bracket {0xFF5D, 3}, // fullwidth right curly bracket {0x27, 1}, {0x60, 1}, {0x22, 1}, {0xFF07, 3}, // fullwidth apostrophe {0xFF02, 3}, // fullwidth quotation mark {0x2019, 3}, // right single quotation mark (English, others) {0x201D, 3}, // right double quotation mark (English, others) {0x2018, 3}, // left single quotation mark (Czech, German, Slovak) {0x201C, 3}, // left double quotation mark (Czech, German, Slovak) {0x203A, 3}, // single right-pointing angle quotation mark (French, others) {0x00BB, 2}, // right-pointing double angle quotation mark (French, others) {0x2039, 3}, // single left-pointing angle quotation mark (Slovenian, // others) {0x00AB, 2}, // left-pointing double angle quotation mark (Slovenian, // others) {0x300D, 3}, // right corner bracket (East Asian languages) {0xfe42, 3}, // presentation form for vertical right corner bracket {0xFF63, 3}, // halfwidth right corner bracket (East Asian languages) {0x300F, 3}, // right white corner bracket (East Asian languages) {0xfe44, 3}, // presentation form for vertical right white corner bracket {0x301F, 3}, // low double prime quotation mark (East Asian languages) {0x301E, 3} // close double prime (East Asian languages written // horizontally) }; TEST_P(ClosePuncParamTest, IsClosePunc) { ClosePuncOffsetPairs test_punc = GetParam(); std::string test_string = StringFromUnicodeChar(test_punc.close_punc); int expected_offset = test_punc.offset; int offset; EXPECT_TRUE(IsClosePunc(test_string, &offset)); EXPECT_EQ(offset, expected_offset); } INSTANTIATE_TEST_SUITE_P(IsClosePuncParamTest, ClosePuncParamTest, ::testing::ValuesIn(close_punc_test_cases)); class OpenParenParamTest : public SentenceBreakingUtilsParamTest {}; const UChar open_paren_test_cases[] = { '(', '[', '<', '{', 0x207D, // superscript left parenthesis 0x208D, // subscript left parenthesis 0x27E6, // mathematical left white square bracket 0x27E8, // mathematical left angle bracket 0x27EA, // mathematical left double angle bracket 0x2983, // left white curly bracket 0x2985, // left white parenthesis 0x2987, // Z notation left image bracket 0x2989, // Z notation left binding bracket 0x298B, // left square bracket with underbar 0x298D, // left square bracket with tick in top corner 0x298F, // left square bracket with tick in bottom corner 0x2991, // left angle bracket with dot 0x2993, // left arc less-than bracket 0x2995, // double left arc greater-than bracket 0x2997, // left black tortoise shell bracket 0x29D8, // left wiggly fence 0x29DA, // left double wiggly fence 0x29FC, // left-pointing curved angle bracket 0x3008, // CJK left angle bracket 0x300A, // CJK left double angle bracket 0x3010, // CJK left black lenticular bracket 0x3014, // CJK left tortoise shell bracket 0x3016, // CJK left white lenticular bracket 0x3018, // CJK left white tortoise shell bracket 0x301A, // CJK left white square bracket 0xFD3E, // Ornate left parenthesis 0xFE59, // small left parenthesis 0xFE5B, // small left curly bracket 0xFF08, // fullwidth left parenthesis 0xFF3B, // fullwidth left square bracket 0xFF5B, // fullwidth left curly bracket }; TEST_P(OpenParenParamTest, IsOpenParen) { std::string test_string = StringFromUnicodeChar(GetParam()); EXPECT_TRUE(IsOpenParen(test_string)); } INSTANTIATE_TEST_SUITE_P(IsOpenParenParamTest, OpenParenParamTest, ::testing::ValuesIn(open_paren_test_cases)); class CloseParenParamTest : public SentenceBreakingUtilsParamTest {}; const UChar close_paren_test_cases[] = { ')', ']', '>', '}', 0x207E, // superscript right parenthesis 0x208E, // subscript right parenthesis 0x27E7, // mathematical right white square bracket 0x27E9, // mathematical right angle bracket 0x27EB, // mathematical right double angle bracket 0x2984, // right white curly bracket 0x2986, // right white parenthesis 0x2988, // Z notation right image bracket 0x298A, // Z notation right binding bracket 0x298C, // right square bracket with underbar 0x298E, // right square bracket with tick in top corner 0x2990, // right square bracket with tick in bottom corner 0x2992, // right angle bracket with dot 0x2994, // right arc greater-than bracket 0x2996, // double right arc less-than bracket 0x2998, // right black tortoise shell bracket 0x29D9, // right wiggly fence 0x29DB, // right double wiggly fence 0x29FD, // right-pointing curved angle bracket 0x3009, // CJK right angle bracket 0x300B, // CJK right double angle bracket 0x3011, // CJK right black lenticular bracket 0x3015, // CJK right tortoise shell bracket 0x3017, // CJK right white lenticular bracket 0x3019, // CJK right white tortoise shell bracket 0x301B, // CJK right white square bracket 0xFD3F, // Ornate right parenthesis 0xFE5A, // small right parenthesis 0xFE5C, // small right curly bracket 0xFF09, // fullwidth right parenthesis 0xFF3D, // fullwidth right square bracket 0xFF5D, // fullwidth right curly bracket }; TEST_P(CloseParenParamTest, IsCloseParen) { std::string test_string = StringFromUnicodeChar(GetParam()); EXPECT_TRUE(IsCloseParen(test_string)); } INSTANTIATE_TEST_SUITE_P(IsCloseParenParamTest, CloseParenParamTest, ::testing::ValuesIn(close_paren_test_cases)); class IsPunctuationWordParamTest : public SentenceBreakingUtilsParamTest {}; const UChar punc_word_test_cases[] = { '(', '[', '<', '{', 0x207D, // superscript left parenthesis 0x208D, // subscript left parenthesis 0x27E6, // mathematical left white square bracket 0x27E8, // mathematical left angle bracket 0x27EA, // mathematical left double angle bracket 0x2983, // left white curly bracket 0x2985, // left white parenthesis 0x2987, // Z notation left image bracket 0x2989, // Z notation left binding bracket 0x298B, // left square bracket with underbar 0x298D, // left square bracket with tick in top corner 0x298F, // left square bracket with tick in bottom corner 0x2991, // left angle bracket with dot 0x2993, // left arc less-than bracket 0x2995, // double left arc greater-than bracket 0x2997, // left black tortoise shell bracket 0x29D8, // left wiggly fence 0x29DA, // left double wiggly fence 0x29FC, // left-pointing curved angle bracket 0x3008, // CJK left angle bracket 0x300A, // CJK left double angle bracket 0x3010, // CJK left black lenticular bracket 0x3014, // CJK left tortoise shell bracket 0x3016, // CJK left white lenticular bracket 0x3018, // CJK left white tortoise shell bracket 0x301A, // CJK left white square bracket 0xFD3E, // Ornate left parenthesis 0xFE59, // small left parenthesis 0xFE5B, // small left curly bracket 0xFF08, // fullwidth left parenthesis 0xFF3B, // fullwidth left square bracket 0xFF5B, // fullwidth left curly bracket '"', '\'', '`', 0xFF07, // fullwidth apostrophe 0xFF02, // fullwidth quotation mark 0x2018, // left single quotation mark (English, others) 0x201C, // left double quotation mark (English, others) 0x201B, // single high-reveresed-9 quotation mark (PropList.txt) 0x201A, // single low-9 quotation mark (Czech, German, Slovak) 0x201E, // double low-9 quotation mark (Czech, German, Slovak) 0x201F, // double high-reversed-9 quotation mark (PropList.txt) 0x2019, // right single quotation mark (Danish, Finnish, Swedish, Norw.) 0x201D, // right double quotation mark (Danish, Finnish, Swedish, Norw.) 0x2039, // single left-pointing angle quotation mark (French, others) 0x00AB, // left-pointing double angle quotation mark (French, others) 0x203A, // single right-pointing angle quotation mark (Slovenian, others) 0x00BB, // right-pointing double angle quotation mark (Slovenian, others) 0x300C, // left corner bracket (East Asian languages) 0xFE41, // presentation form for vertical left corner bracket 0xFF62, // halfwidth left corner bracket (East Asian languages) 0x300E, // left white corner bracket (East Asian languages) 0xFE43, // presentation form for vertical left white corner bracket 0x301D, // reversed double prime quotation mark (East Asian langs, horiz.) ')', ']', '>', '}', 0x207E, // superscript right parenthesis 0x208E, // subscript right parenthesis 0x27E7, // mathematical right white square bracket 0x27E9, // mathematical right angle bracket 0x27EB, // mathematical right double angle bracket 0x2984, // right white curly bracket 0x2986, // right white parenthesis 0x2988, // Z notation right image bracket 0x298A, // Z notation right binding bracket 0x298C, // right square bracket with underbar 0x298E, // right square bracket with tick in top corner 0x2990, // right square bracket with tick in bottom corner 0x2992, // right angle bracket with dot 0x2994, // right arc greater-than bracket 0x2996, // double right arc less-than bracket 0x2998, // right black tortoise shell bracket 0x29D9, // right wiggly fence 0x29DB, // right double wiggly fence 0x29FD, // right-pointing curved angle bracket 0x3009, // CJK right angle bracket 0x300B, // CJK right double angle bracket 0x3011, // CJK right black lenticular bracket 0x3015, // CJK right tortoise shell bracket 0x3017, // CJK right white lenticular bracket 0x3019, // CJK right white tortoise shell bracket 0x301B, // CJK right white square bracket 0xFD3F, // Ornate right parenthesis 0xFE5A, // small right parenthesis 0xFE5C, // small right curly bracket 0xFF09, // fullwidth right parenthesis 0xFF3D, // fullwidth right square bracket 0xFF5D, // fullwidth right curly bracket '\'', '"', '`', 0xFF07, // fullwidth apostrophe 0xFF02, // fullwidth quotation mark 0x2019, // right single quotation mark (English, others) 0x201D, // right double quotation mark (English, others) 0x2018, // left single quotation mark (Czech, German, Slovak) 0x201C, // left double quotation mark (Czech, German, Slovak) 0x203A, // single right-pointing angle quotation mark (French, others) 0x00BB, // right-pointing double angle quotation mark (French, others) 0x2039, // single left-pointing angle quotation mark (Slovenian, others) 0x00AB, // left-pointing double angle quotation mark (Slovenian, others) 0x300D, // right corner bracket (East Asian languages) 0xfe42, // presentation form for vertical right corner bracket 0xFF63, // halfwidth right corner bracket (East Asian languages) 0x300F, // right white corner bracket (East Asian languages) 0xfe44, // presentation form for vertical right white corner bracket 0x301F, // low double prime quotation mark (East Asian languages) 0x301E, // close double prime (East Asian languages written horizontally) 0x00A1, // Spanish inverted exclamation mark 0x00BF, // Spanish inverted question mark '.', '!', '?', 0x055C, // Armenian exclamation mark 0x055E, // Armenian question mark 0x0589, // Armenian full stop 0x061F, // Arabic question mark 0x06D4, // Arabic full stop 0x0700, // Syriac end of paragraph 0x0701, // Syriac supralinear full stop 0x0702, // Syriac sublinear full stop 0x0964, // Devanagari danda..Devanagari double danda 0x0965, 0x1362, // Ethiopic full stop 0x1367, // Ethiopic question mark 0x1368, // Ethiopic paragraph separator 0x104A, // Myanmar sign little section 0x104B, // Myanmar sign section 0x166E, // Canadian syllabics full stop 0x17d4, // Khmer sign khan 0x1803, // Mongolian full stop 0x1809, // Mongolian Manchu full stop 0x1944, // Limbu exclamation mark 0x1945, // Limbu question mark 0x203C, // double exclamation mark 0x203D, // interrobang 0x2047, // double question mark 0x2048, // question exclamation mark 0x2049, // exclamation question mark 0x3002, // ideographic full stop 0x037E, // Greek question mark 0xFE52, // small full stop 0xFE56, // small question mark 0xFE57, // small exclamation mark 0xFF01, // fullwidth exclamation mark 0xFF0E, // fullwidth full stop 0xFF1F, // fullwidth question mark 0xFF61, // halfwidth ideographic full stop 0x2026, // ellipsis 0x30fb, // Katakana middle dot 0xff65, // halfwidth Katakana middle dot 0x2040, // character tie '-', '~', 0x058a, // Armenian hyphen 0x1806, // Mongolian todo soft hyphen 0x2010, // hyphen..horizontal bar 0x2011, 0x2012, 0x2013, 0x2014, 0x2015, 0x2053, // swung dash -- from Table 6-3 of Unicode book 0x207b, // superscript minus 0x208b, // subscript minus 0x2212, // minus sign 0x301c, // wave dash 0x3030, // wavy dash 0xfe31, // presentation form for vertical em dash..en dash 0xfe32, 0xfe58, // small em dash 0xfe63, // small hyphen-minus 0xff0d, // fullwidth hyphen-minus ',', ':', ';', 0x00b7, // middle dot 0x0387, // Greek ano teleia 0x05c3, // Hebrew punctuation sof pasuq 0x060c, // Arabic comma 0x061b, // Arabic semicolon 0x066b, // Arabic decimal separator 0x066c, // Arabic thousands separator 0x0703, // Syriac contraction and others 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x70a, 0x070c, // Syric harklean metobelus 0x0e5a, // Thai character angkhankhu 0x0e5b, // Thai character khomut 0x0f08, // Tibetan mark sbrul shad 0x0f0d, // Tibetan mark shad..Tibetan mark rgya gram shad 0x0f0e, 0x0f0f, 0x0f10, 0x0f11, 0x0f12, 0x1361, // Ethiopic wordspace 0x1363, // other Ethiopic chars 0x1364, 0x1365, 0x1366, 0x166d, // Canadian syllabics chi sign 0x16eb, // Runic single punctuation..Runic cross punctuation 0x16ed, 0x17d5, // Khmer sign camnuc pii huuh and other 0x17d6, 0x17da, // Khmer sign koomut 0x1802, // Mongolian comma 0x1804, // Mongolian four dots and other 0x1805, 0x1808, // Mongolian manchu comma 0x3001, // ideographic comma 0xfe50, // small comma and others 0xfe51, 0xfe54, // small semicolon and other 0xfe55, 0xff0c, // fullwidth comma 0xff0e, // fullwidth stop..fullwidth solidus 0xff0f, 0xff1a, // fullwidth colon..fullwidth semicolon 0xff1b, 0xff64, // halfwidth ideographic comma 0x2016, // double vertical line 0x2032, 0x2033, 0x2034, // prime..triple prime 0xfe61, // small asterisk 0xfe68, // small reverse solidus 0xff3c, // fullwidth reverse solidus }; TEST_P(IsPunctuationWordParamTest, IsPunctuation) { std::string test_string = StringFromUnicodeChar(GetParam()); EXPECT_TRUE(IsPunctuationWord(test_string)); } INSTANTIATE_TEST_SUITE_P(IsPuncWordParamTest, IsPunctuationWordParamTest, ::testing::ValuesIn(punc_word_test_cases)); class IsEllipsisTest : public ::testing::Test {}; TEST_F(IsEllipsisTest, IsEllipsis) { int offset; EXPECT_TRUE(IsEllipsis("...", &offset)); EXPECT_EQ(offset, 3); EXPECT_TRUE(IsEllipsis("…", &offset)); EXPECT_EQ(offset, 3); EXPECT_FALSE(IsEllipsis("@", &offset)); EXPECT_EQ(offset, 1); } class IsWhiteSpaceTest : public ::testing::Test {}; TEST_F(IsWhiteSpaceTest, IsWhiteSpace) { EXPECT_TRUE(IsWhiteSpace(" ")); EXPECT_TRUE(IsWhiteSpace("\n")); EXPECT_TRUE(IsWhiteSpace(" ")); EXPECT_FALSE(IsWhiteSpace("@")); EXPECT_FALSE(IsWhiteSpace("w")); } class IsAcronymTest : public ::testing::Test {}; TEST_F(IsAcronymTest, IsAcronym) { int offset = 0; EXPECT_TRUE(IsPeriodSeparatedAcronym("U.S.", &offset)); EXPECT_EQ(offset, 4); offset = 0; EXPECT_TRUE(IsPeriodSeparatedAcronym("E.A.T.", &offset)); EXPECT_EQ(offset, 6); offset = 0; EXPECT_TRUE(IsPeriodSeparatedAcronym("A.B.C.D.E.F.", &offset)); EXPECT_EQ(offset, 12); offset = 0; EXPECT_FALSE(IsPeriodSeparatedAcronym("X.", &offset)); EXPECT_FALSE(IsPeriodSeparatedAcronym("US", &offset)); EXPECT_FALSE(IsPeriodSeparatedAcronym("U-S", &offset)); } class EmoticonParamTest : public SentenceBreakingUtilsStringParamTest {}; static const char* const emoticon_test_cases[] = {":(:)", ":)", ":(", ":o)", ":]", ":3", ":>", "=]", "=)", ":}", ":^)", ":-D", ":-)))))", ":-))))", ":-)))", ":-))", ":-)", ">:[", ":-(", ":(", ":-c", ":c", ":-<", ":<", ":-[", ":[", ":{", ";(", ":-||", ":@", ">:(", ":'-(", ":'(", ":'-)", ":')", "D:<", ">:O", ":-O", ":-o", ":*", ":-*", ":^*", ";-)", ";)", "*-)", "*)", ";-]", ";]", ";^)", ":-,", ">:P", ":-P", ":p", "=p", ":-p", "=p", ":P", "=P", ";p", ";-p", ";P", ";-P", ">:\\", ">:/", ":-/", ":-.", ":/", ":\\", "=/", "=\\", ":|", ":-|", ":$", ":-#", ":#", "O:-)", "0:-)", "0:)", "0;^)", ">:)", ">;)", ">:-)", "}:-)", "}:)", "3:-)", ">_>^", "^<_<", "|;-)", "|-O", ":-J", ":-&", ":&", "#-)", "<3", "8-)", "^_^", ":D", ":-D", "=D", "^_^;;", "O=)", "}=)", "B)", "B-)", "=|", "-_-", "o_o;", "u_u", ":-\\", ":s", ":S", ":-s", ":-S", ";*", ";-*" "=(", ">.<", ">:-(", ">:(", ">=(", ";_;", "T_T", "='(", ">_<", "D:", ":o", ":-o", "=o", "o.o", ":O", ":-O", "=O", "O.O", "x_x", "X-(", "X(", "X-o", "X-O", ":X)", "(=^.^=)", "(=^..^=)", "=^_^=", "-<@%", ":(|)", "(]:{", "<\\3", "~@~", "8'(", "XD", "DX"}; TEST_P(EmoticonParamTest, IsEmoticon) { int offset = 0; EXPECT_TRUE(IsEmoticon(GetParam(), &offset)); } INSTANTIATE_TEST_SUITE_P(IsEmoticonParamTest, EmoticonParamTest, ::testing::ValuesIn(emoticon_test_cases)); class IsEmoticonTest : public ::testing::Test {}; TEST_F(IsEmoticonTest, IsEmoticon) { int offset = 0; EXPECT_TRUE(IsEmoticon(">:-(", &offset)); EXPECT_FALSE(IsEmoticon("w", &offset)); EXPECT_FALSE(IsEmoticon(":", &offset)); } TEST(SentenceFragmenterTest, Basic) { // 1 // 012345678901234 string test_input = "Hello. Foo bar!"; SentenceFragmenterV2 fragmenter(test_input); std::vector<SentenceFragment> fragments; EXPECT_TRUE(fragmenter.FindFragments(&fragments).ok()); EXPECT_EQ(fragments[0].start, 0); EXPECT_EQ(fragments[0].limit, 6); EXPECT_EQ(fragments[1].start, 7); EXPECT_EQ(fragments[1].limit, 15); } TEST(SentenceFragmenterTest, BasicEllipsis) { // 1 // 012345678901234 string test_input = "Hello...foo bar"; SentenceFragmenterV2 fragmenter(test_input); std::vector<SentenceFragment> fragments; EXPECT_TRUE(fragmenter.FindFragments(&fragments).ok()); EXPECT_EQ(fragments[0].start, 0); EXPECT_EQ(fragments[0].limit, 8); EXPECT_EQ(fragments[1].start, 8); EXPECT_EQ(fragments[1].limit, 15); } TEST(SentenceFragmenterTest, Parentheses) { // 1 2 // 012345678901234567890123456789 string test_input = "Hello (who are you...) foo bar"; SentenceFragmenterV2 fragmenter(test_input); std::vector<SentenceFragment> fragments; EXPECT_TRUE(fragmenter.FindFragments(&fragments).ok()); EXPECT_EQ(fragments[0].start, 0); EXPECT_EQ(fragments[0].limit, 22); EXPECT_EQ(fragments[1].start, 23); EXPECT_EQ(fragments[1].limit, 30); } TEST(SentenceFragmenterTest, MidFragmentParentheses) { // 1 2 // 012345678901234567890123456789 string test_input = "Hello (who are you) world? Foo bar"; SentenceFragmenterV2 fragmenter(test_input); std::vector<SentenceFragment> fragments; EXPECT_TRUE(fragmenter.FindFragments(&fragments).ok()); EXPECT_EQ(fragments[0].start, 0); EXPECT_EQ(fragments[0].limit, 26); EXPECT_EQ(fragments[1].start, 27); EXPECT_EQ(fragments[1].limit, 34); } TEST(SentenceFragmenterTest, PunctuationAfterParentheses) { // 1 2 // 01234567890123456789012345678 string test_input = "Hello (who are you)? Foo bar!"; SentenceFragmenterV2 fragmenter(test_input); std::vector<SentenceFragment> fragments; EXPECT_TRUE(fragmenter.FindFragments(&fragments).ok()); EXPECT_EQ(fragments[0].start, 0); EXPECT_EQ(fragments[0].limit, 20); EXPECT_EQ(fragments[1].start, 21); EXPECT_EQ(fragments[1].limit, 29); } TEST(SentenceFragmenterTest, ManyFinalPunctuations) { // 1 2 // 0123456789012345678901234 string test_input = "Hello!!!!! Who are you??"; SentenceFragmenterV2 fragmenter(test_input); std::vector<SentenceFragment> fragments; EXPECT_TRUE(fragmenter.FindFragments(&fragments).ok()); EXPECT_EQ(fragments[0].start, 0); EXPECT_EQ(fragments[0].limit, 10); EXPECT_EQ(fragments[1].start, 11); EXPECT_EQ(fragments[1].limit, 24); } TEST(SentenceFragmenterTest, NewLine) { // 1 2 3 // 012345678901234567890 1 23456 7 89012 3 45678 string test_input = "Who let the dogs out?\r\nWho?\r\nWho?\r\nWho?"; SentenceFragmenterV2 fragmenter(test_input); std::vector<SentenceFragment> fragments; EXPECT_TRUE(fragmenter.FindFragments(&fragments).ok()); EXPECT_EQ(fragments[0].start, 0); EXPECT_EQ(fragments[0].limit, 21); EXPECT_EQ(fragments[1].start, 23); EXPECT_EQ(fragments[1].limit, 27); EXPECT_EQ(fragments[2].start, 29); EXPECT_EQ(fragments[2].limit, 33); EXPECT_EQ(fragments[3].start, 35); EXPECT_EQ(fragments[3].limit, 39); } TEST(SentenceFragmenterTest, WhiteSpaceInPunctuation) { // 1 2 // 0123456789012345678901234 string test_input = "Hello?? !!! Who are you??"; SentenceFragmenterV2 fragmenter(test_input); std::vector<SentenceFragment> fragments; EXPECT_TRUE(fragmenter.FindFragments(&fragments).ok()); EXPECT_EQ(fragments[0].start, 0); EXPECT_EQ(fragments[0].limit, 7); EXPECT_EQ(fragments[1].start, 8); EXPECT_EQ(fragments[1].limit, 11); EXPECT_EQ(fragments[2].start, 12); EXPECT_EQ(fragments[2].limit, 25); } } // namespace TEST(FragmentBoundaryMatchTest, NoStateChange) { FragmentBoundaryMatch f; // || // 012345678901234 string test_input = "Hello...foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_FALSE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), -1); EXPECT_EQ(f.first_close_punc_index(), -1); EXPECT_EQ(f.limit_index(), 1); EXPECT_EQ(f.state(), FragmentBoundaryMatch::INITIAL_STATE); } TEST(FragmentBoundaryMatchTest, BasicEllipsis) { FragmentBoundaryMatch f; // | | // 0123456789 string test_input = "...foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 3); EXPECT_EQ(f.limit_index(), 3); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, BasicPeriod) { FragmentBoundaryMatch f; // || // 0123456789 string test_input = ". Foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 1); EXPECT_EQ(f.limit_index(), 1); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, BasicAcronym) { FragmentBoundaryMatch f; // | | // 0123456789 string test_input = "A.B. xyz"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 4); EXPECT_EQ(f.limit_index(), 4); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, LongerAcronym) { FragmentBoundaryMatch f; // | | // 0123456789 string test_input = "I.B.M. yo"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 6); EXPECT_EQ(f.limit_index(), 6); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, Emoticon) { FragmentBoundaryMatch f; // | | // 0123456789012 string test_input = ">:-( hello..."; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 4); EXPECT_EQ(f.limit_index(), 4); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, ParensWithEllipsis) { FragmentBoundaryMatch f; // || // 0123456789012345 string test_input = ".foo...) foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 1); EXPECT_EQ(f.limit_index(), 1); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, ClosingParenWithEllipsis) { FragmentBoundaryMatch f; // | | // 012345678901 string test_input = "...) foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 3); EXPECT_EQ(f.limit_index(), 3); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, BeginAndEndParenWithEllipsis) { FragmentBoundaryMatch f; // || // 0123456789012 string test_input = "(...) foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_FALSE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), -1); EXPECT_EQ(f.first_close_punc_index(), -1); EXPECT_EQ(f.limit_index(), 1); EXPECT_EQ(f.state(), FragmentBoundaryMatch::INITIAL_STATE); // | | // 0123456789012 test_input = "...) foo bar"; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 3); EXPECT_EQ(f.limit_index(), 3); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, AcronymInSentence) { FragmentBoundaryMatch f; // | | // 0123456789012 string test_input = "U.S. don't be surprised."; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 4); EXPECT_EQ(f.limit_index(), 4); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, HelloWithEllipsis) { FragmentBoundaryMatch f; // || // 01234567890 string test_input = "o...foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_FALSE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), -1); EXPECT_EQ(f.first_close_punc_index(), -1); EXPECT_EQ(f.limit_index(), 1); EXPECT_EQ(f.state(), FragmentBoundaryMatch::INITIAL_STATE); // | | // 0123456789 test_input = "...foo bar"; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 3); EXPECT_EQ(f.limit_index(), 3); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } TEST(FragmentBoundaryMatchTest, ThreeStatesWithClosigParen) { FragmentBoundaryMatch f; // || // 0123456789012 string test_input = "w...) foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_FALSE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), -1); EXPECT_EQ(f.first_close_punc_index(), -1); EXPECT_EQ(f.limit_index(), 1); EXPECT_EQ(f.state(), FragmentBoundaryMatch::INITIAL_STATE); // | | // 0123456789012 test_input = "...) foo bar"; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 3); EXPECT_EQ(f.limit_index(), 3); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); // || // 0123456789012 test_input = ") foo bar"; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 0); EXPECT_EQ(f.limit_index(), 1); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_CLOSE_PUNC); // || // 0123456789012 test_input = " foo bar"; EXPECT_FALSE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 0); EXPECT_EQ(f.limit_index(), 1); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_CLOSE_PUNC); } TEST(FragmentBoundaryMatchTest, NoTransition) { FragmentBoundaryMatch f; // | | // 0123456789012 string test_input = "...foo bar"; int index = 0; EXPECT_TRUE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 3); EXPECT_EQ(f.limit_index(), 3); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); // || // 0123456789012 test_input = "foo bar"; EXPECT_FALSE(f.Advance(index, test_input)); EXPECT_TRUE(f.GotTerminalPunc()); EXPECT_EQ(f.first_terminal_punc_index(), 0); EXPECT_EQ(f.first_close_punc_index(), 3); EXPECT_EQ(f.limit_index(), 3); EXPECT_EQ(f.state(), FragmentBoundaryMatch::COLLECTING_TERMINAL_PUNC); } } // namespace text } // namespace tensorflow
40.489478
80
0.551599
[ "vector" ]
3331c3a8e15f998bea31b7c5b3b81c9fc46a6811
1,789
cpp
C++
aws-cpp-sdk-gamelift/source/model/ResourceCreationLimitPolicy.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-gamelift/source/model/ResourceCreationLimitPolicy.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-gamelift/source/model/ResourceCreationLimitPolicy.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/gamelift/model/ResourceCreationLimitPolicy.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace GameLift { namespace Model { ResourceCreationLimitPolicy::ResourceCreationLimitPolicy() : m_newGameSessionsPerCreator(0), m_newGameSessionsPerCreatorHasBeenSet(false), m_policyPeriodInMinutes(0), m_policyPeriodInMinutesHasBeenSet(false) { } ResourceCreationLimitPolicy::ResourceCreationLimitPolicy(JsonView jsonValue) : m_newGameSessionsPerCreator(0), m_newGameSessionsPerCreatorHasBeenSet(false), m_policyPeriodInMinutes(0), m_policyPeriodInMinutesHasBeenSet(false) { *this = jsonValue; } ResourceCreationLimitPolicy& ResourceCreationLimitPolicy::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("NewGameSessionsPerCreator")) { m_newGameSessionsPerCreator = jsonValue.GetInteger("NewGameSessionsPerCreator"); m_newGameSessionsPerCreatorHasBeenSet = true; } if(jsonValue.ValueExists("PolicyPeriodInMinutes")) { m_policyPeriodInMinutes = jsonValue.GetInteger("PolicyPeriodInMinutes"); m_policyPeriodInMinutesHasBeenSet = true; } return *this; } JsonValue ResourceCreationLimitPolicy::Jsonize() const { JsonValue payload; if(m_newGameSessionsPerCreatorHasBeenSet) { payload.WithInteger("NewGameSessionsPerCreator", m_newGameSessionsPerCreator); } if(m_policyPeriodInMinutesHasBeenSet) { payload.WithInteger("PolicyPeriodInMinutes", m_policyPeriodInMinutes); } return payload; } } // namespace Model } // namespace GameLift } // namespace Aws
22.64557
88
0.779765
[ "model" ]
3335307f936f041a9c07714653918d3a58b93d7c
5,911
cc
C++
ros/2/src/openvslam/src/run_localization.cc
surfii3z/openvslam-1
b6c40f671f4fa226b933df47dd1b466dbfdab2ee
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
ros/2/src/openvslam/src/run_localization.cc
surfii3z/openvslam-1
b6c40f671f4fa226b933df47dd1b466dbfdab2ee
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
ros/2/src/openvslam/src/run_localization.cc
surfii3z/openvslam-1
b6c40f671f4fa226b933df47dd1b466dbfdab2ee
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
#ifdef USE_PANGOLIN_VIEWER #include <pangolin_viewer/viewer.h> #elif USE_SOCKET_PUBLISHER #include <socket_publisher/publisher.h> #endif #include <openvslam/system.h> #include <openvslam/config.h> #include <openvslam_ros.h> #include <iostream> #include <chrono> #include <numeric> #include <opencv2/core/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui/highgui.hpp> #include <spdlog/spdlog.h> #include <popl.hpp> #ifdef USE_STACK_TRACE_LOGGER #include <glog/logging.h> #endif #ifdef USE_GOOGLE_PERFTOOLS #include <gperftools/profiler.h> #endif void localization(const std::shared_ptr<openvslam::config>& cfg, const std::string& vocab_file_path, const std::string& mask_img_path, const std::string& map_db_path, const bool mapping) { std::shared_ptr<openvslam_ros::system> ros; if (cfg->camera_->setup_type_ == openvslam::camera::setup_type_t::Monocular) { ros = std::make_shared<openvslam_ros::mono>(cfg, vocab_file_path, mask_img_path); } else { throw std::runtime_error("Invalid setup type: " + cfg->camera_->get_setup_type_string()); } auto& SLAM = ros->SLAM_; // load the prebuilt map SLAM.load_map_database(map_db_path); // startup the SLAM process (it does not need initialization of a map) SLAM.startup(false); // select to activate the mapping module or not if (mapping) { SLAM.enable_mapping_module(); } else { SLAM.disable_mapping_module(); } // create a viewer object // and pass the frame_publisher and the map_publisher #ifdef USE_PANGOLIN_VIEWER pangolin_viewer::viewer viewer(cfg, &SLAM, SLAM.get_frame_publisher(), SLAM.get_map_publisher()); #elif USE_SOCKET_PUBLISHER socket_publisher::publisher publisher(cfg, &SLAM, SLAM.get_frame_publisher(), SLAM.get_map_publisher()); #endif // TODO: Pangolin needs to run in the main thread on OSX // run the viewer in this thread #ifdef USE_PANGOLIN_VIEWER std::thread thread([&]() { viewer.run(); if (SLAM.terminate_is_requested()) { // wait until the loop BA is finished while (SLAM.loop_BA_is_running()) { std::this_thread::sleep_for(std::chrono::microseconds(5000)); } rclcpp::shutdown(); } }); #elif USE_SOCKET_PUBLISHER std::thread thread([&]() { publisher.run(); if (SLAM.terminate_is_requested()) { // wait until the loop BA is finished while (SLAM.loop_BA_is_running()) { std::this_thread::sleep_for(std::chrono::microseconds(5000)); } rclcpp::shutdown(); } }); #endif rclcpp::Rate pub_rate(10); while (rclcpp::ok()) { ros->publish_pose(); ros->exec_.spin_some(); pub_rate.sleep(); } // automatically close the viewer #ifdef USE_PANGOLIN_VIEWER viewer.request_terminate(); thread.join(); #elif USE_SOCKET_PUBLISHER publisher.request_terminate(); thread.join(); #endif // shutdown the SLAM process SLAM.shutdown(); auto& track_times = ros->track_times_; if (track_times.size()) { std::sort(track_times.begin(), track_times.end()); const auto total_track_time = std::accumulate(track_times.begin(), track_times.end(), 0.0); std::cout << "median tracking time: " << track_times.at(track_times.size() / 2) << "[s]" << std::endl; std::cout << "mean tracking time: " << total_track_time / track_times.size() << "[s]" << std::endl; } } int main(int argc, char* argv[]) { #ifdef USE_STACK_TRACE_LOGGER google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); #endif rclcpp::init(argc, argv); rclcpp::uninstall_signal_handlers(); // create options popl::OptionParser op("Allowed options"); auto help = op.add<popl::Switch>("h", "help", "produce help message"); auto vocab_file_path = op.add<popl::Value<std::string>>("v", "vocab", "vocabulary file path"); auto setting_file_path = op.add<popl::Value<std::string>>("c", "config", "setting file path"); auto map_db_path = op.add<popl::Value<std::string>>("p", "map-db", "path to a prebuilt map database"); auto mapping = op.add<popl::Switch>("", "mapping", "perform mapping as well as localization"); auto mask_img_path = op.add<popl::Value<std::string>>("", "mask", "mask image path", ""); auto debug_mode = op.add<popl::Switch>("", "debug", "debug mode"); try { op.parse(argc, argv); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; std::cerr << std::endl; std::cerr << op << std::endl; return EXIT_FAILURE; } // check validness of options if (help->is_set()) { std::cerr << op << std::endl; return EXIT_FAILURE; } if (!vocab_file_path->is_set() || !setting_file_path->is_set() || !map_db_path->is_set()) { std::cerr << "invalid arguments" << std::endl; std::cerr << std::endl; std::cerr << op << std::endl; return EXIT_FAILURE; } // setup logger spdlog::set_pattern("[%Y-%m-%d %H:%M:%S.%e] %^[%L] %v%$"); if (debug_mode->is_set()) { spdlog::set_level(spdlog::level::debug); } else { spdlog::set_level(spdlog::level::info); } // load configuration std::shared_ptr<openvslam::config> cfg; try { cfg = std::make_shared<openvslam::config>(setting_file_path->value()); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } #ifdef USE_GOOGLE_PERFTOOLS ProfilerStart("slam.prof"); #endif localization(cfg, vocab_file_path->value(), mask_img_path->value(), map_db_path->value(), mapping->is_set()); #ifdef USE_GOOGLE_PERFTOOLS ProfilerStop(); #endif return EXIT_SUCCESS; }
32.125
113
0.636441
[ "object" ]
3338819dcbbc893262e6b64bcfeb05767717d62e
9,071
cpp
C++
be/test/runtime/tmp_file_mgr_test.cpp
kuolei/incubator-doris
b14678c0021896f11efdfdaa3e2dad15b2d4868d
[ "Apache-2.0" ]
2
2022-01-26T15:24:34.000Z
2022-02-10T09:07:33.000Z
be/test/runtime/tmp_file_mgr_test.cpp
aiwenmo/incubator-doris
b33ab960a840553d2877d56c5c051a94df71917f
[ "Apache-2.0" ]
2
2018-08-27T07:42:21.000Z
2018-08-29T06:37:41.000Z
be/test/runtime/tmp_file_mgr_test.cpp
aiwenmo/incubator-doris
b33ab960a840553d2877d56c5c051a94df71917f
[ "Apache-2.0" ]
1
2022-02-28T09:53:30.000Z
2022-02-28T09:53:30.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "runtime/tmp_file_mgr.h" #include <gtest/gtest.h> #include <cstdlib> #include <filesystem> #include "gen_cpp/Types_types.h" // for TUniqueId #include "util/disk_info.h" #include "util/filesystem_util.h" #include "util/logging.h" #include "util/metrics.h" using std::filesystem::path; using std::string; using std::vector; using std::set; namespace doris { class TmpFileMgrTest : public ::testing::Test { protected: // Check that metric values are consistent with TmpFileMgr state. void check_metrics(TmpFileMgr* tmp_file_mgr) { std::vector<TmpFileMgr::DeviceId> active = tmp_file_mgr->active_tmp_devices(); int64_t active_metric = DorisMetrics::instance() ->metric_registry() ->get_entity("server") ->get_metric("active_scratch_dirs") .value(); EXPECT_EQ(active.size(), active_metric); } }; // Regression test for IMPALA-2160. Verify that temporary file manager allocates blocks // at the expected file offsets and expands the temporary file to the correct size. TEST_F(TmpFileMgrTest, TestFileAllocation) { TmpFileMgr tmp_file_mgr; EXPECT_TRUE(tmp_file_mgr.init().ok()); // Default configuration should give us one temporary device. EXPECT_EQ(1, tmp_file_mgr.num_active_tmp_devices()); std::vector<TmpFileMgr::DeviceId> tmp_devices = tmp_file_mgr.active_tmp_devices(); EXPECT_EQ(1, tmp_devices.size()); TUniqueId id; TmpFileMgr::File* file; Status status = tmp_file_mgr.get_file(tmp_devices[0], id, &file); EXPECT_TRUE(status.ok()); EXPECT_TRUE(file != nullptr); // Apply writes of variable sizes and check space was allocated correctly. int64_t write_sizes[] = {1, 10, 1024, 4, 1024 * 1024 * 8, 1024 * 1024 * 8, 16, 10}; int num_write_sizes = sizeof(write_sizes) / sizeof(write_sizes[0]); int64_t next_offset = 0; for (int i = 0; i < num_write_sizes; ++i) { int64_t offset; status = file->allocate_space(write_sizes[i], &offset); EXPECT_TRUE(status.ok()); EXPECT_EQ(next_offset, offset); next_offset = offset + write_sizes[i]; EXPECT_EQ(next_offset, std::filesystem::file_size(file->path())); } // Check that cleanup is correct. status = file->remove(); EXPECT_TRUE(status.ok()); EXPECT_FALSE(std::filesystem::exists(file->path())); // check_metrics(&tmp_file_mgr); } // Test that we can do initialization with two directories on same device and // that validations prevents duplication of directories. TEST_F(TmpFileMgrTest, TestOneDirPerDevice) { std::vector<string> tmp_dirs; tmp_dirs.push_back("/tmp/tmp-file-mgr-test.1"); tmp_dirs.push_back("/tmp/tmp-file-mgr-test.2"); for (int i = 0; i < tmp_dirs.size(); ++i) { EXPECT_TRUE(FileSystemUtil::create_directory(tmp_dirs[i]).ok()); } TmpFileMgr tmp_file_mgr; tmp_file_mgr.init_custom(tmp_dirs, true); // Only the first directory should be used. EXPECT_EQ(1, tmp_file_mgr.num_active_tmp_devices()); std::vector<TmpFileMgr::DeviceId> devices = tmp_file_mgr.active_tmp_devices(); EXPECT_EQ(1, devices.size()); TUniqueId id; TmpFileMgr::File* file; EXPECT_TRUE(tmp_file_mgr.get_file(devices[0], id, &file).ok()); // Check the prefix is the expected temporary directory. EXPECT_EQ(0, file->path().find(tmp_dirs[0])); FileSystemUtil::remove_paths(tmp_dirs); // check_metrics(&tmp_file_mgr); } // Test that we can do custom initialization with two dirs on same device. TEST_F(TmpFileMgrTest, TestMultiDirsPerDevice) { std::vector<string> tmp_dirs; tmp_dirs.push_back("/tmp/tmp-file-mgr-test.1"); tmp_dirs.push_back("/tmp/tmp-file-mgr-test.2"); for (int i = 0; i < tmp_dirs.size(); ++i) { EXPECT_TRUE(FileSystemUtil::create_directory(tmp_dirs[i]).ok()); } TmpFileMgr tmp_file_mgr; tmp_file_mgr.init_custom(tmp_dirs, false); // Both directories should be used. EXPECT_EQ(2, tmp_file_mgr.num_active_tmp_devices()); std::vector<TmpFileMgr::DeviceId> devices = tmp_file_mgr.active_tmp_devices(); EXPECT_EQ(2, devices.size()); for (int i = 0; i < tmp_dirs.size(); ++i) { EXPECT_EQ(0, tmp_file_mgr.get_tmp_dir_path(devices[i]).find(tmp_dirs[i])); TUniqueId id; TmpFileMgr::File* file; EXPECT_TRUE(tmp_file_mgr.get_file(devices[i], id, &file).ok()); // Check the prefix is the expected temporary directory. EXPECT_EQ(0, file->path().find(tmp_dirs[i])); } FileSystemUtil::remove_paths(tmp_dirs); // check_metrics(&tmp_file_mgr); } // Test that reporting a write error is possible but does not result in // blacklisting, which is disabled. TEST_F(TmpFileMgrTest, TestReportError) { std::vector<string> tmp_dirs; tmp_dirs.push_back("/tmp/tmp-file-mgr-test.1"); tmp_dirs.push_back("/tmp/tmp-file-mgr-test.2"); for (int i = 0; i < tmp_dirs.size(); ++i) { EXPECT_TRUE(FileSystemUtil::create_directory(tmp_dirs[i]).ok()); } TmpFileMgr tmp_file_mgr; tmp_file_mgr.init_custom(tmp_dirs, false); // Both directories should be used. std::vector<TmpFileMgr::DeviceId> devices = tmp_file_mgr.active_tmp_devices(); EXPECT_EQ(2, devices.size()); // check_metrics(&tmp_file_mgr); // Inject an error on one device so that we can validate it is handled correctly. TUniqueId id; int good_device = 0; int bad_device = 1; TmpFileMgr::File* bad_file; EXPECT_TRUE(tmp_file_mgr.get_file(devices[bad_device], id, &bad_file).ok()); // ErrorMsg errmsg(TErrorCode::GENERAL, "A fake error"); // bad_file->ReportIOError(errmsg); bad_file->report_io_error("A fake error"); // Blacklisting is disabled. EXPECT_FALSE(bad_file->is_blacklisted()); // The second device should still be active. EXPECT_EQ(2, tmp_file_mgr.num_active_tmp_devices()); std::vector<TmpFileMgr::DeviceId> devices_after = tmp_file_mgr.active_tmp_devices(); EXPECT_EQ(2, devices_after.size()); // check_metrics(&tmp_file_mgr); // Attempts to expand bad file should succeed. int64_t offset; EXPECT_TRUE(bad_file->allocate_space(128, &offset).ok()); EXPECT_TRUE(bad_file->remove().ok()); // The good device should still be usable. TmpFileMgr::File* good_file; EXPECT_TRUE(tmp_file_mgr.get_file(devices[good_device], id, &good_file).ok()); EXPECT_TRUE(good_file != nullptr); EXPECT_TRUE(good_file->allocate_space(128, &offset).ok()); // Attempts to allocate new files on bad device should succeed. EXPECT_TRUE(tmp_file_mgr.get_file(devices[bad_device], id, &bad_file).ok()); FileSystemUtil::remove_paths(tmp_dirs); // check_metrics(&tmp_file_mgr); } TEST_F(TmpFileMgrTest, TestAllocateFails) { string tmp_dir("/tmp/tmp-file-mgr-test.1"); string scratch_subdir = tmp_dir + "/doris-scratch"; std::vector<string> tmp_dirs(1, tmp_dir); EXPECT_TRUE(FileSystemUtil::create_directory(tmp_dir).ok()); TmpFileMgr tmp_file_mgr; tmp_file_mgr.init_custom(tmp_dirs, false); TUniqueId id; TmpFileMgr::File* allocated_file1; TmpFileMgr::File* allocated_file2; int64_t offset; EXPECT_TRUE(tmp_file_mgr.get_file(0, id, &allocated_file1).ok()); EXPECT_TRUE(tmp_file_mgr.get_file(0, id, &allocated_file2).ok()); EXPECT_TRUE(allocated_file1->allocate_space(1, &offset).ok()); // Make scratch non-writable and test for allocation errors at different stages: // new file creation, files with no allocated blocks. files with allocated space. chmod(scratch_subdir.c_str(), 0); // allocated_file1 already has space allocated. EXPECT_FALSE(allocated_file1->allocate_space(1, &offset).ok()); // allocated_file2 has no space allocated. EXPECT_FALSE(allocated_file2->allocate_space(1, &offset).ok()); // Creating a new File object can succeed because it is not immediately created on disk. TmpFileMgr::File* unallocated_file; EXPECT_TRUE(tmp_file_mgr.get_file(0, id, &unallocated_file).ok()); chmod(scratch_subdir.c_str(), S_IRWXU); FileSystemUtil::remove_paths(tmp_dirs); } } // end namespace doris
41.610092
92
0.696616
[ "object", "vector" ]
333c7a12670dc858285af01e1fd4913a733bd14b
8,016
cc
C++
clipboard.cc
dlabella/win-clipboard
d5137ccff6ecba39369d74d20a7ff6e5ae5caef1
[ "MIT" ]
null
null
null
clipboard.cc
dlabella/win-clipboard
d5137ccff6ecba39369d74d20a7ff6e5ae5caef1
[ "MIT" ]
null
null
null
clipboard.cc
dlabella/win-clipboard
d5137ccff6ecba39369d74d20a7ff6e5ae5caef1
[ "MIT" ]
null
null
null
//#include <node.h> //#include <v8.h> #include <nan.h> #include <Windows.h> #include <map> using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; using v8::Array; using v8::Boolean; using v8::Number; using v8::Exception; std::map<int,std::wstring> standardFormats; void initFormats() { standardFormats[ 2 ] = std::wstring( L"CF_BITMAP" ); standardFormats[ 8 ] = std::wstring( L"CF_DIB" ); standardFormats[ 17 ] = std::wstring( L"CF_DIBV5" ); standardFormats[ 5 ] = std::wstring( L"CF_DIF" ); standardFormats[ 0x0082 ] = std::wstring( L"CF_DSPBITMAP" ); standardFormats[ 0x008E ] = std::wstring( L"CF_DSPENHMETAFILE" ); standardFormats[ 0x0083 ] = std::wstring( L"CF_DSPMETAFILEPICT" ); standardFormats[ 0x0081 ] = std::wstring( L"CF_DSPTEXT" ); standardFormats[ 14 ] = std::wstring( L"CF_ENHMETAFILE" ); standardFormats[ 0x0300 ] = std::wstring( L"CF_GDIOBJFIRST" ); standardFormats[ 0x03FF ] = std::wstring( L"CF_GDIOBJLAST" ); standardFormats[ 15 ] = std::wstring( L"CF_HDROP" ); standardFormats[ 16 ] = std::wstring( L"CF_LOCALE" ); standardFormats[ 3 ] = std::wstring( L"CF_METAFILEPICT" ); standardFormats[ 7 ] = std::wstring( L"CF_OEMTEXT" ); standardFormats[ 0x0080 ] = std::wstring( L"CF_OWNERDISPLAY" ); standardFormats[ 9 ] = std::wstring( L"CF_PALETTE" ); standardFormats[ 10 ] = std::wstring( L"CF_PENDATA" ); standardFormats[ 0x0200 ] = std::wstring( L"CF_PRIVATEFIRST" ); standardFormats[ 0x02FF ] = std::wstring( L"CF_PRIVATELAST" ); standardFormats[ 11 ] = std::wstring( L"CF_RIFF" ); standardFormats[ 4 ] = std::wstring( L"CF_SYLK" ); standardFormats[ 1 ] = std::wstring( L"CF_TEXT" ); standardFormats[ 6 ] = std::wstring( L"CF_TIFF" ); standardFormats[ 13 ] = std::wstring( L"CF_UNICODETEXT" ); standardFormats[ 12 ] = std::wstring( L"CF_WAVE" ); } std::string utf8_encode(const std::wstring &wstr) { if( wstr.empty() ) return std::string(); int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); std::string strTo( size_needed, 0 ); WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); return strTo; } // Convert an UTF8 string to a wide Unicode String std::wstring utf8_decode(const std::string &str) { if( str.empty() ) return std::wstring(); int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); std::wstring wstrTo( size_needed, 0 ); MultiByteToWideChar (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed); return wstrTo; } UINT GetFormatId( const std::wstring &formatName ) { UINT formatId = 0; for (auto& item: standardFormats) { if ( item.second.compare( formatName ) == 0 ) { formatId = item.first; } } if ( formatId == 0 ) { int formatsCount = CountClipboardFormats(); UINT lastClipboardFormat = 0; const UINT BUFFER_LENGTH = 256; std::vector<TCHAR> buffer( BUFFER_LENGTH, TEXT('\0') ); for ( int i = 0; i < formatsCount && formatId == 0; i++ ) { // For first iteration 0 needs to be passed, for any subsequent call a previous // id should be provided. lastClipboardFormat = EnumClipboardFormats( lastClipboardFormat ); // Check only for custom types, as predefined were already tested. if ( standardFormats.count( lastClipboardFormat ) == 0 ) { GetClipboardFormatName( lastClipboardFormat, &buffer[ 0 ], BUFFER_LENGTH ); // Make sure it's null terminated. buffer[ BUFFER_LENGTH - 1 ] = TEXT('\0'); // Compare... if ( formatName.compare( &(wchar_t)buffer[ 0 ] ) == 0 ) { // Matched! formatId = lastClipboardFormat; } // Zero used buffer. memset( &buffer[ 0 ], TEXT('\0'), sizeof( TCHAR ) * BUFFER_LENGTH ); } } } return formatId; } void ClearClipboard( const FunctionCallbackInfo<Value> &args ) { BOOL ret = true; if ( !OpenClipboard( NULL ) ) { ret = false; } EmptyClipboard(); CloseClipboard(); Isolate *isolate = args.GetIsolate(); args.GetReturnValue().Set(Boolean::New(isolate, ret)); } void ContainsFormat( const FunctionCallbackInfo<Value> &args ) { Isolate *isolate = args.GetIsolate(); Local<v8::Object> ret; if ( !args[0]->IsString ()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Argument 1 must be a string").ToLocalChecked())); return; } v8::String::Utf8Value formatRawName(isolate, args[ 0 ] ); std::wstring formatNameUtf16 = utf8_decode( *formatRawName ); UINT format = GetFormatId(formatNameUtf16); args.GetReturnValue().Set( IsClipboardFormatAvailable(format) ); } void GetData( const FunctionCallbackInfo<Value> &args ) { Isolate *isolate = args.GetIsolate(); Local<v8::Object> ret; if ( args.Length() < 1 ) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Missing argument 1").ToLocalChecked())); return; } if ( !args[0]->IsString() ) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Argument 1 must be a string").ToLocalChecked())); return; } OpenClipboard( NULL ); v8::String::Utf8Value formatRawName(isolate, args[ 0 ] ); std::wstring formatNameUtf16 = utf8_decode( *formatRawName ); UINT formatId = GetFormatId( formatNameUtf16 ); if ( formatId != 0 ) { HGLOBAL clipboardDataHandle = GetClipboardData( formatId ); if ( clipboardDataHandle != NULL ) { LPVOID data = GlobalLock( clipboardDataHandle ); if ( data != NULL ) { SIZE_T clipboardBytes = GlobalSize( clipboardDataHandle ); // It copies data, so no worry about WINAPI cleaning it up on it's own. ret = Nan::CopyBuffer( (const char*)data, clipboardBytes ).ToLocalChecked(); GlobalUnlock( clipboardDataHandle ); } } } CloseClipboard(); if ( formatId != 0 ) { args.GetReturnValue().Set( ret ); } else { // Format not found. args.GetReturnValue().Set( Nan::Null() ); } } void SetData( const FunctionCallbackInfo<Value> &args ) { Isolate *isolate = args.GetIsolate(); const int minArgsCount = 2; if ( args.Length() < minArgsCount ) { char buffer[ 256 ]; memset( buffer, 0, sizeof( char ) * 256 ); sprintf( buffer, "Invalid arguments count. Expected %d but %d given.", minArgsCount, args.Length() ); isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, buffer ).ToLocalChecked())); return; } if ( !args[1]->IsString() ) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Argument 2 must be a string").ToLocalChecked())); return; } if ( !args[0]->IsArrayBuffer() ) { isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Argument 1 must be an ArrayBuffer").ToLocalChecked())); return; } v8::Local<v8::ArrayBuffer> newData = v8::Local<v8::ArrayBuffer>::Cast( args[ 0 ] ); size_t newDataBytes = newData->GetContents().ByteLength(); v8::String::Utf8Value formatRawName(isolate, args[ 1 ] ); std::wstring formatNameUtf16 = utf8_decode( *formatRawName ); OpenClipboard( NULL ); UINT formatId = GetFormatId( formatNameUtf16 ); if ( formatId != 0 ) { // If valid fromat was given, do the magic and store the data. HGLOBAL allocHandle = GlobalAlloc( GMEM_MOVEABLE, newDataBytes ); if ( allocHandle != NULL ) { LPVOID buffer = (LPVOID)GlobalLock( allocHandle ); memcpy( buffer, newData->GetContents().Data(), newDataBytes ); SetClipboardData( formatId, allocHandle ); GlobalUnlock( allocHandle ); } } CloseClipboard(); if ( formatId != 0 ) { args.GetReturnValue().Set( Number::New( isolate, newDataBytes ) ); } else { args.GetReturnValue().Set( Nan::Null() ); } } void init(Local<Object> exports) { initFormats(); NODE_SET_METHOD(exports, "clear", ClearClipboard); NODE_SET_METHOD(exports, "getData", GetData); NODE_SET_METHOD(exports, "setData", SetData); NODE_SET_METHOD(exports, "containsFormat", ContainsFormat); } NODE_MODULE(addon, init)
31.190661
135
0.680639
[ "object", "vector" ]
333f70cdd72f7fe958cabff71707d5885fd114c4
23,447
cpp
C++
src/dsharp/src/src_sharpSAT/MainSolver/InstanceGraph/InstanceGraph.cpp
taboege/raku-SAT-Counter-DSHARP
035898f8db28d570762f641f0dbf9d8cf42e20b7
[ "Artistic-2.0" ]
null
null
null
src/dsharp/src/src_sharpSAT/MainSolver/InstanceGraph/InstanceGraph.cpp
taboege/raku-SAT-Counter-DSHARP
035898f8db28d570762f641f0dbf9d8cf42e20b7
[ "Artistic-2.0" ]
null
null
null
src/dsharp/src/src_sharpSAT/MainSolver/InstanceGraph/InstanceGraph.cpp
taboege/raku-SAT-Counter-DSHARP
035898f8db28d570762f641f0dbf9d8cf42e20b7
[ "Artistic-2.0" ]
null
null
null
#include "InstanceGraph.h" #include <math.h> #include<fstream> #include<stdio.h> #include<error.h> #include<errno.h> CRunAnalyzer theRunAn; // class constructor CInstanceGraph::CInstanceGraph() { } // class destructor CInstanceGraph::~CInstanceGraph() { toDEBUGOUT("lv sz:"<< theLitVector.size() << endl);toDEBUGOUT("nUcls:"<< theUnitClauses.size() << endl); } //////////////////////////////////////////////////////////////////////// // // BEGIN Methods for Clauses // /////////////////////////////////////////////////////////////////////// bool CInstanceGraph::substituteLitsOf(CClauseVertex &rCl, const LiteralIdT &oldLit, const LiteralIdT &newLit) { vector<LiteralIdT>::iterator it; if (oldLit == rCl.idLitA()) rCl.setLitA(newLit); else if (oldLit == rCl.idLitB()) rCl.setLitB(newLit); if (oldLit.oppositeLit() == rCl.idLitA()) rCl.setLitA(newLit.oppositeLit()); else if (oldLit.oppositeLit() == rCl.idLitB()) rCl.setLitB(newLit.oppositeLit()); for (it = begin(rCl); *it != ClauseEnd(); it++) { if (*it == oldLit) { *it = newLit; return true; } else if (*it == oldLit.oppositeLit()) { *it = newLit.oppositeLit(); return true; } } return false; } bool CInstanceGraph::containsVar(const CClauseVertex &rCl, const VarIdT &theVar) const { vector<LiteralIdT>::const_iterator it; for (it = begin(rCl); *it != ClauseEnd(); it++) { if (it->toVarIdx() == theVar) return true; } return false; } bool CInstanceGraph::containsLit(const CClauseVertex &rCl, const LiteralIdT &theLit) const { vector<LiteralIdT>::const_iterator it; for (it = begin(rCl); *it != ClauseEnd(); it++) { if (*it == theLit) return true; } return false; } void CInstanceGraph::printCl(const CClauseVertex &rCl) const { vector<LiteralIdT>::const_iterator it; for (it = begin(rCl); *it != ClauseEnd(); it++) { if (!(it)->polarity()) toSTDOUT("-"); toSTDOUT(it->toVarIdx()+1 << " "); } toSTDOUT(" 0\n"); } bool CInstanceGraph::createConflictClause(const vector<LiteralIdT> &theCClause) { ClauseIdT cclId; vector<LiteralIdT>::const_iterator it; #ifdef DEBUG assert(theCClause.size()> 0); #endif if (theCClause.size() == 1) { createUnitCl(theCClause.front()); if (theUnitClauses.size() == 1 || theUnitClauses.size() % 5 == 0) printCClstats(); getVar(theCClause.front()).scoreVSIDS[theCClause.front().polarity()]++; getVar(theCClause.front()).scoreVSIDS[theCClause.front().oppositeLit().polarity()]++; theRunAn.addClause(); return true; } if (theCClause.size() == 2) { if (!createBinCCl(theCClause[0], theCClause[1])) return false; getVar(theCClause[0]).scoreVSIDS[theCClause[0].polarity()]++; getVar(theCClause[1]).scoreVSIDS[theCClause[1].polarity()]++; getVar(theCClause[0]).scoreVSIDS[theCClause[0].oppositeLit().polarity()]++; getVar(theCClause[1]).scoreVSIDS[theCClause[1].oppositeLit().polarity()]++; if (numBinCCls % 100 == 0) printCClstats(); theRunAn.addClause(); return true; } // create the ClauseVertex cclId = makeConflictClause(); CClauseVertex *pCCl = &getClause(cclId); pCCl->setLitOfs(theLitVector.size()); pCCl->setLength(theCClause.size()); int score = 0; LiteralIdT aLit = NOT_A_LIT; LiteralIdT bLit = NOT_A_LIT; theLitVector.reserve(theLitVector.size() + theCClause.size()); for (it = theCClause.begin(); it != theCClause.end(); it++) { // add literal *it to the litvector theLitVector.push_back(*it); if (getVar(*it).getDLOD() >= score) // determine the most recently set literals to become watched { bLit = aLit; aLit = *it; score = getVar(*it).getDLOD(); } getVar(*it).scoreVSIDS[it->polarity()]++; getVar(*it).scoreVSIDS[it->oppositeLit().polarity()]++; } score = 0; if (bLit == NOT_A_LIT) for (it = theCClause.begin(); it != theCClause.end(); it++) { if (*it != aLit && getVar(*it).getDLOD() >= score) // determine the most recently set literals to become watched { bLit = *it; score = getVar(*it).getDLOD(); } } #ifdef DEBUG assert(aLit != NOT_A_LIT); assert(bLit != NOT_A_LIT); #endif // close the clause with a SENTINEL_LIT theLitVector.push_back(SENTINEL_LIT); // set watch for litA if (aLit != NOT_A_LIT) { pCCl->setLitA(aLit); getVar(aLit).addWatchClause(cclId, aLit.polarity()); } // set watch for litB if (bLit != NOT_A_LIT) { pCCl->setLitB(bLit); getVar(bLit).addWatchClause(cclId, bLit.polarity()); } if (countCCls() % 10000 == 0) printCClstats(); theRunAn.addClause(); return true; } bool CInstanceGraph::setCClImplyingLit(ClauseIdT idCl, const LiteralIdT &theLit) { CClauseVertex &rCV = getClause(idCl); vector<LiteralIdT>::const_iterator it; getVar(rCV.idLitA()).eraseWatchClause(idCl, rCV.idLitA().polarity()); getVar(rCV.idLitB()).eraseWatchClause(idCl, rCV.idLitB().polarity()); int score = -1; LiteralIdT aLit = NOT_A_LIT; #ifdef DEBUG bool ex = false; for (it = begin(rCV); *it != ClauseEnd(); it++) if (*it == theLit) { ex = true; break; } assert(ex); #endif rCV.setLitA(theLit); getVar(rCV.idLitA()).addWatchClause(idCl, rCV.idLitA().polarity()); // set watch for litB aLit = NOT_A_LIT; score = -1; for (it = begin(rCV); *it != ClauseEnd(); it++) if (getVar(*it).getDLOD() > score) { if (*it == theLit) continue; aLit = *it; score = getVar(*it).getDLOD(); } if (aLit != NOT_A_LIT) { rCV.setLitB(aLit); getVar(aLit).addWatchClause(idCl, aLit.polarity()); } return true; } bool CInstanceGraph::cleanUp_deletedCCls() { DepositOfClauses::iterator ct; /////////////////// // clean up LitVector /////////////////// vector<LiteralIdT>::iterator writeLit = theLitVector.begin() + (beginOfCCls())->getLitOfs(); ct = beginOfCCls(); for (vector<LiteralIdT>::iterator xt = writeLit; xt != theLitVector.end(); xt++) if (*xt != NOT_A_LIT) { if (!ct->isDeleted()) { ct->setLitOfs((unsigned int) (writeLit - theLitVector.begin())); while (*xt != NOT_A_LIT) { if (writeLit != xt) *writeLit = *xt; xt++; writeLit++; } *(writeLit++) = NOT_A_LIT; } else { // *ct is deleted, hence, omit all its literals from consideration while (*xt != NOT_A_LIT) xt++;//*(xt++) = NOT_A_LIT; } ct++; } theLitVector.resize((unsigned int) (writeLit - theLitVector.begin())); DepositOfClauses::iterator itWrite = beginOfCCls(); /////////////////// // clean up clauses /////////////////// ClauseIdT oldId, newId; for (ct = beginOfCCls(); ct != endOfCCls(); ct++) if (!ct->isDeleted()) { if (itWrite != ct) { *itWrite = *ct; //BEGIN substitute CCLs oldId = toClauseIdT(ct); newId = toClauseIdT(itWrite); if (getVar(itWrite->idLitB()).isImpliedBy(oldId)) getVar(itWrite->idLitB()).adjustAntecedent(AntecedentT( newId)); if (getVar(itWrite->idLitA()).isImpliedBy(oldId)) getVar(itWrite->idLitA()).adjustAntecedent(AntecedentT( newId)); getVar(itWrite->idLitA()).substituteWatchCl( itWrite->idLitA().polarity(), oldId, newId); getVar(itWrite->idLitB()).substituteWatchCl( itWrite->idLitB().polarity(), oldId, newId); //END substitute CCLs ct->setDeleted(); } itWrite++; } theClauses.erase(itWrite, endOfCCls()); return true; } bool CInstanceGraph::deleteConflictCls() { DepositOfClauses::iterator it; double vgl = 0; for (it = beginOfCCls(); it != endOfCCls(); it++) { vgl = 11000.0; if (it->length() != 0) vgl /= pow((double) it->length(), 3); if (CStepTime::getTime() - it->getLastTouchTime() > vgl) { markCClDeleted(toClauseIdT(it)); } } return true; } bool CInstanceGraph::markCClDeleted(ClauseIdT idCl) { CClauseVertex & rCV = getClause(idCl); if (rCV.isDeleted()) return false; ///// // a clause may not be deleted if it causes an implication: /// if (getVar(rCV.idLitB()).isImpliedBy(idCl) || getVar(rCV.idLitA()).isImpliedBy(idCl)) { return false; } getVar(rCV.idLitB()).eraseWatchClause(idCl, rCV.idLitB().polarity()); getVar(rCV.idLitA()).eraseWatchClause(idCl, rCV.idLitA().polarity()); rCV.setDeleted(); return true; } //////////////////////////////////////////////////////////////////////// // // END Methods for Clauses // /////////////////////////////////////////////////////////////////////// bool CInstanceGraph::prep_substituteClauses(unsigned int oldIdx, unsigned int newIdx) { CClauseVertex &rCl = getClause(newIdx); vector<LiteralIdT>::const_iterator it; vector<ClauseIdT>::iterator jt; ClauseIdT oldId(oldIdx), newId(newIdx); if (getVar(rCl.idLitB()).isImpliedBy(oldId)) getVar(rCl.idLitB()).adjustAntecedent(AntecedentT(newId)); if (getVar(rCl.idLitA()).isImpliedBy(oldId)) getVar(rCl.idLitA()).adjustAntecedent(AntecedentT(newId)); getVar(rCl.idLitA()).substituteWatchCl(rCl.idLitA().polarity(), oldId, newId); getVar(rCl.idLitB()).substituteWatchCl(rCl.idLitB().polarity(), oldId, newId); for (it = begin(rCl); *it != ClauseEnd(); it++) { // substitute ClEdges in theInClsVector for (vector<ClauseIdT>::iterator jt = var_InClsBegin(it->toVarIdx(), false); *jt != SENTINEL_CL; jt++) { if (*jt == oldId) *jt = newId; } // } return true; } bool CInstanceGraph::prep_substituteVars(CVariableVertex &rV, unsigned int newIdx) // only valid if no conflict clauses are present { vector<ClauseIdT>::const_iterator it; vector<LiteralIdT>::iterator kt, vt; vector<LiteralIdT>::iterator jt; unsigned int oldIdx = rV.getVarIdT(); rV.newtecIndex(newIdx); LiteralIdT oldLit, newLit; oldLit = LiteralIdT(oldIdx, true); newLit = LiteralIdT(newIdx, true); varTranslation[newIdx] = oldIdx; varUntranslation[oldIdx] = newIdx; for (it = var_InClsBegin(rV.getVarIdT(), true); *it != SENTINEL_CL; it++) { substituteLitsOf(getClause(*it), oldLit, newLit); } for (kt = rV.getBinLinks(true).begin(); *kt != SENTINEL_LIT; kt++) { getVar(*kt).substituteBinLink(kt->polarity(), oldLit, newLit); } oldLit = LiteralIdT(oldIdx, false); newLit = LiteralIdT(newIdx, false); for (it = var_InClsBegin(rV.getVarIdT(), true) - 1; *it != SENTINEL_CL; it--) { substituteLitsOf(getClause(*it), oldLit, newLit); } for (kt = rV.getBinLinks(false).begin(); *kt != SENTINEL_LIT; kt++) { getVar(*kt).substituteBinLink(kt->polarity(), oldLit, newLit); } return true; } bool CInstanceGraph::eraseLiteralFromCl(ClauseIdT idCl, LiteralIdT theLit) { bool retV = false; CClauseVertex & rCV = getClause(idCl); vector<LiteralIdT>::iterator it; vector<LiteralIdT>::iterator endCl = begin(rCV) + rCV.length(); if (rCV.isDeleted()) return false; if (getVar(rCV.idLitA()).isImpliedBy(idCl) || getVar(rCV.idLitB()).isImpliedBy(idCl)) return false; getVar(rCV.idLitA()).eraseWatchClause(idCl, rCV.idLitA().polarity()); if (rCV.length() >= 2) getVar(rCV.idLitB()).eraseWatchClause(idCl, rCV.idLitB().polarity()); for (it = begin(rCV); *it != ClauseEnd(); it++) { if ((*it) == theLit) { if (it != endCl - 1) *it = *(endCl - 1); *(endCl - 1) = NOT_A_LIT; rCV.setLength(rCV.length() - 1); retV = true; break; } } rCV.setLitA(NOT_A_LIT); rCV.setLitB(NOT_A_LIT); if (rCV.length() >= 1) { rCV.setLitA(*begin(rCV)); getVar(rCV.idLitA()).addWatchClause(idCl, rCV.idLitA().polarity()); } if (rCV.length() >= 2) { rCV.setLitB(*(begin(rCV) + 1)); getVar(rCV.idLitB()).addWatchClause(idCl, rCV.idLitB().polarity()); } return retV; } bool CInstanceGraph::prep_CleanUpPool() { /////////////////// // clean up clauses /////////////////// DepositOfClauses::iterator ct, ctWrite = theClauses.begin() + 1; for (ct = theClauses.begin() + 1; ct != theClauses.end(); ct++) if (!ct->isDeleted()) { if (ctWrite != ct) { *ctWrite = *ct; prep_substituteClauses( (unsigned int) (ct - theClauses.begin()), (unsigned int) (ctWrite - theClauses.begin())); } ctWrite++; } theClauses.erase(ctWrite, theClauses.end()); iOfsBeginConflictClauses = theClauses.size(); /////////////////// // clean up LitVector /////////////////// vector<LiteralIdT>::iterator writeLit = theLitVector.begin(); ct = theClauses.begin() + 1; for (vector<LiteralIdT>::iterator xt = writeLit; xt != theLitVector.end(); xt++) if (*xt != SENTINEL_LIT) // start of the next clause found { ct->setLitOfs((unsigned int) (writeLit - theLitVector.begin())); ct++; while (*xt != SENTINEL_LIT) { if (writeLit != xt) *writeLit = *xt; xt++; writeLit++; } *writeLit = NOT_A_LIT; writeLit++; } theLitVector.resize((unsigned int) (writeLit - theLitVector.begin())); /////////////////// // clean up vars /////////////////// DepositOfVars::iterator it, itWriteVar = theVars.begin() + 1; for (it = theVars.begin() + 1; it != theVars.end(); it++) { if (!it->isolated() || it->isActive()) { if (itWriteVar != it) { *itWriteVar = *it; prep_substituteVars(*itWriteVar, itWriteVar - theVars.begin()); } itWriteVar++; } } theVars.erase(itWriteVar, theVars.end()); it = theVars.begin() + 1; /////////////////// // clean up inCls ////////////////// vector<ClauseIdT>::iterator clt, cltWrite = theInClsVector.begin() + 2; for (clt = theInClsVector.begin() + 2; clt != theInClsVector.end(); clt++) if (*clt != SENTINEL_CL) { while (theInClsVector[it->getInClsVecOfs(false)] == SENTINEL_CL && theInClsVector[it->getInClsVecOfs(true)] == SENTINEL_CL) { it->setInClsVecOfs(false, 0); it->setInClsVecOfs(true, 1); it++; } { it->setInClsVecOfs((unsigned int) (cltWrite - theInClsVector.begin())); while (*clt != SENTINEL_CL) { if (cltWrite != clt) *cltWrite = *clt; clt++; cltWrite++; } *(cltWrite++) = SENTINEL_CL; } it++; } theInClsVector.resize((unsigned int) (cltWrite - theInClsVector.begin())); theUnitClauses.clear(); theUClLookUp.clear(); theUClLookUp.resize(theVars.size(), X); unsigned int countBinCl = 0; // as the number of binary clauses might have changed, // we have to update the numBinClauses, which keeps track of the # of bin Clauses for (it = theVars.begin(); it != theVars.end(); it++) { countBinCl += it->countBinLinks(); } numBinClauses = countBinCl >> 1; toDEBUGOUT("inCls sz:"<<theInClsVector.size()*sizeof(ClauseIdT)<<" "<<endl); return true; } bool CInstanceGraph::createfromFile(const char* lpstrFileName) { const int BUF_SZ = 65536; const int TOK_SZ = 255; char buf[BUF_SZ]; char token[TOK_SZ]; unsigned int line = 0; unsigned int nVars, nCls; int lit; vector<int> litVec; vector<TriValue> seenV; int clauseLen = 0; TriValue pol; vector<int> varPosMap; // BEGIN INIT reset(); // clear everything // END INIT ///BEGIN File input FILE *fp = strcmp(lpstrFileName, "-") == 0 ? stdin : fopen(lpstrFileName, "r") ; if (!fp) { error(3, errno, "CNF input: failed to open file"); } // read the preamble of the cnf file while (fgets(buf, BUF_SZ, fp)) { line++; if (buf[0] == 'c') continue; if (buf[0] == 'p') { if (sscanf(buf, "p cnf %d %d", &nVars, &nCls) < 2) { error(3, errno, "failed reading problem at line %d", line); } break; } else { error(3, errno, "failed reading problem at line %d", line); } } originalVarCount = nVars; int i, j; // now read the data while (fgets(buf, BUF_SZ, fp)) { line++; i = 0; j = 0; if (buf[0] == 'c') continue; while (buf[i] != 0x0) { while (buf[i] != 0x0 && buf[i] != '-' && (buf[i] < '0' || buf[i] > '9')) i++; if (buf[i] == 0x0) continue; while (buf[i] == '-' || buf[i] >= '0' && buf[i] <= '9') { token[j] = buf[i]; i++; j++; } token[j] = 0x0; lit = atoi(token); j = 0; if (lit == 0) // end of clause { if (clauseLen > 0) litVec.push_back(0); clauseLen = 0; } else { clauseLen++; litVec.push_back(lit); } } } if (!feof(fp)) { error(3, errno, "CNF input: read error or line too long"); } fclose(fp); /// END FILE input vector<int>::iterator it, jt, itEndCl; int actVar; bool istaut = true; int imultipleLits = 0; int ilitA, ilitB, lengthCl; LiteralIdT LitA, LitB; ClauseIdT idCl; seenV.resize(nVars + 1, X); varPosMap.resize(nVars + 1, -1); theVars.reserve(nVars + 1); theLitVector.reserve(litVec.size()); theClauses.reserve(nCls + 10000); varTranslation.reserve(nVars + 1); varUntranslation.reserve(nVars + 1); origTranslation.reserve(nVars + 1); theRunAn.init(nVars, nCls); vector<vector<ClauseIdT> > _inClLinks[2]; _inClLinks[0].resize(nVars + 1); _inClLinks[1].resize(nVars + 1); it = litVec.begin(); while (it != litVec.end()) { jt = it; istaut = false; imultipleLits = 0; ilitA = 0; ilitB = 0; // we pick two literals from each clause for watch- or bin-creation lengthCl = 0; while (*jt != 0) // jt passes through the clause to determine if it is valid { actVar = abs(*jt); if (seenV[actVar] == X) // literal not seen { seenV[actVar] = (*jt > 0) ? W : F; if (ilitA == 0) ilitA = *jt; else if (ilitB == 0) ilitB = *jt; jt++; } else if (seenV[actVar] == (*jt > 0) ? W : F) { // literal occurs twice: omit it *jt = 0; imultipleLits++; jt++; } else { // literal in two opposing polarities -> don't include this clause (INVALID) istaut = true; while (*jt != 0) jt++; //cout <<"X"; break; } } itEndCl = jt; lengthCl = (int) (itEndCl - it) - imultipleLits; if (!istaut && lengthCl > 0) // if the clause is not tautological, add it { #ifdef DEBUG if (ilitA == 0) { error(4, 0, "ERR"); exit(3); } #endif actVar = abs(ilitA); if (varPosMap[actVar] == -1) // create new Var if not present yet varPosMap[actVar] = makeVariable(actVar); LitA = LiteralIdT(varPosMap[actVar], (ilitA > 0) ? W : F); if (ilitB != 0)// determine LiteralIdT for ilitB { actVar = abs(ilitB); if (varPosMap[actVar] == -1) // create new Var if not present yet varPosMap[actVar] = makeVariable(actVar); LitB = LiteralIdT(varPosMap[actVar], (ilitB > 0) ? W : F); } if (lengthCl == 1) { theUnitClauses.push_back(LitA); } else if (lengthCl == 2) { #ifdef DEBUG if (ilitB == 0) { error(4, 0, "ERR BIN CL"); exit(3); } #endif if (!getVar(LitA).hasBinLinkTo(LitB, LitA.polarity())) { getVar(LitA).addBinLink(LitA.polarity(), LitB); getVar(LitB).addBinLink(LitB.polarity(), LitA); numBinClauses++; } } else { #ifdef DEBUG if (ilitB == 0) { error(4, 0, "ERR CL"); exit(3); } #endif idCl = makeClause(); getClause(idCl).setLitOfs(theLitVector.size()); theLitVector.push_back(LitA); /// new _inClLinks[LitA.polarity()][LitA.toVarIdx()].push_back(idCl); getVar(LitA).scoreDLIS[LitA.polarity()]++; /// theLitVector.push_back(LitB); /// new _inClLinks[LitB.polarity()][LitB.toVarIdx()].push_back(idCl); getVar(LitB).scoreDLIS[LitB.polarity()]++; /// for (jt = it + 2; jt != itEndCl; jt++) if (*jt != 0 && *jt != ilitB) // add all nonzero literals { actVar = abs(*jt); pol = (*jt > 0) ? W : F; if (varPosMap[actVar] == -1) // create new Var varPosMap[actVar] = makeVariable(actVar); // add lit to litvector theLitVector.push_back(LiteralIdT(varPosMap[actVar], pol)); /// new _inClLinks[pol][varPosMap[actVar]].push_back(idCl); getVar(varPosMap[actVar]).scoreDLIS[pol]++; /// } // make an end: SENTINEL_LIT theLitVector.push_back(SENTINEL_LIT); getClause(idCl).setLitA(LitA); getClause(idCl).setLitB(LitB); getClause(idCl).setLength(lengthCl); getVar(LitA).addWatchClause(idCl, LitA.polarity()); getVar(LitB).addWatchClause(idCl, LitB.polarity()); } } // undo the entries in seenV for (jt = it; jt != itEndCl; jt++) seenV[abs(*jt)] = X; it = itEndCl; it++; } //BEGIN initialize theInClsVector theInClsVector.clear(); theInClsVector.reserve(theLitVector.size() + nVars); theInClsVector.push_back(SENTINEL_CL); vector<ClauseIdT>::iterator clt; for (unsigned int i = 0; i <= nVars; i++) { getVar(i).setInClsVecOfs(false, theInClsVector.size()); for (clt = _inClLinks[0][i].begin(); clt != _inClLinks[0][i].end(); clt++) { theInClsVector.push_back(*clt); } getVar(i).setInClsVecOfs(true, theInClsVector.size()); for (clt = _inClLinks[1][i].begin(); clt != _inClLinks[1][i].end(); clt++) { theInClsVector.push_back(*clt); } theInClsVector.push_back(SENTINEL_CL); } //END initialize theInClsVector #ifdef DEBUG assert(theInClsVector.size() <= theLitVector.size() + nVars + 1); toDEBUGOUT("inCls sz:"<<theInClsVector.size()*sizeof(ClauseIdT)<<" "<<endl); toDEBUGOUT("lsz: "<< theLitVector.size()*sizeof(unsigned int)<< " bytes"<<endl); #endif theUClLookUp.resize(theVars.size() + 1, X); iOfsBeginConflictClauses = theClauses.size(); theRunAn.setUsedVars(countAllVars()); // Store the original translation origTranslation.clear(); origTranslation.resize(varPosMap.size(), -1); for (int i = 0; i < varPosMap.size(); i++) { if (-1 != varPosMap[i]) origTranslation[varPosMap[i]] = i; } //----- This is a good place to set up the var(Un)Translation //--- Clear it out varTranslation.clear(); varUntranslation.clear(); varTranslation.resize(nVars + 1); varUntranslation.resize(nVars + 1); //--- Put in the initial 0 (since variables start at 1) //--- and add the default values for all variables for (unsigned int i = 0; i <= countAllVars(); i++) { varTranslation[(int) i] = (int) i; varUntranslation[(int) i] = (int) i; } return true; } unsigned int CInstanceGraph::countActiveBinLinks(VarIdT theVar) const { unsigned int n = 0; const CVariableVertex &rVar = getVar(theVar); vector<LiteralIdT>::const_iterator bt; for (bt = rVar.getBinLinks(true).begin(); bt != rVar.getBinLinks(true).end(); bt++) { if (*bt != SENTINEL_LIT) n += (unsigned int) getVar(*bt).isActive(); } for (bt = rVar.getBinLinks(false).begin(); bt != rVar.getBinLinks(false).end(); bt++) { if (*bt != SENTINEL_LIT) n += (unsigned int) getVar(*bt).isActive(); } return n; } void CInstanceGraph::convertComponent(CComponentId &oldComp, vector<int> * newComp) { vector<ClauseIdT>::const_iterator it; for (it = oldComp.clsBegin(); *it != clsSENTINEL; it++) { vector<LiteralIdT>::const_iterator lit; for (lit = begin(getClause(*it)); *lit != ClauseEnd(); lit++) { int sign = ((*lit).polarity()) ? 1 : -1; int val = (*lit).toVarIdx(); newComp->push_back(sign * val); } newComp->push_back(0); } } void CInstanceGraph::print() { DepositOfClauses::iterator it; for (it = theClauses.begin() + 1; it != theClauses.end(); it++) { printCl(*it); } } void CInstanceGraph::printClause(const ClauseIdT &idCl) const { vector<LiteralIdT>::const_iterator it; toSTDOUT("("); for (it = begin(getClause(idCl)); *it != ClauseEnd(); it++) { (*it).print(); } toSTDOUT(")"); } void CInstanceGraph::printActiveClause(const ClauseIdT &idCl) const { vector<LiteralIdT>::const_iterator it; toSTDOUT("("); for (it = begin(getClause(idCl)); *it != ClauseEnd(); it++) { if (getVar(*it).isActive()) { (*it).print(); } } toSTDOUT(")"); }
22.741998
105
0.620293
[ "vector" ]
33429a11b10079e58f36f0cff45ba3211047ba15
4,097
hpp
C++
src/include/migraphx/run_loop.hpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
null
null
null
src/include/migraphx/run_loop.hpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
null
null
null
src/include/migraphx/run_loop.hpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
null
null
null
#ifndef MIGRAPHX_GUARD_RTGLIB_RUN_LOOP_HPP #define MIGRAPHX_GUARD_RTGLIB_RUN_LOOP_HPP #include <migraphx/instruction_ref.hpp> #include <migraphx/shape.hpp> #include <migraphx/argument.hpp> #include <migraphx/context.hpp> #include <migraphx/module.hpp> #include <migraphx/config.hpp> #include <migraphx/ranges.hpp> #include <string> namespace migraphx { inline namespace MIGRAPHX_INLINE_NS { template <class LoopModel, class T> argument run_loop(const LoopModel& model, T& ctx, std::vector<argument> args, const std::vector<module_ref>& mods, const std::function<std::vector<argument>( module_ref&, const std::unordered_map<std::string, argument>&)>& run) { std::vector<std::vector<argument>> results; // process argu lists auto iter_num = args.at(0).at<int64_t>(); auto cond = args.at(1).at<bool>(); auto input_num = (args.size() - 2) / 2; auto dep_num = input_num - 2; module_ref mod = mods.at(0); auto param_name_shapes = mod->get_parameter_shapes(); auto param_names = mod->get_parameter_names(); std::vector<argument> dep0(args.begin() + input_num + 1, args.begin() + 2 * input_num); std::vector<argument> dep1(args.begin() + 2 * input_num, args.begin() + 2 * input_num + 1); auto ins_outputs = args.back().get_sub_objects(); dep1.insert(dep1.end(), ins_outputs.begin(), ins_outputs.begin() + dep_num); std::array<std::vector<argument>, 2> loop_carry_deps = {dep0, dep1}; // loop iter argument std::vector<argument> in_args = {args.at(input_num), dep1.at(0)}; in_args.insert(in_args.end(), args.begin() + 2, args.begin() + input_num); std::vector<argument> out_args = dep0; out_args.insert(out_args.end(), ins_outputs.begin() + dep_num, ins_outputs.end()); std::vector<argument> scan_outputs(ins_outputs.begin() + dep_num, ins_outputs.end()); auto out_param_indices = model.get_output_params(*mod); int64_t iter = 0; for(iter = 0; iter < iter_num and cond; ++iter) { // copy iter num and cond to device memory model.copy(ctx, iter, in_args.at(0)); model.copy(ctx, cond, in_args.at(1)); // wrap up the inputs and outputs std::unordered_map<std::string, argument> params; int input_index = 0; for(const auto& name : param_names) { auto ps = mod->get_parameter_shape(name); if(ps == shape{}) { continue; } // it is an input parameter if(not contains(out_param_indices, name)) { params[name] = in_args.at(input_index++); } else { auto output_index = out_param_indices[name]; if(output_index > dep_num) { const auto& arg = out_args.at(output_index); assert((iter + 1) * ps.bytes() <= arg.get_shape().bytes()); params[name] = argument(ps, arg.data() + iter * ps.bytes()); } else { params[name] = out_args.at(output_index); } } } auto mod_args = run(mod, params); // copy back cond to be used next iteration model.copy(ctx, mod_args.at(0), cond); // mod outputs are used as next loop input std::copy(mod_args.begin(), mod_args.begin() + dep_num + 1, in_args.begin() + 1); const auto& dep_out = loop_carry_deps[(iter + 1) % 2]; std::copy(dep_out.begin(), dep_out.end(), out_args.begin()); std::vector<argument> mod_scan_outs(mod_args.begin() + 1 + dep_num, mod_args.end()); model.append(mod_scan_outs, scan_outputs, iter); } out_args.erase(out_args.begin()); std::copy(in_args.begin() + 2, in_args.end(), out_args.begin()); model.set_zero(ctx, scan_outputs, iter); return {out_args}; } } // namespace MIGRAPHX_INLINE_NS } // namespace migraphx #endif
35.318966
95
0.592873
[ "shape", "vector", "model" ]
3343c85d151bbdbf4f34fe62b5c6b1071e4db19f
4,463
hh
C++
src/PBGWraps/SolidMaterial/SolidMaterialTypes.hh
as1m0n/spheral
4d72822f56aca76d70724c543d389d15ff6ca48e
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
1
2020-10-21T01:56:55.000Z
2020-10-21T01:56:55.000Z
src/PBGWraps/SolidMaterial/SolidMaterialTypes.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
src/PBGWraps/SolidMaterial/SolidMaterialTypes.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
#ifndef __PBGWRAPS_SOLIDMATERIALTYPES__ #define __PBGWRAPS_SOLIDMATERIALTYPES__ #include "Geometry/Dimension.hh" #include "SolidMaterial/SolidEquationOfState.hh" #include "SolidMaterial/LinearPolynomialEquationOfState.hh" #include "SolidMaterial/GruneisenEquationOfState.hh" #include "SolidMaterial/OsborneEquationOfState.hh" #include "SolidMaterial/TillotsonEquationOfState.hh" #include "SolidMaterial/MurnahanEquationOfState.hh" #include "SolidMaterial/StrengthModel.hh" #include "SolidMaterial/ConstantStrength.hh" #include "SolidMaterial/NullStrength.hh" #include "SolidMaterial/PolynomialFit.hh" #include "SolidMaterial/SteinbergGuinanStrength.hh" #include "SolidMaterial/SteinbergGuinanLundStrength.hh" #include "SolidMaterial/JohnsonCookStrength.hh" #include "SolidMaterial/CollinsStrength.hh" #include "SolidMaterial/PorousEquationOfState.hh" #include "SolidMaterial/PorousStrengthModel.hh" #include "SolidMaterial/StrainPorosity.hh" #include "SolidMaterial/PhysicsEvolvingMaterialLibrary.hh" namespace Spheral { //------------------------------------------------------------------------------ // Names! //------------------------------------------------------------------------------ typedef SolidEquationOfState<Dim<1> > SolidEquationOfState1d; typedef SolidEquationOfState<Dim<2> > SolidEquationOfState2d; typedef SolidEquationOfState<Dim<3> > SolidEquationOfState3d; typedef PorousEquationOfState<Dim<1> > PorousEquationOfState1d; typedef PorousEquationOfState<Dim<2> > PorousEquationOfState2d; typedef PorousEquationOfState<Dim<3> > PorousEquationOfState3d; typedef StrainPorosity<Dim<1> > StrainPorosity1d; typedef StrainPorosity<Dim<2> > StrainPorosity2d; typedef StrainPorosity<Dim<3> > StrainPorosity3d; typedef LinearPolynomialEquationOfState<Dim<1> > LinearPolynomialEquationOfState1d; typedef LinearPolynomialEquationOfState<Dim<2> > LinearPolynomialEquationOfState2d; typedef LinearPolynomialEquationOfState<Dim<3> > LinearPolynomialEquationOfState3d; typedef GruneisenEquationOfState<Dim<1> > GruneisenEquationOfState1d; typedef GruneisenEquationOfState<Dim<2> > GruneisenEquationOfState2d; typedef GruneisenEquationOfState<Dim<3> > GruneisenEquationOfState3d; typedef OsborneEquationOfState<Dim<1> > OsborneEquationOfState1d; typedef OsborneEquationOfState<Dim<2> > OsborneEquationOfState2d; typedef OsborneEquationOfState<Dim<3> > OsborneEquationOfState3d; typedef TillotsonEquationOfState<Dim<1> > TillotsonEquationOfState1d; typedef TillotsonEquationOfState<Dim<2> > TillotsonEquationOfState2d; typedef TillotsonEquationOfState<Dim<3> > TillotsonEquationOfState3d; typedef MurnahanEquationOfState<Dim<1> > MurnahanEquationOfState1d; typedef MurnahanEquationOfState<Dim<2> > MurnahanEquationOfState2d; typedef MurnahanEquationOfState<Dim<3> > MurnahanEquationOfState3d; typedef StrengthModel<Dim<1> > StrengthModel1d; typedef StrengthModel<Dim<2> > StrengthModel2d; typedef StrengthModel<Dim<3> > StrengthModel3d; typedef NullStrength<Dim<1> > NullStrength1d; typedef NullStrength<Dim<2> > NullStrength2d; typedef NullStrength<Dim<3> > NullStrength3d; typedef ConstantStrength<Dim<1> > ConstantStrength1d; typedef ConstantStrength<Dim<2> > ConstantStrength2d; typedef ConstantStrength<Dim<3> > ConstantStrength3d; typedef SteinbergGuinanStrength<Dim<1> > SteinbergGuinanStrength1d; typedef SteinbergGuinanStrength<Dim<2> > SteinbergGuinanStrength2d; typedef SteinbergGuinanStrength<Dim<3> > SteinbergGuinanStrength3d; typedef SteinbergGuinanLundStrength<Dim<1> > SteinbergGuinanLundStrength1d; typedef SteinbergGuinanLundStrength<Dim<2> > SteinbergGuinanLundStrength2d; typedef SteinbergGuinanLundStrength<Dim<3> > SteinbergGuinanLundStrength3d; typedef JohnsonCookStrength<Dim<1> > JohnsonCookStrength1d; typedef JohnsonCookStrength<Dim<2> > JohnsonCookStrength2d; typedef JohnsonCookStrength<Dim<3> > JohnsonCookStrength3d; typedef CollinsStrength<Dim<1> > CollinsStrength1d; typedef CollinsStrength<Dim<2> > CollinsStrength2d; typedef CollinsStrength<Dim<3> > CollinsStrength3d; typedef PorousStrengthModel<Dim<1> > PorousStrengthModel1d; typedef PorousStrengthModel<Dim<2> > PorousStrengthModel2d; typedef PorousStrengthModel<Dim<3> > PorousStrengthModel3d; typedef PhysicsEvolvingMaterialLibrary<Dim<1> > PhysicsEvolvingMaterialLibrary1d; typedef PhysicsEvolvingMaterialLibrary<Dim<2> > PhysicsEvolvingMaterialLibrary2d; typedef PhysicsEvolvingMaterialLibrary<Dim<3> > PhysicsEvolvingMaterialLibrary3d; } #endif
44.63
83
0.822093
[ "geometry" ]
334491b3891610621fee53d618f7e31190ec7909
3,874
hpp
C++
src/Day12.hpp
LunarWatcher/AoC-2020.cpp
fab93c80e9c7208ddc654f0bdf8085e9b5bfe3cb
[ "MIT" ]
null
null
null
src/Day12.hpp
LunarWatcher/AoC-2020.cpp
fab93c80e9c7208ddc654f0bdf8085e9b5bfe3cb
[ "MIT" ]
null
null
null
src/Day12.hpp
LunarWatcher/AoC-2020.cpp
fab93c80e9c7208ddc654f0bdf8085e9b5bfe3cb
[ "MIT" ]
null
null
null
#pragma once #include "util/Loader.hpp" #include "util/Operators.hpp" #include <iostream> #include <math.h> #include <string> #include <utility> #include <vector> namespace aoc { enum class Day12Dir { NORTH = 1, SOUTH = 3, EAST = 0, WEST = 2, LEFT = 4, RIGHT = 5, FORWARD = 6 }; class Day12 { private: std::vector<std::pair<Day12Dir, int>> directions = loadType<std::pair<Day12Dir, int>>("day12.txt", [](const std::string& line) -> std::pair<Day12Dir, int> { Day12Dir dir; switch (line.at(0)) { case 'F': dir = Day12Dir::FORWARD; break; case 'R': dir = Day12Dir::RIGHT; break; case 'L': dir = Day12Dir::LEFT; break; case 'N': dir = Day12Dir::NORTH; break; case 'S': dir = Day12Dir::SOUTH; break; case 'E': dir = Day12Dir::EAST; break; case 'W': dir = Day12Dir::WEST; break; } return {dir, std::stoi(line.substr(1))}; }); public: void part1() { int x = 0, y = 0; auto direction = static_cast<int>(Day12Dir::EAST); for (auto& [dir, value] : directions) { auto _dir = dir; switch (_dir) { case Day12Dir::LEFT: direction = (direction + (value / 90)) mod 4; break; case Day12Dir::RIGHT: direction = (direction - (value / 90)) mod 4; break; case Day12Dir::FORWARD: _dir = static_cast<Day12Dir>(direction); break; default: break; } switch (_dir) { case Day12Dir::EAST: x += value; break; case Day12Dir::WEST: x -= value; break; case Day12Dir::NORTH: y += value; break; case Day12Dir::SOUTH: y -= value; break; default: break; } } std::cout << "Part 1: " << (std::abs(x) + std::abs(y)) << std::endl; } void part2() { int x = 0, y = 0; // Note: the waypoint coords are always relative to the ship int wX = 10, wY = 1; for (auto& [dir, value] : directions) { switch (dir) { case Day12Dir::LEFT: for (int i = 0; i < value / 90; ++i) { auto cache = wY; wY = wX; wX = -cache; } break; case Day12Dir::RIGHT: for (int i = 0; i < value / 90; ++i) { auto cache = wY; wY = -wX; wX = cache; } break; case Day12Dir::FORWARD: x += value * wX; y += value * wY; std::cout << x << " " << y << std::endl; break; case Day12Dir::EAST: wX += value; break; case Day12Dir::WEST: wX -= value; break; case Day12Dir::NORTH: wY += value; break; case Day12Dir::SOUTH: wY -= value; break; } } std::cout << "Part 2: " << (std::abs(x) + std::abs(y)) << std::endl; } void run() { part1(); part2(); } }; } // namespace aoc
27.671429
117
0.373516
[ "vector" ]
33449d38d224809e665ac23c32eeb01efc1548b6
31,695
cpp
C++
libs/gui/src/WxSubsystem.cpp
skair39/mrpt
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
[ "BSD-3-Clause" ]
2
2019-02-20T02:36:05.000Z
2019-02-20T02:46:51.000Z
libs/gui/src/WxSubsystem.cpp
skair39/mrpt
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
[ "BSD-3-Clause" ]
null
null
null
libs/gui/src/WxSubsystem.cpp
skair39/mrpt
88238f8ac1abdcf15401e14dc3a9faa5c59ba559
[ "BSD-3-Clause" ]
null
null
null
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "gui-precomp.h" // Precompiled headers #include <mrpt/config.h> #include <mrpt/gui/CDisplayWindow.h> #include <mrpt/gui/CDisplayWindow3D.h> #include <mrpt/gui/CDisplayWindowPlots.h> #include <mrpt/system/os.h> #include <mrpt/gui/WxSubsystem.h> #include <mrpt/gui/WxUtils.h> //#define WXSUBSYSTEM_VERBOSE // ------------------------------------------------------------------------ // Defined: Try to wait for all windows & the thread to exit cleanly. // Undefined: Just to a std::this_thread::sleep_for(ms) and quit crossing our // fingers. // // Problem with the "clean way" is: As of feb/2011, I get this error // at the end: // ** (MRPT:11711): CRITICAL **: giop_thread_request_push: assertion `tdata != // NULL' failed // ------------------------------------------------------------------------ //#define WXSHUTDOWN_DO_IT_CLEAN #if MRPT_HAS_WXWIDGETS using namespace mrpt; using namespace mrpt::gui; using namespace std; std::mutex WxSubsystem::CWXMainFrame::cs_windowCount; int WxSubsystem::CWXMainFrame::m_windowCount = 0; std::queue<WxSubsystem::TRequestToWxMainThread*>* WxSubsystem::listPendingWxRequests = nullptr; std::mutex* WxSubsystem::cs_listPendingWxRequests = nullptr; volatile WxSubsystem::CWXMainFrame* WxSubsystem::CWXMainFrame::oneInstance = nullptr; bool isConsoleApp_value = true; bool WxSubsystem::isConsoleApp() { return isConsoleApp_value; } WxSubsystem::CAuxWxSubsystemShutdowner WxSubsystem::global_wxsubsystem_shutdown; // Auxiliary class implementation: WxSubsystem::CAuxWxSubsystemShutdowner::CAuxWxSubsystemShutdowner() = default; WxSubsystem::CAuxWxSubsystemShutdowner::~CAuxWxSubsystemShutdowner() { if (WxSubsystem::isConsoleApp()) { #ifdef WXSUBSYSTEM_VERBOSE printf("[~CAuxWxSubsystemShutdowner] Sending 999...\n"); #endif // Shut down: try { auto* REQ = new WxSubsystem::TRequestToWxMainThread[1]; REQ->OPCODE = 999; WxSubsystem::pushPendingWxRequest(REQ); // std::this_thread::sleep_for(100ms); // JL: I found no better way // of doing this, sorry :-( See // WxSubsystem::waitWxShutdownsIfNoWindows() WxSubsystem::waitWxShutdownsIfNoWindows(); } catch (...) { } // Just in case we got an out-of-mem error. } // is console app. #ifdef WXSUBSYSTEM_VERBOSE printf("[~CAuxWxSubsystemShutdowner] Deleting static objects.\n"); #endif // This is the final point where all dynamic memory must be deleted: // delete &WxSubsystem::GetWxMainThreadInstance(); // may cause crashes at // app end... delete WxSubsystem::listPendingWxRequests; delete WxSubsystem::cs_listPendingWxRequests; } // --------------------------------------------------------------------------------------- // Auxiliary dialog class for the "ask user to open a camera": // --------------------------------------------------------------------------------------- class CDialogAskUserForCamera : public wxDialog { public: mrpt::gui::CPanelCameraSelection* panel; static const long ID_BTN_OK; static const long ID_BTN_CANCEL; CDialogAskUserForCamera() : wxDialog( nullptr, wxID_ANY, wxT("Select image source"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE, wxDialogNameStr) { auto* f1 = new wxFlexGridSizer(2, 1, 0, 0); panel = new mrpt::gui::CPanelCameraSelection(this, wxID_ANY); f1->Add( panel, 1, wxALL | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL, 5); auto* f2 = new wxFlexGridSizer(1, 2, 0, 0); wxButton* btnOk = new wxButton( this, ID_BTN_OK, wxT("Ok"), wxDefaultPosition, wxDefaultSize); wxButton* btnCancel = new wxButton( this, ID_BTN_CANCEL, wxT("Cancel"), wxDefaultPosition, wxDefaultSize); f1->Add(f2, 1, wxALL | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL, 5); f2->Add( btnOk, 1, wxALL | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL, 5); f2->Add( btnCancel, 1, wxALL | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL, 5); Connect( ID_BTN_OK, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&CDialogAskUserForCamera::OnBtnOk); Connect( ID_BTN_CANCEL, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&CDialogAskUserForCamera::OnBtnCancel); SetSizer(f1); Fit(); btnOk->SetFocus(); // So the default params can be accepted by just // pressing ENTER. } ~CDialogAskUserForCamera() override = default; void OnBtnOk(wxCommandEvent& event) { EndModal(wxID_OK); } void OnBtnCancel(wxCommandEvent& event) { EndModal(wxID_CANCEL); } }; const long CDialogAskUserForCamera::ID_BTN_OK = wxNewId(); const long CDialogAskUserForCamera::ID_BTN_CANCEL = wxNewId(); // --------------------------------------------------------------------------------------- // The wx dummy frame: // --------------------------------------------------------------------------------------- BEGIN_EVENT_TABLE(WxSubsystem::CWXMainFrame, wxFrame) END_EVENT_TABLE() const long ID_TIMER_WX_PROCESS_REQUESTS = wxNewId(); WxSubsystem::CWXMainFrame::CWXMainFrame(wxWindow* parent, wxWindowID id) { Create( parent, id, _("MRPT-dummy frame window"), wxDefaultPosition, wxSize(1, 1), 0, // wxDEFAULT_FRAME_STYLE, _T("id")); if (oneInstance) { cerr << "[CWXMainFrame] More than one instance running!" << endl; } oneInstance = this; // ------------------------------------------------------------------------------------------ // Create a timer so requests from the main application thread can be // processed regularly: // ------------------------------------------------------------------------------------------ Connect( ID_TIMER_WX_PROCESS_REQUESTS, wxEVT_TIMER, (wxObjectEventFunction)&CWXMainFrame::OnTimerProcessRequests); m_theTimer = new wxTimer(this, ID_TIMER_WX_PROCESS_REQUESTS); m_theTimer->Start(10, true); // One-shot } WxSubsystem::CWXMainFrame::~CWXMainFrame() { #ifdef WXSUBSYSTEM_VERBOSE cout << "[CWXMainFrame] Destructor." << endl; #endif delete m_theTimer; oneInstance = nullptr; // Purge all pending requests: TRequestToWxMainThread* msg; while (nullptr != (msg = popPendingWxRequest())) delete[] msg; } int WxSubsystem::CWXMainFrame::notifyWindowCreation() { std::lock_guard<std::mutex> lock(cs_windowCount); return ++m_windowCount; } int WxSubsystem::CWXMainFrame::notifyWindowDestruction() { int ret; { std::lock_guard<std::mutex> lock(cs_windowCount); ret = --m_windowCount; } if (ret == 0) { // That was the last window... we should close the wx subsystem: if (oneInstance) { #ifdef WXSHUTDOWN_DO_IT_CLEAN CWXMainFrame* me = (CWXMainFrame*)(oneInstance); // cast away the "volatile". me->Close(); #endif #ifdef WXSUBSYSTEM_VERBOSE cout << "[CWXMainFrame::notifyWindowDestruction] numWindows=0. " "me->Close() called." << endl; #endif } } return ret; } /** Thread-safe method to return the next pending request, or nullptr if there * is none (After usage, FREE the memory!) */ WxSubsystem::TRequestToWxMainThread* WxSubsystem::popPendingWxRequest() { if (!cs_listPendingWxRequests) { cs_listPendingWxRequests = new std::mutex(); listPendingWxRequests = new std::queue<TRequestToWxMainThread*>; } std::lock_guard<std::mutex> locker(*cs_listPendingWxRequests); // Is empty? if (listPendingWxRequests->empty()) return nullptr; TRequestToWxMainThread* ret = listPendingWxRequests->front(); listPendingWxRequests->pop(); // Remove from the queue return ret; } /** Thread-safe method to insert a new pending request (The memory must be * dinamically allocated with "new T[1]", will be freed by receiver.) */ void WxSubsystem::pushPendingWxRequest( WxSubsystem::TRequestToWxMainThread* data) { if (!WxSubsystem::CWXMainFrame::oneInstance) { #ifdef WXSUBSYSTEM_VERBOSE cout << "[WxSubsystem::pushPendingWxRequest] IGNORING request since " "app seems already closed.\n"; #endif delete[] data; return; // wx subsystem already closed, ignore. } if (!cs_listPendingWxRequests) { cs_listPendingWxRequests = new std::mutex(); listPendingWxRequests = new std::queue<TRequestToWxMainThread*>; } std::lock_guard<std::mutex> locker(*cs_listPendingWxRequests); listPendingWxRequests->push(data); } /** This method processes the pending requests from the main MRPT application * thread. * The requests may be to create a new window, close another one, change * title, etc... */ void WxSubsystem::CWXMainFrame::OnTimerProcessRequests(wxTimerEvent& event) { bool app_closed = false; try { TRequestToWxMainThread* msg; #ifdef WXSUBSYSTEM_VERBOSE cout << "[OnTimerProcessRequests] Entering" << endl; #endif // For each pending request: while (nullptr != (msg = popPendingWxRequest())) { // Process it: switch (msg->OPCODE) { // CREATE NEW WINDOW case 200: if (msg->source2D) { auto* wnd = new CWindowDialog( msg->source2D, this, (wxWindowID)-1, msg->str, wxSize(msg->x, msg->y)); // Set the "m_hwnd" member of the window: *((void**)msg->voidPtr) = (void*)wnd; // Signal to the constructor (still waiting) that the // window is now ready so it can continue: msg->source2D->notifySemThreadReady(); wnd->Show(); } break; // UPDATE IMAGE case 201: if (msg->source2D) { auto* wnd = (CWindowDialog*) msg->voidPtr; // msg->source2D->getWxObject(); if (!wnd) break; auto* img = (wxImage*)msg->voidPtr2; if (!img) break; wnd->m_image->AssignImage(new wxBitmap( *img)); // Memory will be freed by the object. if (wnd->m_image->GetSize().GetX() != img->GetWidth() && wnd->m_image->GetSize().GetY() != img->GetHeight()) { wnd->m_image->SetSize( img->GetWidth(), img->GetHeight()); wnd->m_image->SetMinSize( wxSize(img->GetWidth(), img->GetHeight())); wnd->m_image->SetMaxSize( wxSize(img->GetWidth(), img->GetHeight())); wnd->Fit(); // wnd->SetClientSize(img->GetWidth(), // img->GetHeight()); } delete img; wnd->m_image->Refresh(false); // false: Do NOT erase // background: avoid // flickering } break; // Set position case 202: if (msg->source2D) { auto* wnd = (CWindowDialog*)msg->source2D->getWxObject(); if (wnd) wnd->SetSize( msg->x, msg->y, wxDefaultCoord, wxDefaultCoord); } break; // Set size case 203: if (msg->source2D) { auto* wnd = (CWindowDialog*)msg->source2D->getWxObject(); if (wnd) wnd->SetClientSize(msg->x, msg->y); } break; // Set window's title: case 204: if (msg->source2D) { auto* wnd = (CWindowDialog*)msg->source2D->getWxObject(); if (wnd) wnd->SetTitle(msg->str.c_str()); } break; // DESTROY EXISTING WINDOW: case 299: if (msg->source2D) { auto* wnd = (CWindowDialog*)msg->source2D->getWxObject(); if (wnd) { // delete wnd; wnd->Close(); } } break; // CREATE NEW WINDOW case 300: if (msg->source3D) { auto* wnd = new C3DWindowDialog( msg->source3D, this, (wxWindowID)-1, msg->str, wxSize(msg->x, msg->y)); // Set the "m_hwnd" member of the window: *((void**)msg->voidPtr) = (void*)wnd; // Signal to the constructor (still waiting) that the // window is now ready so it can continue: msg->source3D->notifySemThreadReady(); wnd->Show(); } break; // Set position case 302: if (msg->source3D) { auto* wnd = (C3DWindowDialog*)msg->source3D->getWxObject(); if (wnd) wnd->SetSize( msg->x, msg->y, wxDefaultCoord, wxDefaultCoord); } break; // Set size case 303: if (msg->source3D) { auto* wnd = (C3DWindowDialog*)msg->source3D->getWxObject(); if (wnd) wnd->SetClientSize(msg->x, msg->y); } break; // Set window's title: case 304: if (msg->source3D) { auto* wnd = (C3DWindowDialog*)msg->source3D->getWxObject(); if (wnd) wnd->SetTitle(msg->str.c_str()); } break; // FORCE REPAINT case 350: if (msg->source3D) { auto* wnd = (C3DWindowDialog*)msg->source3D->getWxObject(); if (wnd) { wnd->Refresh(false); } } break; // Add a 2D text message: vector_x: [0]:x, [1]:y, [2,3,4]:R G B, // "x": enum of desired font. "y": unique index, "str": String. case 360: if (msg->source3D) { auto* wnd = (C3DWindowDialog*)msg->source3D->getWxObject(); if (wnd) { wnd->addTextMessage( msg->vector_x[0], msg->vector_x[1], msg->str, mrpt::img::TColorf( msg->vector_x[2], msg->vector_x[3], msg->vector_x[4]), size_t(msg->y), mrpt::opengl::TOpenGLFont(msg->x)); } } break; // Clear 2D text messages case 361: if (msg->source3D) { auto* wnd = (C3DWindowDialog*)msg->source3D->getWxObject(); if (wnd) { wnd->clearTextMessages(); } } break; // Add a 2D text message: vector_x: [0]:x, [1]:y, [2,3,4]:R G B, // "x": enum of desired font. "y": unique index, "str": String. case 362: if (msg->source3D) { auto* wnd = (C3DWindowDialog*)msg->source3D->getWxObject(); if (wnd) { wnd->addTextMessage( msg->vector_x[0], msg->vector_x[1], msg->str, mrpt::img::TColorf( msg->vector_x[2], msg->vector_x[3], msg->vector_x[4]), msg->plotName, msg->vector_x[5], mrpt::opengl::TOpenGLFontStyle(msg->x), size_t(msg->y), msg->vector_x[6], msg->vector_x[7], msg->vector_x[8] != 0, mrpt::img::TColorf( msg->vector_x[9], msg->vector_x[10], msg->vector_x[11])); } } break; // DESTROY EXISTING WINDOW: case 399: if (msg->source3D) { auto* wnd = (C3DWindowDialog*)msg->source3D->getWxObject(); if (wnd) { // delete wnd; wnd->Close(); } } break; // CREATE NEW WINDOW case 400: if (msg->sourcePlots) { auto* wnd = new CWindowDialogPlots( msg->sourcePlots, this, (wxWindowID)-1, msg->str, wxSize(msg->x, msg->y)); // Set the "m_hwnd" member of the window: *((void**)msg->voidPtr) = (void*)wnd; // Signal to the constructor (still waiting) that the // window is now ready so it can continue: msg->sourcePlots->notifySemThreadReady(); wnd->Show(); } break; // Set position case 402: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) wnd->SetSize( msg->x, msg->y, wxDefaultCoord, wxDefaultCoord); } break; // Set size case 403: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) wnd->SetClientSize(msg->x, msg->y); } break; // Set window's title: case 404: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) wnd->SetTitle(msg->str.c_str()); } break; // Mouse pan case 410: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) wnd->m_plot->EnableMousePanZoom(msg->boolVal); } break; // Aspect ratio case 411: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) wnd->m_plot->LockAspect(msg->boolVal); } break; // Zoom over a rectangle vectorx[0-1] & vectory[0-1] case 412: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) { if (msg->vector_x.size() == 2 && msg->vector_y.size() == 2) { wnd->m_plot->Fit( msg->vector_x[0], msg->vector_x[1], msg->vector_y[0], msg->vector_y[1]); wnd->m_plot->LockAspect(msg->boolVal); } } } break; // Axis fit, with aspect ratio fix to boolVal. case 413: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) { wnd->m_plot->LockAspect(msg->boolVal); wnd->m_plot->Fit(); } } break; // Clear all objects: case 414: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) { wnd->m_plot->DelAllLayers(true, true); wnd->m_plot->AddLayer(new mpScaleX()); wnd->m_plot->AddLayer(new mpScaleY()); } } break; // Create/modify 2D plot case 420: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) wnd->plot( msg->vector_x, msg->vector_y, msg->str, msg->plotName); } break; // Create/modify 2D ellipse case 421: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) wnd->plotEllipse( msg->vector_x, msg->vector_y, msg->str, msg->plotName, msg->boolVal); } break; // Create/modify bitmap image case 422: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) wnd->image( msg->voidPtr2, msg->vector_x[0], msg->vector_x[1], msg->vector_x[2], msg->vector_x[3], msg->plotName); } break; // 440: Insert submenu in the popup menu. name=menu label, x=ID case 440: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) { const long MENUITEM_ID = wxNewId(); // Remember the association between this ID and the // user ID: wnd->m_ID2ID[MENUITEM_ID] = msg->x; wxMenu* popupMnu = wnd->m_plot->GetPopupMenu(); if (wnd->m_firstSubmenu) { wnd->m_firstSubmenu = false; popupMnu->InsertSeparator(0); } wxMenuItem* mnuTarget = new wxMenuItem( popupMnu, MENUITEM_ID, msg->plotName.c_str(), wxEmptyString, wxITEM_NORMAL); popupMnu->Insert(0, mnuTarget); wnd->Connect( MENUITEM_ID, wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&CWindowDialogPlots:: OnMenuSelected); } } break; // DESTROY EXISTING WINDOW: case 499: if (msg->sourcePlots) { auto* wnd = (CWindowDialogPlots*) msg->sourcePlots->getWxObject(); if (wnd) { // delete wnd; wnd->Close(); } } break; // CREATE NEW WINDOW case 700: if (msg->sourceCameraSelectDialog) { auto* sem = reinterpret_cast<std::promise<void>*>(msg->voidPtr); auto dlg = std::make_unique<CDialogAskUserForCamera>(); // Signal that the window is ready: sem->set_value(); // Show const bool wasOk = (dlg->ShowModal() == wxID_OK); // send selection to caller: auto* promise = reinterpret_cast<std::promise< mrpt::gui::detail::TReturnAskUserOpenCamera>*>( msg->voidPtr2); mrpt::gui::detail::TReturnAskUserOpenCamera ret; // Parse selection as a config text block: mrpt::config::CConfigFileMemory c; dlg->panel->writeConfigFromVideoSourcePanel( "CONFIG", &c); c.getContent(ret.selectedConfig); ret.accepted_by_user = wasOk; promise->set_value(std::move(ret)); dlg->Close(); } break; // wxSubsystem shutdown: case 999: { #ifdef WXSUBSYSTEM_VERBOSE cout << "[WxSubsystem:999] Shutdown" << endl; #endif app_closed = true; // Do NOT launch a timer again if (WxSubsystem::CWXMainFrame::oneInstance) ((WxSubsystem::CWXMainFrame*)(WxSubsystem:: CWXMainFrame:: oneInstance)) ->Close(); #ifdef WXSUBSYSTEM_VERBOSE cout << "[WxSubsystem:999] Shutdown done" << endl; #endif } break; } // end switch OPCODE // Free the memory: delete[] msg; } // end while } catch (...) { } if (!app_closed) m_theTimer->Start(10, true); // One-shot } // --------------------------------------------------------------------------------------- // MRPT Icons // --------------------------------------------------------------------------------------- const char* mrpt_default_icon_xpm[] = {"32 32 2 1", " c None", ". c #000000", " ", " ", " ", " ..... ..... ......... ", " .... .... ... .... ", " ..... .... ... ... ", " . ... . ... ... ... ", " . ... . ... ... ... ", " . ... . ... ... ... ", " . ... . ... ........ ", " . ..... ... ... .... ", " . ... ... ... .... ", " . ... ... ... .... ", " . .. ... ... .... ", " ... . ..... ..... ..... ", " ", " ", " ........ ........... ", " ... .... .. ... .. ", " ... ... . ... . ", " ... ... ... ", " ... ... ... ", " ... ... ... ", " ....... ... ", " ... ... ", " ... ... ", " ... ... ", " ... ... ", " ..... ..... ", " ", " ", " "}; wxBitmap WxSubsystem::getMRPTDefaultIcon() { // To avoid an error in wx, always resize the icon to the expected size: #ifdef _WIN32 const wxSize iconsSize( ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON)); return wxBitmap(wxBitmap(mrpt_default_icon_xpm) .ConvertToImage() .Scale(iconsSize.x, iconsSize.y)); #else return wxBitmap(mrpt_default_icon_xpm); #endif } // --------------------------------------------------------------------------------------- // The wx app: // --------------------------------------------------------------------------------------- class CDisplayWindow_WXAPP : public wxApp { public: bool OnInit() override; int OnExit() override; }; bool CDisplayWindow_WXAPP::OnInit() { // Starting in wxWidgets 2.9.0, we must reset numerics locale to "C", // if we want numbers to use "." in all countries. The App::OnInit() is a // perfect place to undo // the default wxWidgets settings. (JL @ Sep-2009) wxSetlocale(LC_NUMERIC, wxString(wxT("C"))); wxInitAllImageHandlers(); // cout << "[wxApp::OnInit] wxApplication OnInit called." << endl; // Create a dummy frame: auto* Frame = new WxSubsystem::CWXMainFrame(nullptr); Frame->Hide(); // We are ready!! // cout << "[wxMainThread] Signaling semaphore." << endl; WxSubsystem::GetWxMainThreadInstance().m_semWxMainThreadReady.set_value(); return true; } // This will be called when all the windows / frames are closed. int CDisplayWindow_WXAPP::OnExit() { #ifdef WXSUBSYSTEM_VERBOSE cout << "[wxApp::OnExit] wxApplication OnExit called." << endl; #endif std::lock_guard<std::mutex> lock( WxSubsystem::GetWxMainThreadInstance().m_csWxMainThreadId); wxApp::OnExit(); CleanUp(); return 0; } /** This method must be called in the destructor of the user class FROM THE MAIN * THREAD, in order to wait for the shutdown of the wx thread if this was the * last open window. */ void WxSubsystem::waitWxShutdownsIfNoWindows() { #ifndef WXSHUTDOWN_DO_IT_CLEAN #ifdef WXSUBSYSTEM_VERBOSE cout << "[WxSubsystem::waitWxShutdownsIfNoWindows] Doing a quick " "std::this_thread::sleep_for(ms) and returning.\n"; #endif std::this_thread::sleep_for(100ms); return; #else // Just let know a global object that, at its destruction, it must .... // Any open windows? int nOpenWnds; { std::lock_guard<std::mutex> lock(CWXMainFrame::cs_windowCount); nOpenWnds = CWXMainFrame::m_windowCount; } if (!nOpenWnds && WxSubsystem::isConsoleApp()) { #ifdef WXSUBSYSTEM_VERBOSE cout << "[WxSubsystem::waitWxShutdownsIfNoWindows] Waiting for " "WxWidgets thread to shutdown...\n"; #endif // Then we must be shutting down in the wx thread (we are in the main // MRPT application thread)... // Wait until wx is safely shut down: bool done = false; int maxTimeout = #ifdef _DEBUG 30000; #else 5000; #endif if (m_done.wait_for(std::chrono::milliseconds(maxTimeout)) == std::future_status::timeout) { cerr << "[WxSubsystem::waitWxShutdownsIfNoWindows] Timeout waiting " "for WxWidgets thread to shutdown!" << endl; } } #endif } wxAppConsole* mrpt_wxCreateApp() { wxAppConsole::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, "your program"); return new CDisplayWindow_WXAPP; } // DECLARE_APP(CDisplayWindow_WXAPP) extern CDisplayWindow_WXAPP& wxGetApp(); // Aux. funcs used in WxSubsystem::wxMainThread // -------------------------------------------------- int mrpt_wxEntryReal(int argc, char** argv) { // library initialization if (!wxEntryStart(argc, argv)) { #if wxUSE_LOG // flush any log messages explaining why we failed delete wxLog::SetActiveTarget(nullptr); #endif return -1; } // if wxEntryStart succeeded, we must call wxEntryCleanup even if the code // below returns or throws try { // app initialization if (!wxTheApp->CallOnInit()) return -1; // don't call OnExit() if OnInit() failed // app execution int ret = wxTheApp->OnRun(); { wxLogNull logNo; // Skip any warning in this scope. wxTheApp->OnExit(); // This replaces the above callOnExit class wxEntryCleanup(); } return ret; } catch (...) { wxTheApp->OnUnhandledException(); wxEntryCleanup(); return -1; } } /*--------------------------------------------------------------- wxMainThread This will be the "MAIN" of wxWidgets: It starts an application object and does not end until all the windows are closed. Only for console apps, not for user GUI apps already with wx. ---------------------------------------------------------------*/ void WxSubsystem::wxMainThread() { MRPT_START // Prepare wxWidgets: int argc = 1; static const char* dummy_prog_name = "./MRPT"; char* argv[2] = {const_cast<char*>(dummy_prog_name), nullptr}; #ifdef WXSUBSYSTEM_VERBOSE cout << "[wxMainThread] Starting..." << endl; #endif // Are we in a console or wxGUI application???? wxAppConsole* app_gui = wxApp::GetInstance(); if (!app_gui) { // We are NOT in a wx application (it's a console program) // --------------------------------------------------------- #ifdef WXSUBSYSTEM_VERBOSE cout << "[wxMainThread] I am in a console app" << endl; #endif // Start a new wx application object: // JLBC OCT2008: wxWidgets little hack to enable console/gui mixed // applications: wxApp::SetInitializerFunction( (wxAppInitializerFunction)mrpt_wxCreateApp); mrpt_wxEntryReal(argc, argv); #ifdef WXSUBSYSTEM_VERBOSE cout << "[wxMainThread] Finished" << endl; #endif // Now this thread is ready. The main thread is free to end now: WxSubsystem::GetWxMainThreadInstance().m_done.set_value(); } else { // We are ALREADY in a wx application: // --------------------------------------------------------- #ifdef WXSUBSYSTEM_VERBOSE cout << "[wxMainThread] I am in a GUI app" << endl; #endif wxWindow* topWin = static_cast<wxApp*>(app_gui)->GetTopWindow(); auto* Frame = new WxSubsystem::CWXMainFrame(topWin); Frame->Hide(); // We are ready!! #ifdef WXSUBSYSTEM_VERBOSE cout << "[wxMainThread] Signaling semaphore." << endl; #endif WxSubsystem::GetWxMainThreadInstance() .m_semWxMainThreadReady.set_value(); } MRPT_END } WxSubsystem::TWxMainThreadData& WxSubsystem::GetWxMainThreadInstance() { // static TWxMainThreadData dat; // Create as dynamic memory, since it'll be deleted in // CAuxWxSubsystemShutdowner: static TWxMainThreadData* dat = nullptr; static bool first_creat = true; if (!dat && first_creat) { first_creat = false; dat = new TWxMainThreadData; } return *dat; } /*--------------------------------------------------------------- createOneInstanceMainThread ---------------------------------------------------------------*/ bool WxSubsystem::createOneInstanceMainThread() { WxSubsystem::TWxMainThreadData& wxmtd = WxSubsystem::GetWxMainThreadInstance(); std::lock_guard<std::mutex> lock(wxmtd.m_csWxMainThreadId); wxAppConsole* app_con = wxApp::GetInstance(); if (app_con && wxmtd.m_wxMainThreadId.get_id() == std::thread::id()) { // We are NOT in a console application: There is already a wxApp // instance running and it's not us. isConsoleApp_value = false; // cout << "[createOneInstanceMainThread] Mode: User GUI." << endl; if (!WxSubsystem::CWXMainFrame::oneInstance) { // Create our main hidden frame: wxWindow* topWin = static_cast<wxApp*>(app_con)->GetTopWindow(); auto* Frame = new WxSubsystem::CWXMainFrame(topWin); // Frame->Show(); // SetTopWindow(Frame); Frame->Hide(); } } else { // cout << "[createOneInstanceMainThread] Mode: Console." << endl; isConsoleApp_value = true; if (wxmtd.m_wxMainThreadId.get_id() == std::thread::id()) { #ifdef WXSUBSYSTEM_VERBOSE printf( "[WxSubsystem::createOneInstanceMainThread] Launching " "wxMainThread() thread...\n"); #endif // Create a thread for message processing there: wxmtd.m_wxMainThreadId = std::thread(wxMainThread); int maxTimeout = #ifdef _DEBUG 30000; #else 5000; #endif // If we have an "MRPT_WXSUBSYS_TIMEOUT_MS" environment variable, // use that timeout instead: const char* envVal = getenv("MRPT_WXSUBSYS_TIMEOUT_MS"); if (envVal) maxTimeout = atoi(envVal); if (wxmtd.m_semWxMainThreadReady.get_future().wait_for( std::chrono::milliseconds(maxTimeout)) == std::future_status::timeout) // A few secs should be enough... { cerr << "[WxSubsystem::createOneInstanceMainThread] Timeout " "waiting wxApplication to start up!" << endl; return false; } } } return true; // OK } #endif // MRPT_HAS_WXWIDGETS
27.75394
94
0.574917
[ "object" ]
3344d21d783da8cae6a95a9442f490a89aa1be27
13,115
hpp
C++
Core/Application.hpp
Feldrise/SieloNavigateurBeta
faa5fc785271b49d26237a5e9985d6fa22565076
[ "MIT" ]
89
2018-04-26T14:28:13.000Z
2019-07-03T03:58:17.000Z
Core/Application.hpp
inviu/webBrowser
37b24eded2e168e43b3f9c9ccc0487ee59410332
[ "MIT" ]
51
2018-04-26T12:43:00.000Z
2019-04-24T20:39:59.000Z
Core/Application.hpp
inviu/webBrowser
37b24eded2e168e43b3f9c9ccc0487ee59410332
[ "MIT" ]
34
2018-05-11T07:09:36.000Z
2019-04-19T08:12:40.000Z
/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #pragma once #ifndef CORE_APPLICATION_HPP #define CORE_APPLICATION_HPP #include "SharedDefines.hpp" #include <QApplication> #include <QList> #include <QPointer> #include <QFont> #include "3rdparty/SingleApplication/singleapplication.h" #include "3rdparty/Piwik/piwiktracker.h" #include <QWebEngine/WebProfile.hpp> #include <QWebEngine/DownloadItem.hpp> namespace Sn { class AutoFill; class CookieJar; class PluginProxy; class History; class Bookmarks; class MaquetteGrid; class DownloadManager; class HTML5PermissionsManager; class NetworkManager; class SideBarInterface; struct RestoreData; class RestoreManager; class BrowserWindow; class MaquetteGridItem; //! The This class manage Sielo instance, windows and settings. /*! * This application give access to all settings and informations on Sielo. There is usually only **one** instance of this class for the entire browser * * This class will also hande OS signals like new tab request, links open request, etc. * */ class SIELO_SHAREDLIB Application: public SingleApplication { Q_OBJECT public: //! Command line actions /*! All command line option that can be requested to Sielo. This can be request from OS. */ enum CommandLineAction { CL_NoAction, /*!< No action requested */ CL_OpenUrl, /*!< We want to open a URL */ CL_OpenUrlInCurrentTab, /*!< We want to open the url in the current tab */ CL_OpenUrlInNewWindow, /*!< We want to open the url in a new window */ CL_StartWithProfile, /*!< We want to start with a profile */ CL_NewTab, /*!< We want to open a new tab */ CL_NewWindow, /*!< We want to open a new window */ CL_StartPrivateBrowsing, /*!< We want to open a new private browsing window */ CL_StartNewInstance, /*!< We want to start a new instance of Sielo */ CL_ExitAction /*!< We want to close Sielo */ }; //! Object name /*! Name of object accessible for applications. It can be used when one of this object emit a signal for all applications running. */ enum ObjectName { ON_WebView, /*!< Web view object */ ON_TabBar, /*!< Tab bar object */ ON_TabWidget, /*!< Tab space object */ ON_BrowserWindow /*!< Browser window object */ }; //! Window type /*! Describe the type of the window. */ enum WindowType { WT_FirstAppWindow, /*!< The window is the first window of the application */ WT_NewWindow, /*!< The window is a simple new window */ WT_OtherRestoredWindow /*!< The window is a restored window */ }; //! Tabs space type /*! Type of the tabs space */ enum TabsSpaceType { TST_Web, /*!< The tabs space run application */ TST_Application /*!< The tabs space run web pages */ }; //! Tab type /*! Type of the new tab */ enum NewTabType { NTT_SelectedTab = 1, /*!< The tab will be selected */ NTT_NotSelectedTab = 2, /*!< The tab will not be selected */ NTT_CleanTab = 4, /*!< The tab will be clean */ NTT_TabAtEnd = 8, /*!< The tab will be at the end */ NTT_NewEmptyTab = 16, /*!< The tab will be blank */ /* ------------------------- */ NTT_SelectedNewEmptyTab = NTT_SelectedTab | NTT_TabAtEnd | NTT_NewEmptyTab, NTT_SelectedTabAtEnd = NTT_SelectedTab | NTT_TabAtEnd, NTT_NotSelectedTabAtEnd = NTT_NotSelectedTab | NTT_TabAtEnd, NTT_CleanSelectedTabAtEnd = NTT_SelectedTab | NTT_TabAtEnd | NTT_CleanTab, NTT_CleanSelectedTab = NTT_CleanTab | NTT_SelectedTab, NTT_CleanNotSelectedTab = NTT_CleanTab | NTT_NotSelectedTab }; Q_DECLARE_FLAGS(NewTabTypeFlags, NewTabType); //! After launch action /*! Action that should be exectued after Sielo startup */ enum AfterLaunch { OpenBlankPage = 0, /*!< Open a blank page */ OpenHomePage = 1, /*!< Open the home page */ RestoreSession = 2, /*!< Restore the previous session */ OpenSavedSession = 3 /*!< Restore the saved session */ }; /*! * This constructor call functions to load SQL database and load settings. * * It will also determine command line options given and check for updates. */ Application(int& argc, char** argv); /*! * The destructor first request to window to save the current session. * * The it remove any window system resources thar were allocated by this application, and free some managers. */ ~Application(); void loadSettings(); void loadWebSettings(); void loadApplicationSettings(); void loadThemesSettings(); void loadPluginsSettings(); void loadTranslationSettings(); void updateToProfiles(); void translateApplication(); QString currentLanguageFile() const { return m_languageFile; } QString currentLanguage() const; /*! * Apply a theme to Sielo. * @param name Name of the theme we want to apply. * @param lightness Needed to let the theme know if it should load light or dark icons. */ void loadTheme(const QString& name, const QString& lightness = "dark"); QString parseSSS(QString& sss, const QString& relativePath, const QString& lightness); QString parseSSSBackground(QString& sss, const QString& relativePath); QString parseSSSColor(QString& sss, const QString& lightness); QString getBlurredBackgroundPath(const QString& defaultBackground, int radius); QImage blurImage(const QImage& image, const QRect& rect, int radius, bool alphaOnly = false); bool privateBrowsing() const { return m_privateBrowsing; } bool isPortable() const { return m_isPortable; } bool is32bit() const { return m_is32bit; } bool isStartingAfterCrash() const { return m_startingAfterCrash; } bool isClosing() const { return m_isClosing; } int windowCount() const; QList<BrowserWindow*> windows() const { return m_windows; } BrowserWindow *getWindow() const; /*! * Create a new window in this instance. * @param type The type of the new window. * @param startUrl The start url for the new window (if it's empty, it will take the home page url). * @return The new window created. */ BrowserWindow *createWindow(Application::WindowType type, const QUrl& startUrl = QUrl()); /*! * Create a new window from a maquetteGrid in this instance. * @param item The maquetteGrid to load. * @return The new window create. */ BrowserWindow *createWindow(MaquetteGridItem* item); AfterLaunch afterCrashLaunch() const { return m_afterCrashLaunch; } AfterLaunch afterLaunch() const; void openSession(BrowserWindow* window, RestoreData& restoreData); bool restoreSession(BrowserWindow* window, RestoreData restoreData); void destroyRestoreManager(); void addSidebar(const QString& id, SideBarInterface* sideBarInterface); void removeSidebar(SideBarInterface* sideBarInterface); QHash<QString, SideBarInterface*> sidebars() const { return m_sidebars; } PluginProxy *plugins() const { return m_plugins; } AutoFill *autoFill() const { return m_autoFill; } CookieJar *cookieJar(); History *history(); Bookmarks *bookmarks(); MaquetteGrid *maquetteGrid(); DownloadManager *downloadManager(); HTML5PermissionsManager *permissionsManager(); NetworkManager *networkManager() const { return m_networkManager; } RestoreManager *restoreManager() const { return m_restoreManager; } Engine::WebProfile *webProfile(); PiwikTracker *piwikTraker() { return m_piwikTracker; } bool fullyLoadThemes() const { return m_fullyLoadThemes; } bool showFloatingButton() const { return m_showFloatingButton; } bool hideToolbarControls() const { return m_hideToolbarControls; } bool hideBookmarksHistoryActions() const { return m_hideBookmarksHistoryActions; } bool floatingButtonFoloweMouse() const { return m_floatingButtonFoloweMouse; } void startAfterCrash(); QFont morpheusFont() const { return m_morpheusFont; } QFont normalFont() const { return m_normalFont; } bool copyPath(const QString& fromDir, const QString& toDir, bool coverFileIfExist = true); QString readFile(const QString& filename); /*! * Process a command in Sielo. There is serval command available for now : * * - site : open Sielo site. * - github : open the Sielo repository. * - witcher [enable/disable] : enable or disable witcher font in the browser. * - easteregg : open a random crasy site. * @param command The command name. * @param args The command arguments. */ void processCommand(const QString& command, const QStringList args); static QString currentVersion; static Application *instance(); static QIcon getAppIcon(const QString& name, const QString& defaultDire = "other", const QString& format = ".png"); static QString getFileNameFromUrl(const QUrl &url); static QByteArray readAllFileByteContents(const QString& filename); static QString ensureUniqueFilename(const QString& name, const QString& appendFormat = QString("(%1)")); static void removeDirectory(const QString& directory); signals: void activeWindowChanged(BrowserWindow* window); public slots: /*! * Add a new tab to the current tabs space. * @param url The url open in the new tab. By default it's the user new tab url. */ void addNewTab(const QUrl& url = QUrl()); /*! * Start a new private browsing instance. * @param startUrl Url open in the new private browsing window. By default it's the user home page url. */ void startPrivateBrowsing(const QUrl& startUrl = QUrl()); /*! * Save application settings. */ void saveSettings(); /*! * Save current session. * @param saveForHome If true, the saved session will be the user saved session, else, it will be the restore session. */ void saveSession(bool saveForHome = false); void reloadUserStyleSheet(); void quitApplication(); private slots: void postLaunch(); void messageReceived(quint32 instanceId, QByteArray messageBytes); void windowDestroyed(QObject* window); void onFocusChanged(); void downloadRequested(Engine::DownloadItem* download); private: enum PostLaunchAction { OpenNewTab }; void setUserStyleSheet(const QString& filePath); void loadThemeFromResources(QString name = "sielo-default", bool loadAtEnd = true); QString m_languageFile{}; bool m_privateBrowsing{false}; bool m_isPortable{true}; bool m_is32bit{false}; bool m_startingAfterCrash{false}; bool m_isRestoring{false}; bool m_isClosing{false}; bool m_fullyLoadThemes{true}; bool m_showFloatingButton{false}; bool m_hideToolbarControls{false}; bool m_hideBookmarksHistoryActions{false}; bool m_floatingButtonFoloweMouse{true}; bool m_databaseConnected{false}; AfterLaunch m_afterCrashLaunch{AfterLaunch::OpenHomePage}; PluginProxy* m_plugins{nullptr}; AutoFill* m_autoFill{nullptr}; CookieJar* m_cookieJar{nullptr}; History* m_history{nullptr}; Bookmarks* m_bookmarks{nullptr}; MaquetteGrid* m_maquetteGrid{nullptr}; DownloadManager* m_downloadManager{nullptr}; HTML5PermissionsManager* m_permissionsManager{nullptr}; NetworkManager* m_networkManager{nullptr}; Engine::WebProfile* m_webProfile{nullptr}; RestoreManager* m_restoreManager{nullptr}; QList<BrowserWindow*> m_windows; QPointer<BrowserWindow> m_lastActiveWindow; QList<PostLaunchAction> m_postLaunchActions; QHash<QString, SideBarInterface*> m_sidebars; PiwikTracker* m_piwikTracker{nullptr}; QFont m_morpheusFont{}; QFont m_normalFont{}; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Application::NewTabTypeFlags); } #endif // CORE_APPLICATION_HPP
34.695767
150
0.700801
[ "object" ]
33471c9b7231439c6102f93df089126071032434
35,378
cpp
C++
src/Clients/cimcli/CIMCLIOptions.cpp
natronkeltner/openpegasus
e64f383c1ed37826041fc63e83b4e65fc1c679ae
[ "ICU", "Unlicense", "OpenSSL", "MIT" ]
1
2021-11-12T21:28:50.000Z
2021-11-12T21:28:50.000Z
src/Clients/cimcli/CIMCLIOptions.cpp
natronkeltner/openpegasus
e64f383c1ed37826041fc63e83b4e65fc1c679ae
[ "ICU", "Unlicense", "OpenSSL", "MIT" ]
39
2021-01-18T19:28:41.000Z
2022-03-27T20:55:36.000Z
src/Clients/cimcli/CIMCLIOptions.cpp
natronkeltner/openpegasus
e64f383c1ed37826041fc63e83b4e65fc1c679ae
[ "ICU", "Unlicense", "OpenSSL", "MIT" ]
4
2021-07-09T12:52:33.000Z
2021-12-21T15:05:59.000Z
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////////// /******************************************************************************* * * Command line options processing. All option processing is based on the * Pegasus OptionManager and the definition of options contained in this * file. This file also contains the funtions to process input options. * * Once processed, the input options are placed into the options structure * to be passed to the operation processors. * *******************************************************************************/ #include <Pegasus/Common/Config.h> #include <Pegasus/Common/Constants.h> #include <Pegasus/Common/PegasusAssert.h> #include <Pegasus/Common/FileSystem.h> #include <Pegasus/Common/XmlWriter.h> #include <Pegasus/General/MofWriter.h> #include <Pegasus/Common/Tracer.h> #include <Pegasus/Common/StringConversion.h> #include <Pegasus/Common/ArrayInternal.h> #include <Pegasus/Common/PegasusVersion.h> #include <Pegasus/Common/Pegasus_inl.h> #include "CIMCLIOptions.h" #include "CIMCLIClient.h" #include "CIMCLIHelp.h" #include "CIMCLICommon.h" #include "CIMCLIClient.h" PEGASUS_USING_STD; PEGASUS_NAMESPACE_BEGIN /******************************************************************************* ** ** BuildOptionsTable ** *******************************************************************************/ /* This function builds the complete options table from the entries defined below. It then merges in the options from any config file and from any command line parameters. The command line parameters will override any config file parameters. */ void BuildOptionsTable( OptionManager& om, int& argc, char** argv, const String& testHome) { // Table of available options to be used by cimcli. Each of the possible // options is defined in one entry in the table below. static OptionRowWithMsg optionsTable[] = //optionname defaultvalue rqd type domain domainsize clname msgkey // hlpmsg { // FUTURE TODO. This strange number was a way to tell option parser // that the option was not found on the command line. That concept // does not exist today in the OptionManager. The error mechanism // tells you whether the option name is defined not whether there was // an option supplied. Need to fix OptionManager {"count", "29346", false, Option::WHOLE_NUMBER, 0, 0, "count", "Clients.cimcli.CIMCLIClient.COUNT_OPTION_HELP", "Expected count of objects returned if summary set.\n" " Tests this count and displays difference.\n" " Return nonzero status code if test fails"}, {"debug", "false", false, Option::BOOLEAN, 0, 0, "d", "Clients.cimcli.CIMCLIClient.DEBUG_OPTION_HELP", "More detailed debug messages"}, {"delay", "0", false, Option::WHOLE_NUMBER, 0, 0, "delay", "Clients.cimcli.CIMCLIClient.DELAY_OPTION_HELP", "Delay between connection and request"}, {"Password", "", false, Option::STRING, 0, 0, "p", "Clients.cimcli.CIMCLIClient.PASSWORD_OPTION_HELP", "Defines password for authentication" }, {"location", "", false, Option::STRING, 0, 0, "l", "Clients.cimcli.CIMCLIClient.LOCATION_OPTION_HELP", "Specifies system and port (HostName:port).\n" " Port is optional" }, #ifdef PEGASUS_HAS_SSL {"ssl", "false", false, Option::BOOLEAN, 0, 0, "s", "Clients.cimcli.CIMCLIClient.SSL_OPTION_HELP", "Specifies to connect over HTTPS" }, {"clientCert", "", false, Option::STRING, 0, 0, "-cert", "Clients.cimcli.CIMCLIClient.CLIENTCERT_OPTION_HELP", "Specifies a client certificate file path to present to the server.\n" " This is optional and only has an effect on connections\n" " made over HTTPS using -s. If this option specified the\n" " clientKey must also exist" }, {"clientKey", "", false, Option::STRING, 0, 0, "-key", "Clients.cimcli.CIMCLIClient.CLIENTKEY_OPTION_HELP", "Specifies a client private key file path.\n" " This is optional and only has an effect on connections\n" " made over HTTPS using -s. If this option specified the\n" " clientCert must also exist" }, {"clientTruststore", "", false, Option::STRING, 0, 0, "-truststore", "Clients.cimcli.CIMCLIClient.CLIENTKEY_OPTION_HELP", "Specifies a path to a client trust store cused to verify server\n" " certificates. This is optional and only has an effect" " on connections made over HTTPS using -s\n"}, #endif {"User", "", false, Option::STRING, 0, 0, "u", "Clients.cimcli.CIMCLIClient.USER_OPTION_HELP", "Defines User Name for authentication" }, {"namespace", "root/cimv2", false, Option::STRING, 0, 0, "n", "Clients.cimcli.CIMCLIClient.NAMESPACE_OPTION_HELP", "Specifies namespace to use for operation" }, {"includeClassOrigin", "false", false, Option::BOOLEAN, 0, 0, "ic", "Clients.cimcli.CIMCLIClient.INCLUDECLASSORIGIN_OPTION_HELP", "If set includeClassOrigin parameter\n" " set true on requests that honor this parameter"}, {"deepInheritance", "false", false, Option::BOOLEAN, 0, 0, "di", "Clients.cimcli.CIMCLIClient.DEEPINHERITANCE_OPTION_HELP", "If set deepInheritance parameter\n" " set true"}, // FUTURE - Drop this option completely {"localOnly", "true", false, Option::BOOLEAN, 0, 0, "lo", "Clients.cimcli.CIMCLIClient.LOCALONLY_OPTION_HELP", "DEPRECATED. This was used to set LocalOnly.\n" " However, default should be true and we cannot use True\n" " as default. See -nlo"}, {"notLocalOnly", "false", false, Option::BOOLEAN, 0, 0, "nlo", "Clients.cimcli.CIMCLIClient.NOTLOCALONLY_OPTION_HELP", "When set, sets LocalOnly = false on\n" " operations"}, {"includeQualifiers", "false", false, Option::BOOLEAN, 0, 0, "iq", "Clients.cimcli.CIMCLIClient.INCLUDEQUALIFIERS_OPTION_HELP", "DEPRECATED. Sets includeQualifiers = True.\n" " Useful for instance operations where default is false"}, {"notIncludeQualifiers", "false", false, Option::BOOLEAN, 0, 0, "niq", "Clients.cimcli.CIMCLIClient.NOTINCLUDEQUALIFIERS_OPTION_HELP", "Sets includeQualifiers = false\n" " on operations. Useful for class operations where \n" " the default is true."}, // Uses a magic string as shown below to indicate never used. {"propertyList", "###!###", false, Option::STRING, 0, 0, "pl", "Clients.cimcli.CIMCLIClient.PROPERTYLIST_OPTION_HELP", "Defines a propertyNameList. Format is p1,p2,p3\n" " (without spaces). Use \"\" for empty"}, {"assocClass", "", false, Option::STRING, 0, 0, "ac", "Clients.cimcli.CIMCLIClient.ASSOCCLASS_OPTION_HELP", "Defines a assocation Class string for Associator calls"}, {"assocRole", "", false, Option::STRING, 0, 0, "ar", "Clients.cimcli.CIMCLIClient.ASSOCROLE_OPTION_HELP", "Defines a role string for Associators. AssocRole\n" " parameter"}, {"role", "", false, Option::STRING, 0, 0, "r", "Clients.cimcli.CIMCLIClient.ROLE_OPTION_HELP", "Defines a role string for reference role parameter"}, {"resultClass", "", false, Option::STRING, 0, 0, "rc", "Clients.cimcli.CIMCLIClient.RESULTCLASS_OPTION_HELP", "Defines a resultClass string for References and\n" " Associatiors"}, {"resultRole", "", false, Option::STRING, 0, 0, "rr", "Clients.cimcli.CIMCLIClient.RESULTROLE_OPTION_HELP", "Defines a role string for associators operation resultRole\n" " parameter"}, // This options has been deprecated and its functionality removed // Keeping it simply as means to explain the issue to users in case // they try to use it. {"inputParameters", "", false, Option::STRING, 0, 0, "ip", "Clients.cimcli.CIMCLIClient.INPUTPARAMETERS_OPTION_HELP", "This option deprecated and removed. Replaced by use of\n" " the same name/value pair syntax as properties in create\n" " and modify instance."}, {"filter", "", false, Option::STRING, 0, 0, "f", "Clients.cimcli.CIMCLIClient.FILTER_OPTION_HELP", "Defines a filter to use for query. Single String input"}, {"queryLanguage", "WQL", false, Option::STRING, 0, 0, "ql", "Clients.cimcli.CIMCLIClient.QUERYLANGUAGE_OPTION_HELP", "Defines a Query Language to be used with a query filter.\n"}, // Defines the multiple output formats. List of possible options // defined in CIMCLIOptionStruct files. default mof. // FUTURE - Add simple option that uses the enum features of // options manager. However. we cannot remove this option. {"outputformats", "mof", false, Option::STRING, 0,0, "o", "Clients.cimcli.CIMCLIClient.OUTPUTFORMATS_OPTION_HELP", "Output in xml, mof, txt, table"}, {"xmlOutput", "false", false, Option::BOOLEAN, 0,0, "x", "Clients.cimcli.CIMCLIClient.XMLOUTPUT_OPTION_HELP", "Output objects in xml format"}, {"version", "false", false, Option::BOOLEAN, 0, 0, "-version", "Clients.cimcli.CIMCLIClient.VERSION_OPTION_HELP", "Displays software Version"}, {"verbose", "false", false, Option::BOOLEAN, 0, 0, "v", "Clients.cimcli.CIMCLIClient.VERBOSE_OPTION_HELP", "Verbose Display. Outputs detailed parameter input\n" " display and other request processing information"}, {"summary", "false", false, Option::BOOLEAN, 0, 0, "-sum", "Clients.cimcli.CIMCLIClient.SUMMARY_OPTION_HELP", "Displays only summary count for enumerations,\n" " associators, etc."}, {"help", "false", false, Option::BOOLEAN, 0, 0, "h", "Clients.cimcli.CIMCLIClient.HELP_OPTION_HELP", "Prints help usage message"}, {"full help", "false", false, Option::BOOLEAN, 0, 0, "-help", "Clients.cimcli.CIMCLIClient.FULLHELP_OPTION_HELP", "Prints full help message with commands, options,\n" " examples"}, {"help options", "false", false, Option::BOOLEAN, 0, 0, "ho", "Clients.cimcli.CIMCLIClient.HELPOPTIONS_OPTION_HELP", "Prints list of options"}, {"help commands", "false", false, Option::BOOLEAN, 0, 0, "hc", "Clients.cimcli.CIMCLIClient.HELPCOMMANDS_OPTION_HELP", "Prints CIM Operation command list"}, {"connecttimeout", "0", false, Option::WHOLE_NUMBER, 0, 0, "-timeout", "Clients.cimcli.CIMCLIClient.CONNECTIONTIMEOUT_OPTION_HELP", "Set the connection timeout in seconds."}, {"interactive", "false", false, Option::BOOLEAN, 0, 0, "i", "Clients.cimcli.CIMCLIClient.INTERACTIVE_OPTION_HELP", "Interactively ask user to select instances.\n" " Used with associator and reference operations"}, {"setRtnHostNames", "", false, Option::STRING, 0, 0, "-setRtnHostNames", "Clients.cimcli.CIMCLIClient.SETRTNHOSTNAMES_OPTION_HELP", "Set namespace component of reference and path outputs parameter.\n" " Used to allow comparison of paths and instances without" " involving the variable of host namespaces."}, {"trace", "0", false, Option::WHOLE_NUMBER, 0, 0, "trace", "Clients.cimcli.CIMCLIClient.TRACE_OPTION_HELP", "Set Pegasus Common Components Trace. Sets the Trace level.\n" " 0 is off"}, {"repeat", "0", false, Option::WHOLE_NUMBER, 0, 0, "-r", "Clients.cimcli.CIMCLIClient.REPEAT_OPTION_HELP", "Number of times to repeat the operation.\n" " Zero means one time"}, {"time", "false", false, Option::BOOLEAN, 0, 0, "-t", "Clients.cimcli.CIMCLIClient.TIME_OPTION_HELP", "Measure time for the operation and present results"}, //EXP_PULL_BEGIN {"pullTimeout", "10", false, Option::WHOLE_NUMBER, 0, 0, "pt", "Clients.cimcli.CIMCLIClient.PULLTIMEOUT", "Pull interoperation timeout in seconds. "}, {"maxObjectCount", "100", false, Option::WHOLE_NUMBER, 0, 0, "mo", "Clients.cimcli.CIMCLIClient.MAXOBJCNT", "Maximum number of objects in a single Pull "}, {"maxObjectsToReceive", "0", false, Option::WHOLE_NUMBER, 0, 0, "mr", "Clients.cimcli.CIMCLIClient.MAXOBJRCV", "Maximum objects to Receive in a pull sequence. " "Will Close when this number received."}, {"pullDelay", "0", false, Option::WHOLE_NUMBER, 0, 0, "pullDelay", "Clients.cimcli.CIMCLIClient.PULLDELAY", "Delay in Seconds between pull Operations. " "Default zero, no delay."}, // EXP_PULL_END {"sort", "false", false, Option::BOOLEAN, 0, 0, "-sort", "Clients.cimcli.CIMCLIClient.SORT_OPTION_HELP", "Sort the returned entities for multi-object responses " "(ex. enumerations, associators, etc.)"}, {"expectedExitCode", "0", false, Option::WHOLE_NUMBER, 0, 0, "-expExit", "Clients.cimcli.CIMCLIClient.EXPEXIT_OPTION_HELP", "Set the exit code that cimcli expects for this operation. cimcli" " exits code = 0 if expectedExitCode matches pgm exit code."} }; const Uint32 NUM_OPTIONS = sizeof(optionsTable) / sizeof(optionsTable[0]); // Register all of the options in the table above om.registerOptions(optionsTable, NUM_OPTIONS); // Merge any options from the config file if it exists String configFile = "cimcli.conf"; if (FileSystem::exists(configFile)) { om.mergeFile(configFile); } // Merge options from the command line om.mergeCommandLine(argc, argv); om.checkRequiredOptions(); } /* Execute lookup on option. This used because the OptionTable functions generally return error when the option is not found. In cimcli this is really a developer error (i.e option not in the table) so we isolate it from the general lookup functionality. This function exits if the lookup fails, that means that there is a discrepency between the table of options and the names in the lookup functions. Fix the table. The error exit in this function should NEVER happen in a released version of cimcli. */ static const Option* _lookupOption(OptionManager& om, const char* optionName) { const Option* op = om.lookupOption(optionName); // if option does not exist in table, terminate. All options must exist // in the table. This is a programming error between the input // parsing code and the table defining options. if (op == 0) { cerr << "Parse Error in " << optionName << " Name not valid cimcli option. Fix options table" << endl; cimcliExit(CIMCLI_INPUT_ERR); } return op; } // Get the value of the option if it was resolved. Note that // resolved means that it was input on either the command line or // a configuration file. // @param opts - reference to the options structure // @param om -reference to the OptionManger where the data is saved. // @param optionName - Name of the option for which we want the value // @param resolvedStateVariable Boolean that is set true if the option has // been resolved (i.e. provided by either the config file or command line) // @param optsTarget String containing the value of the parameter if it // was resolved. // @return Boolean indicating whether the parameter was found in the table Boolean lookupStringResolvedOption(Options& opts, OptionManager& om, const char* optionName, Boolean& resolvedStateVariable, String& optsTarget) { // test for existing option const Option* op = _lookupOption(om, optionName); if (op->isResolved()) { resolvedStateVariable = true; optsTarget = op->getValue(); if (opts.verboseTest && opts.debug) { cout << optionName << " = " << optsTarget << endl; } } else { resolvedStateVariable = false; } return resolvedStateVariable; } /* Lookup string option and insert into target property Uses the table defined default directly if nothing input from either command line or config file. */ void lookupStringOption(Options& opts, OptionManager& om, const char* optionName, String& optsTarget) { // Test for existing option. If nothing found, this // function exits cimcli with error status _lookupOption(om, optionName); if (om.lookupValue(optionName, optsTarget)) { if (opts.verboseTest && opts.debug) cout << optionName << " = " << optsTarget << endl; } } // Looks up a String option by name. If the returned value is empty // insures that it is value by setting to String::EMPTY void lookupStringOptionEMPTY(Options& opts, OptionManager& om, const char* optionName, String& optsTarget) { // Test for Existing Option _lookupOption(om, optionName); String temp; if (om.lookupValue(optionName, temp)) { optsTarget = (temp.size() == 0)? String::EMPTY : temp; if (opts.verboseTest && opts.debug) { cout << optionName << " = " << optsTarget << endl; } } } Boolean lookupCIMNameOption(Options& opts, OptionManager& om, const char* optionName, CIMName& optsTarget, const CIMName& defaultValue) { // Test for existing option _lookupOption(om, optionName); String temp; if (om.lookupValue(optionName, temp)) { if (temp != "") { //Assigning to CIMName can cause exception. try { optsTarget = temp; } catch(Exception& e) { cerr << "Parse Error in " << optionName << " Class. Exception " << e.getMessage() << endl; return false; } } else optsTarget = defaultValue; if (opts.verboseTest && opts.debug && temp != "") { cout << optionName << " = " << optsTarget.getString() << endl; } } return true; } // Lookup a single Uint32 option. NOTE: The issue here is with detecting // whether the option exists or we should use the internal default. // Return from the option manager is the defined default which is itself // an integer. void lookupUint32Option(Options& opts, OptionManager& om, const char* optionName, Uint32& optsTarget, Uint32 defaultValue, const char* units = "") { // Test for existing option _lookupOption(om, optionName); optsTarget = 0; if (!om.lookupIntegerValue(optionName, optsTarget)) { optsTarget = 0; } if (opts.verboseTest && opts.debug && optsTarget != 0) { cout << optionName << " = " << optsTarget << units << endl; } } //EXP_PULL_BEGIN // Lookup a single Uint32 option. NOTE: The issue here is with detecting // whether the option exists or we should use the internal default. // Return from the option manager is the defined default which is itself // an integer. void lookupUint32ArgOption(Options& opts, OptionManager& om, const char* optionName, Uint32Arg& optsTarget, Uint32 defaultValue, const char* units = "") { // KS_TBD - Expand this to allow the NULL options which is part of // Uint32Arg optsTarget.setNullValue(); Uint32 temp; if (!om.lookupIntegerValue(optionName, temp)) { optsTarget.setValue(0); } // KS_TBD - This is temporary until we expand option manager to support // the numeric arg concept. optsTarget.setValue(temp); if (opts.verboseTest && opts.debug && (optsTarget.getValue() != 0 || !optsTarget.isNull() ) ) { cout << optionName << " = " << optsTarget.toString() << " " << units << endl; } } //EXP_PULL_END // Lookup value only if the option was resolved. Ignores default values. Boolean lookupUint32ResolvedOption(Options& opts, OptionManager& om, const char* optionName, Boolean& resolvedStateVariable, Uint32& optsTarget, Uint32 defaultValue, const char* units = "") { // Test for existing Option const Option* op = _lookupOption(om, optionName); optsTarget = 0; if (op->isResolved()) { resolvedStateVariable = true; const String value = op->getValue(); Uint64 u64 = strToUint(value.getCString(), CIMTYPE_UINT32); optsTarget = (Uint32)u64; } else { resolvedStateVariable = false; } return resolvedStateVariable; } void lookupBooleanOption(Options& opts, OptionManager& om, const char* optionName, Boolean& optsTarget) { // Test for existing option _lookupOption(om, optionName); optsTarget = om.isTrue(optionName); if (optsTarget && opts.verboseTest && opts.debug) { cout << optionName << " = " << boolToString(optsTarget) << endl; } } void lookupBooleanOptionNegate(Options& opts, OptionManager& om, const char* optionName, Boolean& optsTarget) { // Test for existing option _lookupOption(om, optionName); optsTarget = !om.isTrue(optionName); if (optsTarget && opts.verboseTest && opts.debug) { cout << optionName << " = " << boolToString(optsTarget) << endl; } } Boolean CheckCommonOptionValues(OptionManager& om, char** argv, Options& opts) { Uint32 lineLength = 79; // Catch the verbose and debug options first so they can control other // processing Boolean verboseTest = (om.valueEquals("verbose", "true")) ? true :false; Boolean debug = (om.valueEquals("debug", "true")) ? true :false; if (verboseTest) { opts.verboseTest = verboseTest; } if (debug) { opts.debug= debug; } if (om.isTrue("full help")) { showFullHelpMsg(argv[0], om, lineLength); return false; // signal cimcli should terminate after display } // show usage for a single operation and exit if (om.isTrue("help")) { if (!showOperationUsage(argv[1], om, lineLength)) { opts.termCondition = CIMCLI_INPUT_ERR; return false; } return false; } // show version number if (om.isTrue("version")) { showVersion(argv[0], om); return false; } // show all help options if (om.isTrue("help options")) { showOptions(argv[0], om); return false; } // show help Operation list if (om.isTrue("help commands")) { showOperations(argv[0], lineLength); return false; } lookupStringOption(opts, om, "namespace", opts.nameSpace); lookupStringOptionEMPTY(opts, om, "role", opts.role); lookupStringOptionEMPTY(opts, om, "resultRole", opts.resultRole); lookupStringOption(opts, om, "location", opts.location); #ifdef PEGASUS_HAS_SSL // Determine whether to connect over HTTPS opts.ssl = om.isTrue("ssl"); // Get value for client certificate om.lookupValue("clientCert", opts.clientCert); // Get value for client key om.lookupValue("clientKey", opts.clientKey); // Get value for client key om.lookupValue("clientTruststore", opts.clientTruststore); if (verboseTest && debug && opts.ssl) { cout << "ssl = true" << endl; if (opts.clientCert != "" && opts.clientKey != "") { cout << "clientCert = " << opts.clientCert << endl; cout << "clientKey = " << opts.clientKey << endl; if (opts.clientTruststore.size() != 0) { cout << "clientTruststore path = " << opts.clientTruststore << endl; } } } #endif // Assign the result class if (!lookupCIMNameOption(opts, om, "resultClass", opts.resultClass, CIMName())) { opts.termCondition = CIMCLI_INPUT_ERR; return false; } if (!lookupCIMNameOption(opts, om, "assocClass", opts.assocClass, CIMName())) { opts.termCondition = CIMCLI_INPUT_ERR; return false; } // Evaluate connectiontimeout option. lookupUint32Option(opts, om, "connecttimeout", opts.connectionTimeout, 0, "seconds"); lookupUint32Option(opts, om, "delay", opts.delay, 0, "seconds"); //EXP_PULL_BEGIN // Options to support parameters on pull operations lookupUint32ArgOption(opts, om, "pullTimeout", opts.pullOperationTimeout, 0, "seconds"); lookupUint32Option(opts, om, "maxObjectCount", opts.maxObjectCount, 0, "max rtn"); lookupUint32Option(opts, om, "pullDelay", opts.pullDelay, 0, "seconds"); lookupUint32Option(opts, om, "maxObjectsToReceive", opts.maxObjectsToReceive, 0, "seconds"); //EXP_PULL_END // Set the interactive request flag based on input lookupBooleanOption(opts, om,"interactive", opts.interactive); // Set the sort request flag based on input lookupBooleanOption(opts, om,"sort", opts.sort); // set the deepInheritance flag based on input lookupBooleanOption(opts, om,"deepInheritance", opts.deepInheritance); // only use this one if there was an input from the command line // or config file. sets the Boolean setRtnHostNames based on whether // there was an option input (i.e. resolved). lookupStringResolvedOption(opts, om, "setRtnHostNames", opts.setRtnHostNames, opts.rtnHostSubstituteName); lookupStringOption(opts, om, "filter", opts.query); lookupStringOption(opts, om, "queryLanguage", opts.queryLanguage); // Test for existence of input parameter option. If found, put out // warning and exit with syntax error message. This parameter was // deprecated and removed in favor of direct input of name/value pairs // as separate input entities in CIM Version 2.10 Boolean inputParametersResolved = false; String inputParameters; lookupStringResolvedOption(opts, om, "inputParameters", inputParametersResolved, inputParameters); if (inputParametersResolved) { cerr << "The -ip option has been deprecated and removed.\n" " parameters can be directly input as name/value pairs\n" " in the same manner properties are input to the\n" " createInstance and other operations\n" << endl; opts.termCondition = CIMCLI_INPUT_ERR; return false; } // process localOnly and notlocalOnly parameters opts.localOnly = om.isTrue("localOnly"); if (om.isTrue("notLocalOnly")) { opts.localOnly = false; } // Used the not version because the DMTF and pegasus default is true if (verboseTest && debug && om.isTrue("notLocalOnly")) { cout << "localOnly= " << boolToString(opts.localOnly) << endl;; } // Process includeQualifiers and notIncludeQualifiers // These are particular in that there are two parameters each // of which may be useful. Also, the CIM/XML default is different // for class operations and instance operations. In class operations // the default is true while, in instance operations, the default // is false and further, the whole use of the parameter is deprecated for // instance operations. // For each of these parameters we want to specifically confirm if // the command line input parameter is supplied. Thus, for class operations // the user would use the niq to tell the environment to not include // qualifiers whereas for instance operations the user would use iq // to specifically request qualifiers with instances. lookupBooleanOption(opts, om, "includeQualifiers", opts.includeQualifiersRequested); lookupBooleanOption(opts, om, "notIncludeQualifiers", opts.notIncludeQualifiersRequested); lookupBooleanOption(opts, om,"includeClassOrigin", opts.includeClassOrigin ); lookupBooleanOption(opts, om,"time", opts.time); if (!om.lookupIntegerValue("trace", opts.trace)) { opts.trace = 0; } else { Uint32 traceLevel = 0; switch (opts.trace) { case 0: // This covers the default. break; case 1 : traceLevel = Tracer::LEVEL1; break; case 2 : traceLevel = Tracer::LEVEL2; break; case 3 : traceLevel = Tracer::LEVEL3; break; case 4 : traceLevel = Tracer::LEVEL4; break; default: cerr << "Illegal value for Trace. Max = 4" << endl; } opts.trace = traceLevel; } if (verboseTest && debug && opts.trace != 0) { cout << "Pegasus Trace set to Level " << opts.trace << endl; } lookupBooleanOption(opts, om,"summary", opts.summary); // get User name and password if set. lookupStringOptionEMPTY(opts, om, "User", opts.user); lookupStringOptionEMPTY(opts, om, "Password", opts.password); // Test for outputFormats parameter with valid type string if (om.lookupValue("outputformats", opts.outputTypeParamStr)) { if (debug && verboseTest) { cout << "Output Format = " << opts.outputTypeParamStr << endl; } } // test for valid string on output type. if ((opts.outputType = OutputTypeStruct::getOutputType( opts.outputTypeParamStr)) == OUTPUT_TYPE_ILLEGAL ) { cerr << "Error: Invalid Output Type " << opts.outputTypeParamStr << ". Valid types are: "<< OutputTypeStruct::listOutputTypes() << endl; opts.termCondition = CIMCLI_INPUT_ERR; return false; } // Test for special output option -x // Note that this is after the general format definition so that it // overrides any choice made with -o Boolean xmlTest = om.isTrue("xmlOutput"); if (xmlTest) { opts.outputType = OUTPUT_XML; if (debug && verboseTest) { cout << "xmlOutput set" << endl; } } lookupUint32Option(opts, om, "repeat", opts.repeat, 0, "times"); Uint32 tempCode = 0; lookupUint32Option(opts, om, "expectedExitCode", tempCode, 0, ""); if (tempCode != 0) { setExpectedExitCode(tempCode); if (debug && verboseTest) { cout << "expectedExitCode=" << tempCode << endl; } } lookupUint32ResolvedOption(opts, om, "count", opts.executeCountTest, opts.expectedCount, 0, "Comparison Count"); /* Property List parameter. Separate an input stream into an array of Strings Two special situations, empty list and NULL list Use NULL when there is no list. This means return all Use empty if if you want no properties in the response NOTE: We use the ###!### to represent no input of parameter */ { String properties; if (om.lookupValue("propertyList", properties)) { // om default. No property list input if (properties == "###!###") { opts.propertyList.clear(); } // propertylist input empty. // Account for inputter error where they try to input string // representing two quotes else if (properties.size() == 0 || properties == "\"\"") { Array<CIMName> pList; opts.propertyList = pList; } else { Array<CIMName> pList; // tokenize everything separated by commas Array<String> pListString = _tokenize(properties, ',', true); for (Uint32 i = 0 ; i < pListString.size(); i++) { try { pList.append(CIMName(pListString[i])); } catch (InvalidNameException&) { throw OMInvalidOptionValue("propertyList", properties); } } opts.propertyList.set(pList); } if (debug && verboseTest && properties != "###!###") { cout << "PropertyList= " << opts.propertyList.toString() << endl; } } } return true; } PEGASUS_NAMESPACE_END // END_OF_FILE
36.547521
80
0.609644
[ "object" ]
334b467b7bb49715f76554bfb094f7afafc1f19f
5,165
hpp
C++
nlohmann_json/include/nlohmann/detail/iterators/iteration_proxy.hpp
BM1880-BIRD/ThirdParty
0dbf24987ba534a3cf140daefa698a75dfbb2e0b
[ "Apache-2.0" ]
2,111
2019-01-29T07:01:32.000Z
2022-03-29T06:48:14.000Z
software/scene_retrieving/src/nlohmann_json/include/nlohmann/detail/iterators/iteration_proxy.hpp
Wayne-xixi/GAAS
308ff4267ccc6fcad77eef07e21fa006cc2cdd5f
[ "BSD-3-Clause" ]
131
2019-02-18T10:56:18.000Z
2021-09-27T12:07:00.000Z
software/scene_retrieving/src/nlohmann_json/include/nlohmann/detail/iterators/iteration_proxy.hpp
Wayne-xixi/GAAS
308ff4267ccc6fcad77eef07e21fa006cc2cdd5f
[ "BSD-3-Clause" ]
421
2019-02-12T07:59:18.000Z
2022-03-27T05:22:01.000Z
#pragma once #include <cstddef> // size_t #include <string> // string, to_string #include <iterator> // input_iterator_tag #include <tuple> // tuple_size, get, tuple_element #include <nlohmann/detail/value_t.hpp> #include <nlohmann/detail/meta/type_traits.hpp> namespace nlohmann { namespace detail { template <typename IteratorType> class iteration_proxy_value { public: using difference_type = std::ptrdiff_t; using value_type = iteration_proxy_value; using pointer = value_type * ; using reference = value_type & ; using iterator_category = std::input_iterator_tag; private: /// the iterator IteratorType anchor; /// an index for arrays (used to create key names) std::size_t array_index = 0; /// last stringified array index mutable std::size_t array_index_last = 0; /// a string representation of the array index mutable std::string array_index_str = "0"; /// an empty string (to return a reference for primitive values) const std::string empty_str = ""; public: explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {} /// dereference operator (needed for range-based for) iteration_proxy_value& operator*() { return *this; } /// increment operator (needed for range-based for) iteration_proxy_value& operator++() { ++anchor; ++array_index; return *this; } /// equality operator (needed for InputIterator) bool operator==(const iteration_proxy_value& o) const { return anchor == o.anchor; } /// inequality operator (needed for range-based for) bool operator!=(const iteration_proxy_value& o) const { return anchor != o.anchor; } /// return key of the iterator const std::string& key() const { assert(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: { if (array_index != array_index_last) { array_index_str = std::to_string(array_index); array_index_last = array_index; } return array_index_str; } // use key from the object case value_t::object: return anchor.key(); // use an empty key for all primitive types default: return empty_str; } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// proxy class for the items() function template<typename IteratorType> class iteration_proxy { private: /// the container to iterate typename IteratorType::reference container; public: /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) noexcept : container(cont) {} /// return iterator begin (needed for range-based for) iteration_proxy_value<IteratorType> begin() noexcept { return iteration_proxy_value<IteratorType>(container.begin()); } /// return iterator end (needed for range-based for) iteration_proxy_value<IteratorType> end() noexcept { return iteration_proxy_value<IteratorType>(container.end()); } }; // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0> auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key()) { return i.key(); } // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0> auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value()) { return i.value(); } } // namespace detail } // namespace nlohmann // The Addition to the STD Namespace is required to add // Structured Bindings Support to the iteration_proxy_value class // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 namespace std { #if defined(__clang__) // Fix: https://github.com/nlohmann/json/issues/1401 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmismatched-tags" #endif template <typename IteratorType> class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>> : public std::integral_constant<std::size_t, 2> {}; template <std::size_t N, typename IteratorType> class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >> { public: using type = decltype( get<N>(std::declval < ::nlohmann::detail::iteration_proxy_value<IteratorType >> ())); }; #if defined(__clang__) #pragma clang diagnostic pop #endif }
30.204678
95
0.663698
[ "object" ]
334b4e2613964318db44c37a5be9122381e93ba9
3,395
hpp
C++
include/System/Xml/Schema/DtdValidator_NamespaceManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/Xml/Schema/DtdValidator_NamespaceManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/Xml/Schema/DtdValidator_NamespaceManager.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Xml.Schema.DtdValidator #include "System/Xml/Schema/DtdValidator.hpp" // Including type: System.Xml.XmlNamespaceManager #include "System/Xml/XmlNamespaceManager.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Xml::Schema::DtdValidator::NamespaceManager); DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Schema::DtdValidator::NamespaceManager*, "System.Xml.Schema", "DtdValidator/NamespaceManager"); // Type namespace: System.Xml.Schema namespace System::Xml::Schema { // Size: 0x50 #pragma pack(push, 1) // Autogenerated type: System.Xml.Schema.DtdValidator/System.Xml.Schema.NamespaceManager // [TokenAttribute] Offset: FFFFFFFF class DtdValidator::NamespaceManager : public ::System::Xml::XmlNamespaceManager { public: // public System.Void .ctor() // Offset: 0x1C22F40 // Implemented from: System.Xml.XmlNamespaceManager // Base method: System.Void XmlNamespaceManager::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static DtdValidator::NamespaceManager* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::DtdValidator::NamespaceManager::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<DtdValidator::NamespaceManager*, creationType>())); } // public override System.String LookupNamespace(System.String prefix) // Offset: 0x1C22F48 // Implemented from: System.Xml.XmlNamespaceManager // Base method: System.String XmlNamespaceManager::LookupNamespace(System.String prefix) ::StringW LookupNamespace(::StringW prefix); }; // System.Xml.Schema.DtdValidator/System.Xml.Schema.NamespaceManager #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Xml::Schema::DtdValidator::NamespaceManager::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Xml::Schema::DtdValidator::NamespaceManager::LookupNamespace // Il2CppName: LookupNamespace template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::Schema::DtdValidator::NamespaceManager::*)(::StringW)>(&System::Xml::Schema::DtdValidator::NamespaceManager::LookupNamespace)> { static const MethodInfo* get() { static auto* prefix = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Xml::Schema::DtdValidator::NamespaceManager*), "LookupNamespace", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{prefix}); } };
55.655738
221
0.747275
[ "object", "vector" ]
334d268dbd07a15ce936758343763b541e9b4a8d
8,779
cpp
C++
source/Photon.cpp
sgshulman/DGEM
5958e4c06f31e273b0a5b2de563822a02c1f03ef
[ "BSD-2-Clause" ]
null
null
null
source/Photon.cpp
sgshulman/DGEM
5958e4c06f31e273b0a5b2de563822a02c1f03ef
[ "BSD-2-Clause" ]
null
null
null
source/Photon.cpp
sgshulman/DGEM
5958e4c06f31e273b0a5b2de563822a02c1f03ef
[ "BSD-2-Clause" ]
null
null
null
#include <cmath> #include "CartesianGrid.hpp" #include "Observer.hpp" #include "Photon.hpp" #include "Random.hpp" #include "Directions.hpp" #include "IDust.hpp" Photon::Photon( Vector3d const& pos, std::uint64_t cellId, Direction3d const& dir, double weight, std::uint32_t nscat, double fi, double fq, double fu, double fv ) : pos_{ pos } , dir_{ dir } , nscat_{ nscat } , cellId_{ cellId } , weight_{ weight } , fi_{ fi } , fq_{ fq } , fu_{ fu } , fv_{ fv } {} double Photon::Scatt(IDustCRef dust, Direction3d const& dir, Random* ran) { // cos(Theta), where Theta is angle between incident // and outgoing (i.e., observed) photon direction double const cosTheta = dir_.vector() * dir.vector(); double const fraction = dust->fraction(cosTheta) / 4. / PI; Stokes(dust, dir, cosTheta, true, ran); return fraction; } void Photon::Scatt( Model const &m, Directions const &dirs, IGridCRef grid, std::vector<Observer>& observers, Random* ran) { if (nscat_ == m.MonteCarloStart() ) { Photon ph(*this); int tflag = 0; ph.Stokes( m.dust(), Direction3d(), 0.0, false, ran); tflag = grid->movePhotonAtRandomDepth(ph, ran); ph.nscat()+=1; while ( !tflag && ( ph.nscat() <= m.nscat() ) ) { ph.weight() *= m.dust()->albedo(); // Do peeling off and project weighted photons into image for (Observer& observer : observers) { grid->peeloff(ph, observer, m.dust()); } // Scatter photon into new direction and update Stokes parameters ph.Stokes( m.dust(), Direction3d(), 0.0, false, ran); ph.nscat()+=1; if (ph.nscat() > m.nscat()) break; // Find next scattering location tflag = grid->movePhotonAtRandomDepth(ph, ran); } } else { double calpha; double fraction; // normalizing double sum=0; for (std::uint64_t j=0; j!=dirs.number(); ++j) { calpha = dir_.vector() * dirs.direction(j); sum += dirs.w(j) * m.dust()->fraction(calpha); } for (std::uint64_t j=0; j!=dirs.number(); ++j) { // Release photon from point source calpha = dir_.vector() * dirs.direction(j); fraction = m.dust()->fraction(calpha); Photon ph0(pos_, cellId_, dir_, weight_ * dirs.w( j )*fraction/sum, nscat_+1, fi_, fq_, fu_, fv_ ); ph0.Stokes(m.dust(), dirs.direction(j), calpha, true, ran); double w = 1.0 / m.NumOfSecondaryScatterings() ; Vector3d spos = pos_; std::uint64_t sCellId = cellId_; double tauold = 0.0, tau = 0.0; // Loop over scattering dots for (std::uint64_t s=0; s!=m.NumOfSecondaryScatterings(); ++s) { Photon ph(spos, sCellId, ph0.dir(), ph0.weight()*w, nscat_+1, ph0.fi(), ph0.fq(), ph0.fu(), ph0.fv() ); // Force photon to scatter at optical depth tau before edge of grid tauold = tau; tau = -std::log( 1.0-0.5*w*(2*s+1) ); // Find scattering location of tau if( grid->movePhotonAtDepth(ph, tau, tauold) ) { break; } else { spos = ph.pos(); sCellId = ph.cellId(); // Photon scattering ph.weight() *= m.dust()->albedo(); for (Observer& observer : observers) { grid->peeloff(ph, observer, m.dust()); } if (ph.nscat() < m.nscat() ) ph.Scatt( m, dirs, grid, observers, ran); } } } } } // Stokes vector changes // spherical trigonometry is used void Photon::Stokes(IDustCRef dust, Direction3d const &dir, double calpha, bool fDir, Random* ran) { double a11,a12,a13,a21,a22,a23,a24,a31,a32,a33,a34; double a42,a43,a44; double phi=0.0, cost, sint; double wght = fi_; fi_ /= wght; fq_ /= wght; fu_ /= wght; fv_ /= wght; double costp = dir_.cosTheta(); double sintp = dir_.sinTheta(); double phip = dir_.phi(); // dust scattering double cosTh; if (fDir) { cosTh = calpha; } else { cosTh = dust->cosRandomTheta(ran->Get()); } if ( cosTh > 1.0 ) { cosTh=1.0; }else if(cosTh < -1.0) { cosTh=-1.0; } double p1, p2, p3, p4; dust->scatteringMatrixElements(p1, p2, p3, p4, cosTh); double a = p1; double sinTh = sqrt(1.0 - cosTh*cosTh); double ri1; if (fDir) { double ophi = dir.phi(); if (ophi > PI) ophi -= 2*PI; double cosi1 = (dir.cosTheta()-dir_.cosTheta()*cosTh)/(dir_.sinTheta()*sinTh); double sini1 = sin(dir_.phi()-ophi-PI)*dir.sinTheta()/sinTh; ri1 = atan2(sini1, cosi1)+PI; } else { ri1=2*PI*ran->Get(); } if(ri1 >= PI) { double ri3 = PI*2-ri1; double cosi3=cos(ri3); double sini3=sin(ri3); double sin2i3=2.0*sini3*cosi3; double cos2i3=2.0*cosi3*cosi3-1.0; a11=p1; a12=p2*cos2i3; a13=p2*sin2i3; if(cosTh == 1.0) return; if(cosTh ==-1.0) { fu_=-fu_; return; } if (fDir) { cost = dir.cosTheta(); sint = dir.sinTheta(); } else { cost = costp*cosTh+sintp*sinTh*cosi3; sint = fabs(sqrt(1.0-cost*cost)); } double sini2=0.0, cosi2=1.0; if(cost < 1.0 && cost > -1.0) { sini2=sini3*sintp/sint; double bott=sint*sinTh; cosi2=costp/bott-cost*cosTh/bott; } else if(cost >= 1.0) { cosi2=-1.0; } if (!fDir) { double cosdph=-cosi2*cosi3+sini2*sini3*cosTh; if(cosdph > 1.0) cosdph=1.0; if(cosdph <-1.0) cosdph=-1.0; phi = normAngle(phip + acos(cosdph)); } double sin2i2=2.0*sini2*cosi2; double cos2i2=2.0*cosi2*cosi2-1.0; double sin2=sin2i2*sin2i3; double cos2=cos2i2*cos2i3; double sin2cos1=sin2i2*cos2i3; double cos2sin1=cos2i2*sin2i3; a21=p2*cos2i2; a22=p1*cos2-p3*sin2; a23=p1*cos2sin1+p3*sin2cos1; a24=-p4*sin2i2; a31=-p2*sin2i2; a32=-p1*sin2cos1-p3*cos2sin1; a33=-p1*sin2+p3*cos2; a34=-p4*cos2i2; a42=-p4*sin2i3; a43=p4*cos2i3; a44=p3; } else { double cosi1=cos(ri1); double sini1=sin(ri1); double sin2i1=2.0*sini1*cosi1; double cos2i1=2.0*cosi1*cosi1-1.0; a11=p1; a12=p2*cos2i1; a13=-p2*sin2i1; if(cosTh == 1.0) return; if(cosTh ==-1.0) { fu_=-fu_; return; } if ( fDir ) { cost = dir.cosTheta(); sint = dir.sinTheta(); } else { cost=costp*cosTh+sintp*sinTh*cosi1; sint=fabs(sqrt(1.0-cost*cost)); } double sini2=0.0, cosi2=1.0; if(cost < 1.0 && cost > -1.0) { sini2=sini1*sintp/sint; double bott=sint*sinTh; cosi2=costp/bott-cost*cosTh/bott; } else if(cost >= 1.0) { cosi2=-1.0; } if( !fDir ) { double cosdph=-cosi1*cosi2+sini1*sini2*cosTh; if( cosdph > 1.0 ) cosdph= 1.0; if( cosdph <-1.0 ) cosdph=-1.0; phi = normAngle(phip - acos(cosdph)); } double sin2i2=2.0*sini2*cosi2; double cos2i2=2.0*cosi2*cosi2-1.0; double sin2=sin2i2*sin2i1; double cos2=cos2i2*cos2i1; double sin2cos1=sin2i2*cos2i1; double cos2sin1=cos2i2*sin2i1; a21=p2*cos2i2; a22=p1*cos2-p3*sin2; a23=-p1*cos2sin1-p3*sin2cos1; a24=p4*sin2i2; a31=p2*sin2i2; a32=p1*sin2cos1+p3*cos2sin1; a33=-p1*sin2+p3*cos2; a34=-p4*cos2i2; a42=p4*sin2i1; a43=p4*cos2i1; a44=p3; } double si=(a11*fi_+a12*fq_+a13*fu_)/a; double sq=(a21*fi_+a22*fq_+a23*fu_+a24*fv_)/a; double su=(a31*fi_+a32*fq_+a33*fu_+a34*fv_)/a; double sv=(a42*fq_+a43*fu_+a44*fv_)/a; fi_=si*wght; fq_=sq*wght; fu_=su*wght; fv_=sv*wght; if( fDir ) { dir_ = dir; } else { double cosp=cos(phi); double sinp=sin(phi); dir_ = Direction3d(Vector3d{sint*cosp, sint*sinp, cost}); } }
28.319355
163
0.508031
[ "vector", "model" ]
334e52fa83eac53bccee743025d9b182026c44ef
4,808
cpp
C++
src/third_party/mozjs-45/extract/js/src/vm/StringBuffer.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
4
2018-02-06T01:53:12.000Z
2018-02-20T01:47:36.000Z
src/third_party/mozjs-45/extract/js/src/vm/StringBuffer.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
null
null
null
src/third_party/mozjs-45/extract/js/src/vm/StringBuffer.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
3
2018-02-06T01:53:18.000Z
2021-07-28T09:48:15.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "vm/StringBuffer.h" #include "mozilla/Range.h" #include "jsobjinlines.h" #include "vm/String-inl.h" using namespace js; template <typename CharT, class Buffer> static CharT* ExtractWellSized(ExclusiveContext* cx, Buffer& cb) { size_t capacity = cb.capacity(); size_t length = cb.length(); CharT* buf = cb.extractRawBuffer(); if (!buf) return nullptr; /* For medium/big buffers, avoid wasting more than 1/4 of the memory. */ MOZ_ASSERT(capacity >= length); if (length > Buffer::sMaxInlineStorage && capacity - length > length / 4) { CharT* tmp = cx->zone()->pod_realloc<CharT>(buf, capacity, length + 1); if (!tmp) { js_free(buf); ReportOutOfMemory(cx); return nullptr; } buf = tmp; } return buf; } char16_t* StringBuffer::stealChars() { if (isLatin1() && !inflateChars()) return nullptr; return ExtractWellSized<char16_t>(cx, twoByteChars()); } bool StringBuffer::inflateChars() { MOZ_ASSERT(isLatin1()); TwoByteCharBuffer twoByte(cx); /* * Note: we don't use Vector::capacity() because it always returns a * value >= sInlineCapacity. Since Latin1CharBuffer::sInlineCapacity > * TwoByteCharBuffer::sInlineCapacitychars, we'd always malloc here. */ size_t capacity = Max(reserved_, latin1Chars().length()); if (!twoByte.reserve(capacity)) return false; twoByte.infallibleAppend(latin1Chars().begin(), latin1Chars().length()); cb.destroy(); cb.construct<TwoByteCharBuffer>(Move(twoByte)); return true; } template <typename CharT, class Buffer> static JSFlatString* FinishStringFlat(ExclusiveContext* cx, StringBuffer& sb, Buffer& cb) { size_t len = sb.length(); if (!sb.append('\0')) return nullptr; ScopedJSFreePtr<CharT> buf(ExtractWellSized<CharT>(cx, cb)); if (!buf) return nullptr; JSFlatString* str = NewStringDontDeflate<CanGC>(cx, buf.get(), len); if (!str) return nullptr; /* * The allocation was made on a TempAllocPolicy, so account for the string * data on the string's zone. */ str->zone()->updateMallocCounter(sizeof(CharT) * len); buf.forget(); return str; } JSFlatString* StringBuffer::finishString() { size_t len = length(); if (len == 0) return cx->names().empty; if (!JSString::validateLength(cx, len)) return nullptr; JS_STATIC_ASSERT(JSFatInlineString::MAX_LENGTH_TWO_BYTE < TwoByteCharBuffer::InlineLength); JS_STATIC_ASSERT(JSFatInlineString::MAX_LENGTH_LATIN1 < Latin1CharBuffer::InlineLength); if (isLatin1()) { if (JSInlineString::lengthFits<Latin1Char>(len)) { mozilla::Range<const Latin1Char> range(latin1Chars().begin(), len); return NewInlineString<CanGC>(cx, range); } } else { if (JSInlineString::lengthFits<char16_t>(len)) { mozilla::Range<const char16_t> range(twoByteChars().begin(), len); return NewInlineString<CanGC>(cx, range); } } return isLatin1() ? FinishStringFlat<Latin1Char>(cx, *this, latin1Chars()) : FinishStringFlat<char16_t>(cx, *this, twoByteChars()); } JSAtom* StringBuffer::finishAtom() { size_t len = length(); if (len == 0) return cx->names().empty; if (isLatin1()) { JSAtom* atom = AtomizeChars(cx, latin1Chars().begin(), len); latin1Chars().clear(); return atom; } JSAtom* atom = AtomizeChars(cx, twoByteChars().begin(), len); twoByteChars().clear(); return atom; } bool js::ValueToStringBufferSlow(JSContext* cx, const Value& arg, StringBuffer& sb) { RootedValue v(cx, arg); if (!ToPrimitive(cx, JSTYPE_STRING, &v)) return false; if (v.isString()) return sb.append(v.toString()); if (v.isNumber()) return NumberValueToStringBuffer(cx, v, sb); if (v.isBoolean()) return BooleanToStringBuffer(v.toBoolean(), sb); if (v.isNull()) return sb.append(cx->names().null); if (v.isSymbol()) { JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_SYMBOL_TO_STRING); return false; } MOZ_ASSERT(v.isUndefined()); return sb.append(cx->names().undefined); }
28.116959
96
0.613977
[ "vector" ]
334f97757c3010e53aa2fa12d68f23979ad75027
317
cpp
C++
303/P303/P303/main.cpp
swy20190/Leetcode-Cracker
3b80eacfa63983d5fcc50442f0813296d5c1af94
[ "MIT" ]
null
null
null
303/P303/P303/main.cpp
swy20190/Leetcode-Cracker
3b80eacfa63983d5fcc50442f0813296d5c1af94
[ "MIT" ]
null
null
null
303/P303/P303/main.cpp
swy20190/Leetcode-Cracker
3b80eacfa63983d5fcc50442f0813296d5c1af94
[ "MIT" ]
null
null
null
#include <vector> using namespace std; class NumArray { vector<int> front_sum; public: NumArray(vector<int>& nums) { int tmp = 0; front_sum.push_back(0); for (auto num : nums) { tmp += num; front_sum.push_back(tmp); } } int sumRange(int i, int j) { return front_sum[j + 1] - front_sum[i]; } };
15.85
41
0.634069
[ "vector" ]
3353f33bd6dd743232ef8747b82468166034f1c0
37,593
cpp
C++
Porthos/src/tools.cpp
kanav99/EzPC
094e75111d00883dd90ef328bd47a7c0a1eb689f
[ "MIT" ]
221
2019-05-16T16:42:49.000Z
2022-03-29T14:05:31.000Z
Porthos/src/tools.cpp
kanav99/EzPC
094e75111d00883dd90ef328bd47a7c0a1eb689f
[ "MIT" ]
63
2019-07-02T11:50:15.000Z
2022-03-31T08:14:02.000Z
Porthos/src/tools.cpp
kanav99/EzPC
094e75111d00883dd90ef328bd47a7c0a1eb689f
[ "MIT" ]
67
2019-08-30T08:44:47.000Z
2022-03-23T08:08:33.000Z
/* * BMR_BGW_aux.cpp * * Author: Aner Ben-Efraim, Satyanarayana * * year: 2016 * * Modified for crypTFlow. */ #include "tools.h" #include <stdint.h> #include <mutex> #include <bitset> //If Porthos compiled with Eigen support #ifdef USE_EIGEN #include <Eigen/Dense> using namespace Eigen; #endif using namespace std; #define NANOSECONDS_PER_SEC 1E9 //For time measurements clock_t tStart; struct timespec requestStart, requestEnd; bool alreadyMeasuringTime = false; int roundComplexitySend = 0; int roundComplexityRecv = 0; bool alreadyMeasuringRounds = false; extern void aggregateCommunication(); extern CommunicationObject commObject; /************************************ Some statistics functions ***********************/ void start_time() { if (alreadyMeasuringTime) { cout << "Nested timing measurements" << endl; exit(-1); } tStart = clock(); clock_gettime(CLOCK_REALTIME, &requestStart); alreadyMeasuringTime = true; } double diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp.tv_sec + (double)temp.tv_nsec/NANOSECONDS_PER_SEC; } void end_time() { if (!alreadyMeasuringTime) { cout << "start_time() never called" << endl; exit(-1); } clock_gettime(CLOCK_REALTIME, &requestEnd); #ifdef RUNTIME_DETAILED cout << "------------------------------------" << endl; cout << "Wall Clock time for execution: " << diff(requestStart, requestEnd) << " sec\n"; cout << "CPU time for execution: " << (double)(clock() - tStart)/CLOCKS_PER_SEC << " sec\n"; #endif cout << "------------------------------------" << endl; alreadyMeasuringTime = false; } void start_rounds() { if (alreadyMeasuringRounds) { cout << "Nested round measurements" << endl; exit(-1); } roundComplexitySend = 0; roundComplexityRecv = 0; alreadyMeasuringRounds = true; } void end_rounds() { if (!alreadyMeasuringTime) { cout << "start_rounds() never called" << endl; exit(-1); } cout << "------------------------------------" << endl; cout << "Send Round Complexity of execution: " << roundComplexitySend << endl; cout << "Recv Round Complexity of execution: " << roundComplexityRecv << endl; cout << "------------------------------------" << endl; alreadyMeasuringRounds = false; } //This function should be useed for some layer wise timing analysis #if (LOG_LAYERWISE) void analyseComputeVsCommTime() { /* assert(commObject.dataSent.size() == commObject.timeInSending.size()); assert(commObject.dataReceived.size() == commObject.timeInReceiving.size()); */ double totalTimeInSending = commObject.totalTimeInSending; double totalTimeInReceiving = commObject.totalTimeInReceiving; porthosLongUnsignedInt totalDataSent = commObject.totalDataSent; porthosLongUnsignedInt totalDataReceived = commObject.totalDataReceived; /* for(int i=0,end=commObject.dataSent.size();i<end;i++){ totalDataSent += commObject.dataSent[i]; totalTimeInSending += commObject.timeInSending[i]; } for(int i=0,end=commObject.dataReceived.size();i<end;i++){ totalDataReceived += commObject.dataReceived[i]; totalTimeInReceiving += commObject.timeInReceiving[i]; } */ cout<<"Total data sent = "<<totalDataSent<<", total time in sending = "<<totalTimeInSending<<endl; cout<<"Total data received = "<<totalDataReceived<<", total time in receving = "<<totalTimeInReceiving<<endl; cout<<"Average b/w in sending = "<<(totalDataSent/(1000*1000*totalTimeInSending))<<" MBps"<<endl; cout<<"Average b/w in receiving = "<<(totalDataReceived/(1000*1000*totalTimeInReceiving))<<" MBps"<<endl; cout<<"Min size sent = "<<commObject.minSizeSent<<endl; cout<<"matmul time comm, matmul time total, data sent, data received = " <<commObject.timeMatmul[0]<<" " <<commObject.timeMatmul[1]<<" " <<(commObject.dataMatmul[0]/(1000.0*1000.0))<<" " <<(commObject.dataMatmul[1]/(1000.0*1000.0))<<endl; cout<<"relu time, data sent, data received = " <<commObject.timeRelu<<" " <<(commObject.dataRelu[0]/(1000.0*1000.0))<<" " <<(commObject.dataRelu[1]/(1000.0*1000.0))<<endl; cout<<"maxpool time, data sent, data received = " <<commObject.timeMaxpool<<" " <<(commObject.dataMaxPool[0]/(1000.0*1000.0))<<" " <<(commObject.dataMaxPool[1]/(1000.0*1000.0))<<endl; cout<<"avgpool time, data sent, data received = " <<commObject.timeAvgPool<<" " <<(commObject.dataAvgPool[0]/(1000.0*1000.0))<<" " <<(commObject.dataAvgPool[1]/(1000.0*1000.0))<<endl; cout<<"bn time, data sent, data received = " <<commObject.timeBN<<" " <<(commObject.dataBN[0]/(1000.0*1000.0))<<" " <<(commObject.dataBN[1]/(1000.0*1000.0))<<endl; } #endif //Aggregate some stats about ongoing communication void aggregateCommunication() { vector<size_t> vec(4, 0), temp(4, 0); vec[0] = commObject.getSent(); vec[1] = commObject.getRecv(); vec[2] = commObject.getRoundsSent(); vec[3] = commObject.getRoundsRecv(); if (partyNum == PARTY_B or partyNum == PARTY_C) sendVector<size_t>(vec, PARTY_A, 4); if (partyNum == PARTY_A) { receiveVector<size_t>(temp, PARTY_B, 4); addVectors<size_t>(vec, temp, vec, 4); receiveVector<size_t>(temp, PARTY_C, 4); addVectors<size_t>(vec, temp, vec, 4); } if (partyNum == PARTY_A) { cout << "------------------------------------" << endl; cout << "Total communication: " << (double)vec[0]/(1024 * 1024) << "MiB (sent) and " << (double)vec[1]/(1024 * 1024) << "MiB (recv)\n"; cout << "Total #calls: " << vec[2] << " (sends) and " << vec[3] << " (recvs)" << endl; cout << "------------------------------------" << endl; } } void start_m() { cout << endl; start_time(); start_communication(); } void end_m() { end_time(); pause_communication(); aggregateCommunication(); #if (LOG_LAYERWISE) analyseComputeVsCommTime(); #endif end_communication(); } /************************************ Some MatMul functions ************************/ // If Eigen is not to be used for matmul #ifndef USE_EIGEN void matrixMultEigen(const vector<porthosSecretType> &a, const vector<porthosSecretType> &b, vector<porthosSecretType> &c, size_t rows, size_t common_dim, size_t columns, size_t transpose_a, size_t transpose_b) { assert(transpose_a == 0 && transpose_b == 0 && "Transpose support not added yet"); int ta, tc; porthosSecretType cumu_ele; for(int r=0; r<rows; r++){ ta = r*common_dim; tc = r*columns; for(int col=0; col<columns; col++){ cumu_ele = 0; for(int com=0; com<common_dim; com++){ cumu_ele += a[ta + com] * b[com*columns + col]; } c[tc + col] = cumu_ele; } } } void matrixMultEigen(const vector<vector<porthosSecretType>> &a, const vector<vector<porthosSecretType>> &b, vector<vector<porthosSecretType>> &c, size_t rows, size_t common_dim, size_t columns, size_t transpose_a, size_t transpose_b) { assert(transpose_a == 0 && transpose_b == 0 && "Transpose support not added yet"); porthosSecretType cumu_ele; for(int r=0; r<rows; r++){ for(int col=0; col<columns; col++){ cumu_ele = 0; for(int com=0; com<common_dim; com++){ cumu_ele += a[r][com] * b[com][col]; } c[r][col] = cumu_ele; } } } void matrixMultEigen(porthosSecretType* a, porthosSecretType* b, porthosSecretType* c, size_t rows, size_t common_dim, size_t columns, size_t transpose_a, size_t transpose_b) { assert(transpose_a == 0 && transpose_b == 0 && "Transpose support not added yet"); int ta, tc; porthosSecretType cumu_ele; for(int r=0; r<rows; r++){ ta = r*common_dim; tc = r*columns; for(int col=0; col<columns; col++){ cumu_ele = 0; for(int com=0; com<common_dim; com++){ cumu_ele += a[ta + com] * b[com*columns + col]; } c[tc + col] = cumu_ele; } } } #else //Use Eigen MatMul void matrixMultEigen(const vector<porthosSecretType> &a, const vector<porthosSecretType> &b, vector<porthosSecretType> &c, size_t rows, size_t common_dim, size_t columns, size_t transpose_a, size_t transpose_b) { Matrix<porthosSecretType, Dynamic, Dynamic> eigen_a(rows, common_dim); Matrix<porthosSecretType, Dynamic, Dynamic> eigen_b(common_dim, columns); Matrix<porthosSecretType, Dynamic, Dynamic> eigen_c(rows, columns); for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < common_dim; ++j) { if (transpose_a) eigen_a(i, j) = a[j*rows + i]; else eigen_a(i, j) = a[i*common_dim + j]; } } for (size_t i = 0; i < common_dim; ++i) { for (size_t j = 0; j < columns; ++j) { if (transpose_b) eigen_b(i, j) = b[j*common_dim + i]; else eigen_b(i, j) = b[i*columns + j]; } } eigen_c = eigen_a * eigen_b; for (size_t i = 0; i < rows; ++i) for (size_t j = 0; j < columns; ++j) c[i*columns + j] = eigen_c(i,j); } void matrixMultEigen(const vector< vector<porthosSecretType> > &a, const vector< vector<porthosSecretType> > &b, vector< vector<porthosSecretType> > &c, size_t rows, size_t common_dim, size_t columns, size_t transpose_a, size_t transpose_b) { Matrix<porthosSecretType, Dynamic, Dynamic> eigen_a(rows, common_dim); Matrix<porthosSecretType, Dynamic, Dynamic> eigen_b(common_dim, columns); Matrix<porthosSecretType, Dynamic, Dynamic> eigen_c(rows, columns); for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < common_dim; ++j) { if (transpose_a) eigen_a(i, j) = a[j][i]; else eigen_a(i, j) = a[i][j]; } } for (size_t i = 0; i < common_dim; ++i) { for (size_t j = 0; j < columns; ++j) { if (transpose_b) eigen_b(i, j) = b[j][i]; else eigen_b(i, j) = b[i][j]; } } eigen_c = eigen_a * eigen_b; for (size_t i = 0; i < rows; ++i) for (size_t j = 0; j < columns; ++j) c[i][j] = eigen_c(i,j); } void matrixMultEigen(porthosSecretType* a, porthosSecretType* b, porthosSecretType* c, size_t rows, size_t common_dim, size_t columns, size_t transpose_a, size_t transpose_b) { Matrix<porthosSecretType, Dynamic, Dynamic> eigen_a(rows, common_dim); Matrix<porthosSecretType, Dynamic, Dynamic> eigen_b(common_dim, columns); Matrix<porthosSecretType, Dynamic, Dynamic> eigen_c(rows, columns); for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < common_dim; ++j) { if (transpose_a) eigen_a(i, j) = Arr2DIdx(a, rows, common_dim, j, i); else eigen_a(i, j) = Arr2DIdx(a, rows, common_dim, i, j); } } for (size_t i = 0; i < common_dim; ++i) { for (size_t j = 0; j < columns; ++j) { if (transpose_b) eigen_b(i, j) = Arr2DIdx(b, common_dim, columns, j, i); else eigen_b(i, j) = Arr2DIdx(b, common_dim, columns, i, j); } } eigen_c = eigen_a * eigen_b; for (size_t i = 0; i < rows; ++i) for (size_t j = 0; j < columns; ++j) Arr2DIdx(c, rows, columns, i, j) = eigen_c(i,j); } #endif /*************************************** End of MatMul functions ***********************************/ /*************************************** Some other STANDALONE EXECTION utility functions **************************/ porthosSecretType divideMyTypeSA(porthosSecretType a, porthosSecretType b) { assert((sizeof(double) == sizeof(porthosSecretType)) && "sizeof(double) != sizeof(porthosSecretType)"); assert((b != 0) && "Cannot divide by 0"); return floatToMyType((double)((porthosLongSignedInt)a)/(double)((porthosLongSignedInt)b)); } porthosSecretType dividePlainSA(porthosSecretType a, int b) { assert((b != 0) && "Cannot divide by 0"); return static_cast<porthosSecretType>(static_cast<porthosLongSignedInt>(a)/static_cast<porthosLongSignedInt>(b)); } void dividePlainSA(vector<porthosSecretType> &vec, int divisor) { assert((sizeof(double) == sizeof(porthosSecretType)) && "sizeof(double) != sizeof(porthosSecretType)"); assert((divisor != 0) && "Cannot divide by 0"); for (int i = 0; i < vec.size(); ++i) vec[i] = (porthosSecretType)((double)((porthosLongSignedInt)vec[i])/(double)((porthosLongSignedInt)divisor)); } porthosSecretType multiplyMyTypesSA(porthosSecretType a, porthosSecretType b, int shift) { porthosSecretType ret; ret = static_cast<porthosSecretType>((static_cast<porthosLongSignedInt>(a) * static_cast<porthosLongSignedInt>(b))/ (1 << shift)); return ret; } /*************************************** Other small utility functions ************************************/ void XORVectors(const vector<smallType> &a, const vector<smallType> &b, vector<smallType> &c, size_t size) { for (size_t i = 0; i < size; ++i) c[i] = a[i] ^ b[i]; } void log_print(string str) { #if (LOG_DEBUG) cout << "----------------------------" << endl; cout << "Started " << str << " at " << getCurrentTime() << endl; cout << "----------------------------" << endl; #endif } void error(string str) { cout << "Error: " << str << endl; exit(-1); } size_t adversary(size_t party) { size_t ret; switch(party) { case PARTY_A : ret = PARTY_B; break; case PARTY_B : ret = PARTY_A; break; } return ret; } smallType subtractModPrime(smallType a, smallType b) { if (b == 0) return a; else { b = (PRIME_NUMBER - b); return additionModPrime[a][b]; } } void wrapAround(const vector<porthosSecretType> &a, const vector<porthosSecretType> &b, vector<smallType> &c, size_t size) { for (size_t i = 0; i < size; ++i) c[i] = wrapAround(a[i], b[i]); } /************************************* Some functions with AES and resharing ****************************/ void populateBitsVector(vector<smallType> &vec, string r_type, size_t size) { assert((r_type == "COMMON" or r_type == "INDEP") && "invalid randomness type for populateBitsVector"); if (r_type == "COMMON") { for (size_t i = 0; i < size; ++i) vec[i] = aes_common->getBit(); } if (r_type == "INDEP") { for (size_t i = 0; i < size; ++i) vec[i] = aes_indep->getBit(); } } //Returns shares of MSB...LSB of first number and so on. void sharesOfBits(vector<smallType> &bit_shares_x_1, vector<smallType> &bit_shares_x_2, const vector<porthosSecretType> &x, size_t size, string r_type) { #ifdef DEBUG assert((r_type == "PRG_COMM_OPTI" || (r_type == "COMMON" or r_type == "INDEP")) && "invalid randomness type for sharesOfBits"); assert(partyNum == PARTY_C); #endif smallType temp; if (r_type == "COMMON") { #ifdef PRECOMPUTEAES aes_common->fillWithRandomModuloPrimeBits(bit_shares_x_1.data(), size*BIT_SIZE); #else for (size_t i = 0; i < size; ++i) { for (size_t k = 0; k < BIT_SIZE; ++k) { bit_shares_x_1[i*BIT_SIZE + k] = aes_common->randModPrime(); } } #endif for (size_t i = 0; i < size; ++i) { for (size_t k = 0; k < BIT_SIZE; ++k) { bit_shares_x_2[i*BIT_SIZE + k] = subtractModPrime((x[i] >> (BIT_SIZE - 1 - k) & 1), bit_shares_x_1[i*BIT_SIZE + k]); } } } else if (r_type == "INDEP") { #ifdef PRECOMPUTEAES aes_indep->fillWithRandomModuloPrimeBits(bit_shares_x_1.data(), size*BIT_SIZE); #else for (size_t i = 0; i < size; ++i) { for (size_t k = 0; k < BIT_SIZE; ++k) { bit_shares_x_1[i*BIT_SIZE + k] = aes_indep->randModPrime(); } } #endif for (size_t i = 0; i < size; ++i) { for (size_t k = 0; k < BIT_SIZE; ++k) { bit_shares_x_2[i*BIT_SIZE + k] = subtractModPrime((x[i] >> (BIT_SIZE - 1 - k) & 1), bit_shares_x_1[i*BIT_SIZE + k]); } } } else if (r_type == "PRG_COMM_OPTI") { #ifdef PRECOMPUTEAES aes_share_conv_bit_shares_p0_p2->fillWithRandomModuloPrimeBits(bit_shares_x_1.data(), (size/2)*BIT_SIZE); aes_share_conv_bit_shares_p1_p2->fillWithRandomModuloPrimeBits(bit_shares_x_2.data() + (size/2)*BIT_SIZE, (size - (size/2))*BIT_SIZE); #else for(size_t i = 0; i < (size/2); i++) { for(size_t k=0; k<BIT_SIZE; k++) { bit_shares_x_1[i*BIT_SIZE + k] = aes_share_conv_bit_shares_p0_p2->randModPrime(); } } for(size_t i = (size/2); i < size; i++) { for(size_t k=0; k<BIT_SIZE; k++) { bit_shares_x_2[i*BIT_SIZE + k] = aes_share_conv_bit_shares_p1_p2->randModPrime(); } } #endif for(size_t i = 0; i < (size/2); i++) { for(size_t k=0; k<BIT_SIZE; k++) { bit_shares_x_2[i*BIT_SIZE + k] = subtractModPrime((x[i] >> (BIT_SIZE - 1 - k) & 1), bit_shares_x_1[i*BIT_SIZE + k]); } } for(size_t i = (size/2); i < size; i++) { for(size_t k=0; k<BIT_SIZE; k++) { bit_shares_x_1[i*BIT_SIZE + k] = subtractModPrime((x[i] >> (BIT_SIZE - 1 - k) & 1), bit_shares_x_2[i*BIT_SIZE + k]); } } } } //Returns boolean shares of LSB of r. void sharesOfLSB(vector<smallType> &share_1, vector<smallType> &share_2, const vector<porthosSecretType> &r, size_t size, string r_type) { #ifdef DEBUG assert((r_type == "COMMON" or r_type == "INDEP") && "invalid randomness type for sharesOfLSB"); assert(partyNum == PARTY_C); #endif if (r_type == "COMMON") { for (size_t i = 0; i < size; ++i) { share_1[i] = aes_common->getBit(); share_2[i] = share_1[i] ^ (r[i] % 2); } } else if (r_type == "INDEP") { for (size_t i = 0; i < size; ++i) { share_1[i] = aes_indep->getBit(); share_2[i] = share_1[i] ^ (r[i] % 2); } } } //Returns \Z_L shares of LSB of r. void sharesOfLSB(vector<porthosSecretType> &share_1, vector<porthosSecretType> &share_2, const vector<porthosSecretType> &r, size_t size, string r_type) { #ifdef DEBUG assert((r_type == "PRG_COMM_OPTI" || (r_type == "COMMON" or r_type == "INDEP")) && "invalid randomness type for sharesOfLSB"); assert(partyNum == PARTY_C); #endif if (r_type == "COMMON") { #ifdef PRECOMPUTEAES aes_common->fillWithRandomBits64(share_1.data(), size); for (size_t i = 0; i < size; ++i) { share_2[i] = floatToMyType(r[i] % 2) - share_1[i]; } #else for (size_t i = 0; i < size; ++i) { share_1[i] = aes_common->get64Bits(); } for (size_t i = 0; i < size; ++i) { share_2[i] = floatToMyType(r[i] % 2) - share_1[i]; } #endif } else if (r_type == "INDEP") { #ifdef PRECOMPUTEAES aes_indep->fillWithRandomBits64(share_1.data(), size); for (size_t i = 0; i < size; ++i) { share_2[i] = floatToMyType(r[i] % 2) - share_1[i]; } #else for (size_t i = 0; i < size; ++i) { share_1[i] = aes_indep->get64Bits(); } for (size_t i = 0; i < size; ++i) { share_2[i] = floatToMyType(r[i] % 2) - share_1[i]; } #endif } else if(r_type == "PRG_COMM_OPTI"){ #ifdef PRECOMPUTEAES aes_comp_msb_shares_lsb_p0_p2->fillWithRandomBits64(share_1.data(), (size/2)); aes_comp_msb_shares_lsb_p1_p2->fillWithRandomBits64(share_2.data() + (size/2), (size-(size/2))); #else for (size_t i = 0; i < (size/2); ++i) { share_1[i] = aes_comp_msb_shares_lsb_p0_p2->get64Bits(); } for (size_t i = (size/2); i < size; ++i) { share_2[i] = aes_comp_msb_shares_lsb_p1_p2->get64Bits(); } #endif for (size_t i = 0; i < (size/2); ++i) { share_2[i] = floatToMyType(r[i] % 2) - share_1[i]; } for (size_t i = (size/2); i < size; ++i) { share_1[i] = floatToMyType(r[i] % 2) - share_2[i]; } } } //Returns boolean shares of a bit vector vec. void sharesOfBitVector(vector<smallType> &share_1, vector<smallType> &share_2, const vector<smallType> &vec, size_t size, string r_type) { assert((r_type == "COMMON" or r_type == "INDEP") && "invalid randomness type for sharesOfLSB"); if (r_type == "COMMON") { for (size_t i = 0; i < size; ++i) { share_1[i] = aes_common->getBit(); share_2[i] = share_1[i] ^ vec[i]; } } if (r_type == "INDEP") { for (size_t i = 0; i < size; ++i) { share_1[i] = aes_indep->getBit(); share_2[i] = share_1[i] ^ vec[i]; } } } //Returns \Z_L shares of a bit vector vec. void sharesOfBitVector(vector<porthosSecretType> &share_1, vector<porthosSecretType> &share_2, const vector<smallType> &vec, size_t size, string r_type) { #ifdef DEBUG assert((r_type == "PRG_COMM_OPTI" ||(r_type == "COMMON" or r_type == "INDEP")) && "invalid randomness type for sharesOfLSB"); assert(partyNum == PARTY_C); #endif if (r_type == "COMMON") { #ifdef PRECOMPUTEAES aes_common->fillWithRandomBits64(share_1.data(), size); for (size_t i = 0; i < size; ++i) { share_2[i] = floatToMyType(vec[i]) - share_1[i]; } #else for (size_t i = 0; i < size; ++i) { share_1[i] = aes_common->get64Bits(); } for (size_t i = 0; i < size; ++i) { share_2[i] = floatToMyType(vec[i]) - share_1[i]; } #endif } else if (r_type == "INDEP") { #ifdef PRECOMPUTEAES aes_indep->fillWithRandomBits64(share_1.data(), size); for (size_t i = 0; i < size; ++i) { share_2[i] = floatToMyType(vec[i]) - share_1[i]; } #else for (size_t i = 0; i < size; ++i) { share_1[i] = aes_indep->get64Bits(); } for (size_t i = 0; i < size; ++i) { share_2[i] = floatToMyType(vec[i]) - share_1[i]; } #endif } else if(r_type == "PRG_COMM_OPTI"){ #ifdef PRECOMPUTEAES aes_comp_msb_shares_bit_vec_p0_p2->fillWithRandomBits64(share_1.data(), (size/2)); aes_comp_msb_shares_bit_vec_p1_p2->fillWithRandomBits64(share_2.data() + (size/2), (size-(size/2))); #else for (size_t i = 0; i < (size/2); ++i) { share_1[i] = aes_comp_msb_shares_bit_vec_p0_p2->get64Bits(); } for (size_t i = (size/2); i < size; ++i) { share_2[i] = aes_comp_msb_shares_bit_vec_p1_p2->get64Bits(); } #endif for (size_t i = 0; i < (size/2); ++i) { share_2[i] = floatToMyType(vec[i]) - share_1[i]; } for (size_t i = (size/2); i < size; ++i) { share_1[i] = floatToMyType(vec[i]) - share_2[i]; } } } //Split shares of a vector of porthosSecretType into shares (randomness is independent) void splitIntoShares(const vector<porthosSecretType> &a, vector<porthosSecretType> &a1, vector<porthosSecretType> &a2, size_t size) { populateRandomVector<porthosSecretType>(a1, size, "INDEP", "POSITIVE"); subtractVectors<porthosSecretType>(a, a1, a2, size); } /***************************** Basic utility functions for Convolution drivers ************************/ void zero_4D_vector(vector< vector< vector< vector<porthosSecretType> > > >& vec, int d1, int d2, int d3, int d4) { for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ for(int k=0; k<d3; k++){ for(int l=0; l<d4; l++){ vec[i][j][k][l] = 0; } } } } } void subtract_2D_vectors(const vector< vector<porthosSecretType> >& inp_l, const vector< vector<porthosSecretType> >& inp_r, vector< vector<porthosSecretType> >& out, int d1, int d2) { for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ out[i][j] = inp_l[i][j] - inp_r[i][j]; } } } void add_2D_vectors(const vector< vector<porthosSecretType> >& inp_l, const vector< vector<porthosSecretType> >& inp_r, vector< vector<porthosSecretType> >& out, int d1, int d2) { for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ out[i][j] = inp_l[i][j] + inp_r[i][j]; } } } void zero_2D_vector(vector< vector<porthosSecretType> >& vec, int d1, int d2) { for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ vec[i][j] = 0; } } } void add_4D_vectors(vector< vector< vector< vector<porthosSecretType> > > >& inp_l, vector< vector< vector< vector<porthosSecretType> > > >& inp_r, vector< vector< vector< vector<porthosSecretType> > > >& out, int d1, int d2, int d3, int d4) { for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ for(int k=0; k<d3; k++){ for(int l=0; l<d4; l++){ out[i][j][k][l] = inp_l[i][j][k][l] + inp_r[i][j][k][l]; } } } } } void add_5D_vectors(vector< vector< vector< vector< vector<porthosSecretType> > > > >& inp_l, vector< vector< vector< vector< vector<porthosSecretType> > > > >& inp_r, vector< vector< vector< vector< vector<porthosSecretType> > > > >& out, int d1, int d2, int d3, int d4, int d5) { for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ for(int k=0; k<d3; k++){ for(int l=0; l<d4; l++){ for(int m=0; m<d5; m++){ out[i][j][k][l][m] = inp_l[i][j][k][l][m] + inp_r[i][j][k][l][m]; } } } } } } void subtract_4D_vectors(vector< vector< vector< vector<porthosSecretType> > > >& inp_l, vector< vector< vector< vector<porthosSecretType> > > >& inp_r, vector< vector< vector< vector<porthosSecretType> > > >& out, int d1, int d2, int d3, int d4) { for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ for(int k=0; k<d3; k++){ for(int l=0; l<d4; l++){ out[i][j][k][l] = inp_l[i][j][k][l] - inp_r[i][j][k][l]; } } } } } void subtract_5D_vectors(vector< vector< vector< vector< vector<porthosSecretType> > > > >& inp_l, vector< vector< vector< vector< vector<porthosSecretType> > > > >& inp_r, vector< vector< vector< vector< vector<porthosSecretType> > > > >& out, int d1, int d2, int d3, int d4, int d5) { for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ for(int k=0; k<d3; k++){ for(int l=0; l<d4; l++){ for(int m=0; m<d5; m++){ out[i][j][k][l][m] = inp_l[i][j][k][l][m] - inp_r[i][j][k][l][m]; } } } } } } void flatten_5D_vector(vector< vector< vector< vector< vector<porthosSecretType> > > > >& input, vector<porthosSecretType>& output, int d1, int d2, int d3, int d4, int d5) { for(int i=0;i<d1;i++){ for(int j=0;j<d2;j++){ for(int k=0;k<d3;k++){ for(int l=0;l<d4;l++){ for(int m=0;m<d5;m++){ output[i*d2*d3*d4*d5 + j*d3*d4*d5 + k*d4*d5 + l*d5 + m] = input[i][j][k][l][m]; } } } } } } void deflatten_5D_vector(vector<porthosSecretType>& input, vector< vector< vector< vector< vector<porthosSecretType> > > > >& output, int d1, int d2, int d3, int d4, int d5) { for(int i=0;i<d1;i++){ for(int j=0;j<d2;j++){ for(int k=0;k<d3;k++){ for(int l=0;l<d4;l++){ for(int m=0;m<d5;m++){ output[i][j][k][l][m] = input[i*d2*d3*d4*d5 + j*d3*d4*d5 + k*d4*d5 + l*d5 + m]; } } } } } } void flatten_4D_vector(vector< vector< vector< vector<porthosSecretType> > > >& input, vector<porthosSecretType>& output, int d1, int d2, int d3, int d4) { for(int i=0;i<d1;i++){ for(int j=0;j<d2;j++){ for(int k=0;k<d3;k++){ for(int l=0;l<d4;l++){ output[i*d2*d3*d4 + j*d3*d4 + k*d4 + l] = input[i][j][k][l]; } } } } } void deflatten_4D_vector(vector<porthosSecretType>& input, vector< vector< vector< vector<porthosSecretType> > > >& output, int d1, int d2, int d3, int d4) { for(int i=0;i<d1;i++){ for(int j=0;j<d2;j++){ for(int k=0;k<d3;k++){ for(int l=0;l<d4;l++){ output[i][j][k][l] = input[i*d2*d3*d4 + j*d3*d4 + k*d4 + l]; } } } } } void flatten_2D_vector(vector< vector<porthosSecretType> >& input, vector<porthosSecretType>& output, int d1, int d2) { for(int i=0;i<d1;i++){ for(int j=0;j<d2;j++){ output[i*d2 + j] = input[i][j]; } } } void deflatten_2D_vector(vector<porthosSecretType>& input, vector< vector<porthosSecretType> >& output, int d1, int d2) { for(int i=0;i<d1;i++){ for(int j=0;j<d2;j++){ output[i][j] = input[i*d2 + j]; } } } void send_5D_vector(vector< vector< vector< vector< vector<porthosSecretType> > > > >& input, int party, int d1, int d2, int d3, int d4, int d5) { vector<porthosSecretType> flat_input(d1*d2*d3*d4*d5, 0); //Flatten and send. flatten_5D_vector(input, flat_input, d1, d2, d3, d4, d5); sendVector<porthosSecretType>(ref(flat_input), party, d1*d2*d3*d4*d5); } void receive_5D_vector(vector< vector< vector< vector< vector<porthosSecretType> > > > >& recv, int party, int d1, int d2, int d3, int d4, int d5) { vector<porthosSecretType> flat_recv(d1*d2*d3*d4*d5, 0); //Receive and deflatten. receiveVector<porthosSecretType>(ref(flat_recv), party, d1*d2*d3*d4*d5); deflatten_5D_vector(flat_recv, recv, d1, d2, d3, d4, d5); } void send_4D_vector(vector< vector< vector< vector<porthosSecretType> > > >& input, int d1, int d2, int d3, int d4) { vector<porthosSecretType> flat_input(d1*d2*d3*d4, 0); //Flatten and send. flatten_4D_vector(input, flat_input, d1, d2, d3, d4); sendVector<porthosSecretType>(ref(flat_input), adversary(partyNum), d1*d2*d3*d4); } void receive_4D_vector(vector< vector< vector< vector<porthosSecretType> > > >& recv, int d1, int d2, int d3, int d4) { vector<porthosSecretType> flat_recv(d1*d2*d3*d4, 0); //Receive and deflatten. receiveVector<porthosSecretType>(ref(flat_recv), adversary(partyNum), d1*d2*d3*d4); deflatten_4D_vector(flat_recv, recv, d1, d2, d3, d4); } void send_2_4D_vector(vector< vector< vector< vector<porthosSecretType> > > >& input1, vector< vector< vector< vector<porthosSecretType> > > >& input2, int d11, int d12, int d13, int d14, int d21, int d22, int d23, int d24) { int32_t len1 = d11*d12*d13*d14; int32_t len2 = d21*d22*d23*d24; vector<porthosSecretType> sendArr(len1 + len2, 0); for(int i=0;i<d11;i++){ for(int j=0;j<d12;j++){ for(int k=0;k<d13;k++){ for(int l=0;l<d14;l++){ sendArr[i*d12*d13*d14 + j*d13*d14 + k*d14 + l] = input1[i][j][k][l]; } } } } for(int i=0;i<d21;i++){ for(int j=0;j<d22;j++){ for(int k=0;k<d23;k++){ for(int l=0;l<d24;l++){ sendArr[len1 + i*d22*d23*d24 + j*d23*d24 + k*d24 + l] = input2[i][j][k][l]; } } } } sendVector<porthosSecretType>(ref(sendArr), adversary(partyNum), len1+len2); } void receive_2_4D_vector(vector< vector< vector< vector<porthosSecretType> > > >& input1, vector< vector< vector< vector<porthosSecretType> > > >& input2, int d11, int d12, int d13, int d14, int d21, int d22, int d23, int d24) { int32_t len1 = d11*d12*d13*d14; int32_t len2 = d21*d22*d23*d24; vector<porthosSecretType> rcvArr(len1 + len2, 0); receiveVector<porthosSecretType>(ref(rcvArr), adversary(partyNum), len1+len2); for(int i=0;i<d11;i++){ for(int j=0;j<d12;j++){ for(int k=0;k<d13;k++){ for(int l=0;l<d14;l++){ input1[i][j][k][l] = rcvArr[i*d12*d13*d14 + j*d13*d14 + k*d14 + l]; } } } } for(int i=0;i<d21;i++){ for(int j=0;j<d22;j++){ for(int k=0;k<d23;k++){ for(int l=0;l<d24;l++){ input2[i][j][k][l] = rcvArr[len1 + i*d22*d23*d24 + j*d23*d24 + k*d24 + l]; } } } } } void send_2D_vector(vector< vector<porthosSecretType> >& input, int d1, int d2) { vector<porthosSecretType> flat_input(d1*d2, 0); //Flatten and send. flatten_2D_vector(input, flat_input, d1, d2); sendVector<porthosSecretType>(ref(flat_input), PARTY_B, d1*d2); } void receive_2D_vector(vector< vector<porthosSecretType> >& recv, int d1, int d2) { vector<porthosSecretType> flat_recv(d1*d2, 0); //Receive and deflatten. receiveVector<porthosSecretType>(ref(flat_recv), PARTY_C, d1*d2); deflatten_2D_vector(flat_recv, recv, d1, d2); } void populate_4D_vector(vector< vector< vector< vector<porthosSecretType> > > >& vec, int d1, int d2, int d3, int d4, string type) { AESObject* aesObject; if(type == "a1") aesObject = aes_conv_opti_a_1; else if(type == "a2") aesObject = aes_conv_opti_a_2; else if(type == "b1") aesObject = aes_conv_opti_b_1; else if(type == "b2") aesObject = aes_conv_opti_b_2; else if(type == "c1") aesObject = aes_conv_opti_c_1; else assert(false); for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ for(int k=0; k<d3; k++){ for(int l=0; l<d4; l++){ vec[i][j][k][l] = aesObject->get64Bits(); } } } } } void populate_5D_vector(vector< vector< vector< vector< vector<porthosSecretType> > > > >& vec, int d1, int d2, int d3, int d4, int d5, string type) { AESObject* aesObject; if(type == "a1") aesObject = aes_conv_opti_a_1; else if(type == "a2") aesObject = aes_conv_opti_a_2; else if(type == "b1") aesObject = aes_conv_opti_b_1; else if(type == "b2") aesObject = aes_conv_opti_b_2; else if(type == "c1") aesObject = aes_conv_opti_c_1; else assert(false); for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ for(int k=0; k<d3; k++){ for(int l=0; l<d4; l++){ for(int m=0; m<d5; m++){ vec[i][j][k][l][m] = aesObject->get64Bits(); } } } } } } void populate_2D_vector(vector< vector<porthosSecretType> >& vec, int d1, int d2, string type) { AESObject* aesObject; if(type == "a1") aesObject = aes_conv_opti_a_1; else if(type == "a2") aesObject = aes_conv_opti_a_2; else if(type == "b1") aesObject = aes_conv_opti_b_1; else if(type == "b2") aesObject = aes_conv_opti_b_2; else if(type == "c1") aesObject = aes_conv_opti_c_1; else assert(false); for(int i=0; i<d1; i++){ for(int j=0; j<d2; j++){ vec[i][j] = aesObject->get64Bits(); } } } void populate_AES_Arr(porthosSecretType* arr, porthosLongUnsignedInt size, string type) { AESObject* aesObject; if(type == "a1") aesObject = aes_conv_opti_a_1; else if(type == "a2") aesObject = aes_conv_opti_a_2; else if(type == "b1") aesObject = aes_conv_opti_b_1; else if(type == "b2") aesObject = aes_conv_opti_b_2; else if(type == "c1") aesObject = aes_conv_opti_c_1; else assert(false); #ifdef PRECOMPUTEAES aesObject->fillWithRandomBits64(arr, size); #else for(porthosLongUnsignedInt i=0; i<size; i++){ arr[i] = aesObject->get64Bits(); } #endif } void add_2_Arr(porthosSecretType* arr1, porthosSecretType* arr2, porthosSecretType* arr, porthosLongUnsignedInt size) { for(porthosLongUnsignedInt i=0; i<size; i++){ arr[i] = arr1[i] + arr2[i]; } } void subtract_2_Arr(porthosSecretType* arr1, porthosSecretType* arr2, porthosSecretType* arr, porthosLongUnsignedInt size) { for(porthosLongUnsignedInt i=0; i<size; i++){ arr[i] = arr1[i] - arr2[i]; } } /********************************** Porthos info display functions *****************************/ void porthos_throw_error(int code) { switch(code){ case PARSE_ERROR: cout<<endl<<"*********************PORTHOS SYSTEM: ERROR DETECTED********************"<<endl; cout<<"Usage: ./Porthos.out <PARTY_NUMBER> <PATH_IP_ADDRESSES> [ < <ANY_INPUT> ]"<<endl<<"For bugs, contact at mayankrathee.japan@gmail.com or nishant.kr10@gmail.com"<<endl<<endl; break; default: cout<<endl<<"*********************PORTHOS SYSTEM: ERROR DETECTED********************"<<endl; }; } void show_porthos_mode() { bool all_opti, share_conv_opti, msb_opti, conv_opti, precompute_aes, parallelize_crit_opti; cout<<endl<<"**********************PORTHOS MODE**********************"<<endl<<">>> Running Porthos in the following mode: "<<endl; #ifndef PORTHOS_OPTIMIZATIONS cout<<"PORTHOS OPTIMIZATIONS OFF"<<endl<<endl; #else #ifdef RUN_SHARECONV_OPTI cout<<"SHARE CONVERT OPTIMIZATION ON"<<endl; #else cout<<"SHARE CONVERT OPTIMIZATION OFF"<<endl; #endif #ifdef RUN_MSB_OPTI cout<<"COMPUTE MSB OPTIMIZATION ON"<<endl; #else cout<<"COMPUTE MSB OPTIMIZATION OFF"<<endl; #endif #ifdef CONV_OPTI cout<<"CONVOLUTION OPTIMIZATION ON"<<endl; #else cout<<"CONVOLUTION OPTIMIZATION OFF"<<endl; #endif #ifdef PRECOMPUTEAES cout<<"PRECOMP. AES OPTIMIZATION ON"<<endl; #else cout<<"PRECOMP. AES OPTIMIZATION OFF"<<endl; #endif #ifdef PARALLIZE_CRITICAL cout<<"PRIVATE COMP. OPTIMIZATION ON"<<endl; #else cout<<"PRIVATE COMP. OPTIMIZATION OFF"<<endl; #endif #endif #ifdef DEBUG cout<<"PORTHOS DEBUG BUILD(ASSERTS) ON"<<endl; #else cout<<"PORTHOS DEBUG BUILD(ASSERTS) OFF"<<endl; #endif #ifdef USE_EIGEN cout<<"PORTHOS EIGEN MATMUL SUPPORT ON"<<endl; #else cout<<"PORTHOS EIGEN MATMUL SUPPORT OFF"<<endl; #endif if(sizeof(uint64_t) == sizeof(porthosSecretType)){ cout<<"Running Porthos in Z_2^64"<<endl; } else{ cout<<"Support for custom ring not available"<<endl; } cout<<endl; } /********************************** Some helper functions invoked only by test functions **************/ void print_linear(porthosSecretType var, string type) { if (type == "BITS") cout << bitset<64>(var) << " "; else if (type == "FLOAT") cout << (static_cast<porthosLongSignedInt>(var))/(float)(1 << FLOAT_PRECISION) << " "; else if (type == "SIGNED") cout << static_cast<porthosLongSignedInt>(var) << " "; else if (type == "UNSIGNED") cout << var << " "; } void maxPoolReshape(const vector<porthosSecretType> &vec, vector<porthosSecretType> &vecShaped, size_t ih, size_t iw, size_t D, size_t B, size_t fh, size_t fw, size_t sy, size_t sx) { assert(fw >= sx and fh >= sy && "Check implementation"); assert((iw - fw)%sx == 0 && "Check implementations for this unmet condition"); assert((ih - fh)%sy == 0 && "Check implementations for this unmet condition"); assert(vec.size() == vecShaped.size() && "Dimension issue with convolutionReshape"); size_t loc = 0, counter = 0; for (size_t i = 0; i < B; ++i) for (size_t j = 0; j < D; ++j) for (size_t k = 0; k < ih-fh+1; k += sy) for (size_t l = 0; l < iw-fw+1; l += sx) { loc = i*iw*ih*D + j*iw*ih + k*iw + l; for (size_t a = 0; a < fh; ++a) for (size_t b = 0; b < fw; ++b) vecShaped[counter++] = vec[loc + a*iw + b]; } }
24.945587
182
0.613173
[ "vector" ]
33554480e9fb1a2e2108d6e0479d1c38c6167275
1,684
cpp
C++
Level5/Level5/Section 3.5/Exercise 3.5.2/Shape.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
1
2021-09-12T08:15:57.000Z
2021-09-12T08:15:57.000Z
Level5/Level5/Section 3.5/Exercise 3.5.2/Shape.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
null
null
null
Level5/Level5/Section 3.5/Exercise 3.5.2/Shape.cpp
chunyuyuan/My-Solution-for-C-Programming-for-Financial-Engineering
478b414714edbea1ebdc2f565baad6f04f54bc70
[ "MIT" ]
null
null
null
/* * Level_5 Exercise 3.5.2: * Source file for Shape Class * * Same file as Level_5 Exercise 3.5.1 * * @file Shape.cpp * @author Chunyu Yuan * @version 1.1 02/14/2021 * */ #include "Shape.hpp" //header file for Shape Class #include "stdlib.h" // library for using rand() to get a random number #include <sstream> // library that provides templates and types that enable interoperation between stream buffers and string objects //Default constructor Shape::Shape() :m_id(rand()) //Colon syntax, assign a random number to id member, the random is in range between 0 and RAND_MAX { } //constructor with id argument Shape::Shape(int new_id) : m_id(new_id) //Colon syntax { } // copy constructor, copy the id member Shape::Shape(const Shape& shape) : m_id(shape.m_id) //Colon syntax { } //destructor Shape::~Shape() { std::cout << "Bye my shape...." << std::endl;//remind the status of using destructor } //receive the id member const int& Shape::ID() const { return m_id; } //return the id as string std::string Shape::ToString() const { std::stringstream m_id_str; // declares one stringstream objects m_id_str << m_id; //put id integer value to string buffer std::string str; // declare a string value str = "ID: " + m_id_str.str(); //get the id string from the string buffer and assign it to str return str; //return the id string } //assignment operator Shape& Shape::operator = (const Shape& source) { if (this == &source) //check if the address is the same return *this; //if same, return itself m_id = source.m_id; //copy the id member of source return *this; //return itself to end assignment }
23.388889
134
0.682898
[ "shape" ]
3356e1a2a21137cab6421192d7bfdaf6964814b9
24,588
hpp
C++
hpxml/hpx/runtime/threads/thread_data.hpp
STEllAR-GROUP/hpxML
cce6478c2fe28e9917a67bab12af5ae54a254786
[ "BSL-1.0" ]
3
2017-04-06T16:36:38.000Z
2018-05-19T11:28:54.000Z
hpxml/hpx/runtime/threads/thread_data.hpp
STEllAR-GROUP/hpxML
cce6478c2fe28e9917a67bab12af5ae54a254786
[ "BSL-1.0" ]
1
2018-08-13T17:42:55.000Z
2018-08-13T18:20:23.000Z
hpxml/hpx/runtime/threads/thread_data.hpp
STEllAR-GROUP/hpxML
cce6478c2fe28e9917a67bab12af5ae54a254786
[ "BSL-1.0" ]
2
2018-05-25T06:33:50.000Z
2019-02-25T20:09:13.000Z
// Copyright (c) 2007-2016 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach // Copyright (c) 2008-2009 Chirag Dekate, Anshul Tandon // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef HPX_RUNTIME_THREADS_THREAD_DATA_HPP #define HPX_RUNTIME_THREADS_THREAD_DATA_HPP #include <hpx/config.hpp> #include <hpx/runtime/get_locality_id.hpp> #include <hpx/runtime/naming_fwd.hpp> #include <hpx/runtime/threads/coroutines/coroutine.hpp> #include <hpx/runtime/threads/detail/combined_tagged_state.hpp> #include <hpx/runtime/threads/thread_data_fwd.hpp> #include <hpx/runtime/threads/thread_init_data.hpp> #include <hpx/throw_exception.hpp> #include <hpx/util/assert.hpp> #include <hpx/util/atomic_count.hpp> #include <hpx/util/backtrace.hpp> #include <hpx/util/function.hpp> #include <hpx/util/lockfree/freelist.hpp> #include <hpx/util/logging.hpp> #include <hpx/util/spinlock_pool.hpp> #include <hpx/util/thread_description.hpp> #include <boost/atomic.hpp> #include <boost/intrusive_ptr.hpp> #include <cstddef> #include <cstdint> #include <stack> #include <string> #include <utility> #include <hpx/config/warnings_prefix.hpp> /////////////////////////////////////////////////////////////////////////////// namespace hpx { namespace threads { class thread_data; namespace detail { /////////////////////////////////////////////////////////////////////// struct thread_exit_callback_node { util::function_nonser<void()> f_; thread_exit_callback_node* next_; thread_exit_callback_node(util::function_nonser<void()> const& f, thread_exit_callback_node* next) : f_(f), next_(next) {} void operator()() { f_(); } }; } /////////////////////////////////////////////////////////////////////////// /// A \a thread is the representation of a ParalleX thread. It's a first /// class object in ParalleX. In our implementation this is a user level /// thread running on top of one of the OS threads spawned by the \a /// thread-manager. /// /// A \a thread encapsulates: /// - A thread status word (see the functions \a thread#get_state and /// \a thread#set_state) /// - A function to execute (the thread function) /// - A frame (in this implementation this is a block of memory used as /// the threads stack) /// - A block of registers (not implemented yet) /// /// Generally, \a threads are not created or executed directly. All /// functionality related to the management of \a thread's is /// implemented by the thread-manager. class thread_data { HPX_MOVABLE_ONLY(thread_data); // Avoid warning about using 'this' in initializer list thread_data* this_() { return this; } public: typedef thread_function_type function_type; struct tag {}; typedef util::spinlock_pool<tag> mutex_type; typedef boost::lockfree::caching_freelist<thread_data> pool_type; static boost::intrusive_ptr<thread_data> create( thread_init_data& init_data, pool_type& pool, thread_state_enum newstate) { thread_data* ret = pool.allocate(); if (ret == nullptr) { HPX_THROW_EXCEPTION(out_of_memory, "thread_data::operator new", "could not allocate memory for thread_data"); } #ifdef HPX_DEBUG_THREAD_POOL using namespace std; // some systems have memset in namespace std memset (ret, initial_value, sizeof(thread_data)); #endif return new (ret) thread_data(init_data, &pool, newstate); } ~thread_data() { free_thread_exit_callbacks(); LTM_(debug) << "~thread(" << this << "), description(" //-V128 << get_description() << "), phase(" << get_thread_phase() << ")"; } /// The get_state function queries the state of this thread instance. /// /// \returns This function returns the current state of this /// thread. It will return one of the values as defined /// by the \a thread_state enumeration. /// /// \note This function will be seldom used directly. Most of /// the time the state of a thread will be retrieved /// by using the function \a threadmanager#get_state. thread_state get_state() const { return current_state_.load(boost::memory_order_acquire); } /// The set_state function changes the state of this thread instance. /// /// \param newstate [in] The new state to be set for the thread. /// /// \note This function will be seldomly used directly. Most of /// the time the state of a thread will have to be /// changed using the threadmanager. Moreover, /// changing the thread state using this function does /// not change its scheduling status. It only sets the /// thread's status word. To change the thread's /// scheduling status \a threadmanager#set_state should /// be used. thread_state set_state(thread_state_enum state, thread_state_ex_enum state_ex = wait_unknown) { thread_state prev_state = current_state_.load(boost::memory_order_acquire); for (;;) { thread_state tmp = prev_state; // ABA prevention for state only (not for state_ex) std::int64_t tag = tmp.tag(); if (state != tmp.state()) ++tag; if (state_ex == wait_unknown) state_ex = tmp.state_ex(); if (HPX_LIKELY(current_state_.compare_exchange_strong(tmp, thread_state(state, state_ex, tag)))) { return prev_state; } prev_state = tmp; } } bool set_state_tagged(thread_state_enum newstate, thread_state& prev_state, thread_state& new_tagged_state) { thread_state tmp = prev_state; thread_state_ex_enum state_ex = tmp.state_ex(); new_tagged_state = thread_state(newstate, state_ex, prev_state.tag() + 1); if (!current_state_.compare_exchange_strong(tmp, new_tagged_state)) return false; prev_state = tmp; return true; } /// The restore_state function changes the state of this thread /// instance depending on its current state. It will change the state /// atomically only if the current state is still the same as passed /// as the second parameter. Otherwise it won't touch the thread state /// of this instance. /// /// \param newstate [in] The new state to be set for the thread. /// \param oldstate [in] The old state of the thread which still has to /// be the current state. /// /// \note This function will be seldomly used directly. Most of /// the time the state of a thread will have to be /// changed using the threadmanager. Moreover, /// changing the thread state using this function does /// not change its scheduling status. It only sets the /// thread's status word. To change the thread's /// scheduling status \a threadmanager#set_state should /// be used. /// /// \returns This function returns \a true if the state has been /// changed successfully bool restore_state(thread_state new_state, thread_state old_state) { // ABA prevention for state only (not for state_ex) std::int64_t tag = old_state.tag(); if (new_state.state() != old_state.state()) ++tag; // ignore the state_ex while compare-exchanging thread_state_ex_enum state_ex = current_state_.load(boost::memory_order_relaxed).state_ex(); thread_state old_tmp(old_state.state(), state_ex, old_state.tag()); thread_state new_tmp(new_state.state(), state_ex, tag); return current_state_.compare_exchange_strong(old_tmp, new_tmp); } bool restore_state(thread_state_enum new_state, thread_state_ex_enum state_ex, thread_state old_state) { // ABA prevention for state only (not for state_ex) std::int64_t tag = old_state.tag(); if (new_state != old_state.state()) ++tag; return current_state_.compare_exchange_strong(old_state, thread_state(new_state, state_ex, tag)); } private: /// The set_state function changes the extended state of this /// thread instance. /// /// \param newstate [in] The new extended state to be set for the /// thread. /// /// \note This function will be seldom used directly. Most of /// the time the state of a thread will have to be /// changed using the threadmanager. thread_state_ex_enum set_state_ex(thread_state_ex_enum new_state) { thread_state prev_state = current_state_.load(boost::memory_order_acquire); for (;;) { thread_state tmp = prev_state; if (HPX_LIKELY(current_state_.compare_exchange_strong(tmp, thread_state(tmp.state(), new_state, tmp.tag())))) { return prev_state.state_ex(); } prev_state = tmp; } } public: /// Return the id of the component this thread is running in naming::address_type get_component_id() const { #ifndef HPX_HAVE_THREAD_TARGET_ADDRESS return 0; #else return component_id_; #endif } #ifndef HPX_HAVE_THREAD_DESCRIPTION util::thread_description get_description() const { return util::thread_description("<unknown>"); } util::thread_description set_description(util::thread_description /*value*/) { return util::thread_description("<unknown>"); } util::thread_description get_lco_description() const { return util::thread_description("<unknown>"); } util::thread_description set_lco_description(util::thread_description /*value*/) { return util::thread_description("<unknown>"); } #else util::thread_description get_description() const { mutex_type::scoped_lock l(this); return description_; } util::thread_description set_description(util::thread_description value) { mutex_type::scoped_lock l(this); std::swap(description_, value); return value; } util::thread_description get_lco_description() const { mutex_type::scoped_lock l(this); return lco_description_; } util::thread_description set_lco_description( util::thread_description value) { mutex_type::scoped_lock l(this); std::swap(lco_description_, value); return value; } #endif #ifndef HPX_HAVE_THREAD_PARENT_REFERENCE /// Return the locality of the parent thread std::uint32_t get_parent_locality_id() const { return naming::invalid_locality_id; } /// Return the thread id of the parent thread thread_id_repr_type get_parent_thread_id() const { return threads::invalid_thread_id_repr; } /// Return the phase of the parent thread std::size_t get_parent_thread_phase() const { return 0; } #else /// Return the locality of the parent thread std::uint32_t get_parent_locality_id() const { return parent_locality_id_; } /// Return the thread id of the parent thread thread_id_repr_type get_parent_thread_id() const { return parent_thread_id_; } /// Return the phase of the parent thread std::size_t get_parent_thread_phase() const { return parent_thread_phase_; } #endif #ifdef HPX_HAVE_THREAD_MINIMAL_DEADLOCK_DETECTION void set_marked_state(thread_state_enum mark) const { marked_state_ = mark; } thread_state_enum get_marked_state() const { return marked_state_; } #endif #ifndef HPX_HAVE_THREAD_BACKTRACE_ON_SUSPENSION # ifdef HPX_HAVE_THREAD_FULLBACKTRACE_ON_SUSPENSION char const* get_backtrace() const { return nullptr; } char const* set_backtrace(char const*) { return nullptr; } # else util::backtrace const* get_backtrace() const { return nullptr; } util::backtrace const* set_backtrace(util::backtrace const*) { return nullptr; } # endif #else // defined(HPX_HAVE_THREAD_BACKTRACE_ON_SUSPENSION # ifdef HPX_HAVE_THREAD_FULLBACKTRACE_ON_SUSPENSION char const* get_backtrace() const { mutex_type::scoped_lock l(this); return backtrace_; } char const* set_backtrace(char const* value) { mutex_type::scoped_lock l(this); char const* bt = backtrace_; backtrace_ = value; return bt; } # else util::backtrace const* get_backtrace() const { mutex_type::scoped_lock l(this); return backtrace_; } util::backtrace const* set_backtrace(util::backtrace const* value) { mutex_type::scoped_lock l(this); util::backtrace const* bt = backtrace_; backtrace_ = value; return bt; } # endif // Generate full backtrace for captured stack std::string backtrace() { mutex_type::scoped_lock l(this); std::string bt; if (0 != backtrace_) { # ifdef HPX_HAVE_THREAD_FULLBACKTRACE_ON_SUSPENSION bt = *backtrace_; #else bt = backtrace_->trace(); #endif } return bt; } #endif thread_priority get_priority() const { return priority_; } void set_priority(thread_priority priority) { priority_ = priority; } // handle thread interruption bool interruption_requested() const { mutex_type::scoped_lock l(this); return requested_interrupt_; } bool interruption_enabled() const { mutex_type::scoped_lock l(this); return enabled_interrupt_; } bool set_interruption_enabled(bool enable) { mutex_type::scoped_lock l(this); std::swap(enabled_interrupt_, enable); return enable; } void interrupt(bool flag = true) { mutex_type::scoped_lock l(this); if (flag && !enabled_interrupt_) { l.unlock(); HPX_THROW_EXCEPTION(thread_not_interruptable, "thread_data::interrupt", "interrupts are disabled for this thread"); return; } requested_interrupt_ = flag; } bool interruption_point(bool throw_on_interrupt = true); bool add_thread_exit_callback(util::function_nonser<void()> const& f); void run_thread_exit_callbacks(); void free_thread_exit_callbacks(); policies::scheduler_base* get_scheduler_base() const { return scheduler_base_; } std::ptrdiff_t get_stack_size() const { return stacksize_; } pool_type* get_pool() { return pool_; } /// \brief Execute the thread function /// /// \returns This function returns the thread state the thread /// should be scheduled from this point on. The thread /// manager will use the returned value to set the /// thread's scheduling status. coroutine_type::result_type operator()() { HPX_ASSERT(this == coroutine_.get_thread_id()); return coroutine_(set_state_ex(wait_signaled)); } thread_id_type get_thread_id() const { HPX_ASSERT(this == coroutine_.get_thread_id()); return thread_id_type( reinterpret_cast<thread_data*>(coroutine_.get_thread_id()) ); } std::size_t get_thread_phase() const { #ifndef HPX_HAVE_THREAD_PHASE_INFORMATION return 0; #else return coroutine_.get_thread_phase(); #endif } std::size_t get_thread_data() const { return coroutine_.get_thread_data(); } std::size_t set_thread_data(std::size_t data) { return coroutine_.set_thread_data(data); } void rebind(thread_init_data& init_data, thread_state_enum newstate) { LTM_(debug) << "~thread(" << this << "), description(" //-V128 << get_description() << "), phase(" << get_thread_phase() << "), rebind"; rebind_base(init_data, newstate); coroutine_.rebind(std::move(init_data.func), this_()); HPX_ASSERT(init_data.stacksize != 0); HPX_ASSERT(coroutine_.is_ready()); } /// This function will be called when the thread is about to be deleted //virtual void reset() {} friend HPX_EXPORT void intrusive_ptr_add_ref(thread_data* p); friend HPX_EXPORT void intrusive_ptr_release(thread_data* p); /// Construct a new \a thread thread_data(thread_init_data& init_data, pool_type* pool, thread_state_enum newstate) : current_state_(thread_state(newstate, wait_signaled)), #ifdef HPX_HAVE_THREAD_TARGET_ADDRESS component_id_(init_data.lva), #endif #ifdef HPX_HAVE_THREAD_DESCRIPTION description_(init_data.description), lco_description_(), #endif #ifdef HPX_HAVE_THREAD_PARENT_REFERENCE parent_locality_id_(init_data.parent_locality_id), parent_thread_id_(init_data.parent_id), parent_thread_phase_(init_data.parent_phase), #endif #ifdef HPX_HAVE_THREAD_MINIMAL_DEADLOCK_DETECTION marked_state_(unknown), #endif #ifdef HPX_HAVE_THREAD_BACKTRACE_ON_SUSPENSION backtrace_(nullptr), #endif priority_(init_data.priority), requested_interrupt_(false), enabled_interrupt_(true), ran_exit_funcs_(false), scheduler_base_(init_data.scheduler_base), count_(0), stacksize_(init_data.stacksize), coroutine_(std::move(init_data.func), this_(), init_data.stacksize), pool_(pool) { LTM_(debug) << "thread::thread(" << this << "), description(" << get_description() << ")"; #ifdef HPX_HAVE_THREAD_PARENT_REFERENCE // store the thread id of the parent thread, mainly for debugging // purposes if (nullptr == parent_thread_id_) { thread_self* self = get_self_ptr(); if (self) { parent_thread_id_ = threads::get_self_id().get(); parent_thread_phase_ = self->get_thread_phase(); } } if (0 == parent_locality_id_) parent_locality_id_ = get_locality_id(); #endif HPX_ASSERT(init_data.stacksize != 0); HPX_ASSERT(coroutine_.is_ready()); } private: void rebind_base(thread_init_data& init_data, thread_state_enum newstate) { free_thread_exit_callbacks(); current_state_.store(thread_state(newstate, wait_signaled)); #ifdef HPX_HAVE_THREAD_TARGET_ADDRESS component_id_ = init_data.lva; #endif #ifdef HPX_HAVE_THREAD_DESCRIPTION description_ = (init_data.description); lco_description_ = util::thread_description(); #endif #ifdef HPX_HAVE_THREAD_PARENT_REFERENCE parent_locality_id_ = init_data.parent_locality_id; parent_thread_id_ = init_data.parent_id; parent_thread_phase_ = init_data.parent_phase; #endif #ifdef HPX_HAVE_THREAD_MINIMAL_DEADLOCK_DETECTION set_marked_state(unknown); #endif #ifdef HPX_HAVE_THREAD_BACKTRACE_ON_SUSPENSION backtrace_ = nullptr; #endif priority_ = init_data.priority; requested_interrupt_ = false; enabled_interrupt_ = true; ran_exit_funcs_ = false; exit_funcs_.clear(); scheduler_base_ = init_data.scheduler_base; HPX_ASSERT(init_data.stacksize == get_stack_size()); LTM_(debug) << "thread::thread(" << this << "), description(" << get_description() << "), rebind"; #ifdef HPX_HAVE_THREAD_PARENT_REFERENCE // store the thread id of the parent thread, mainly for debugging // purposes if (nullptr == parent_thread_id_) { thread_self* self = get_self_ptr(); if (self) { parent_thread_id_ = threads::get_self_id().get(); parent_thread_phase_ = self->get_thread_phase(); } } if (0 == parent_locality_id_) parent_locality_id_ = get_locality_id(); #endif } mutable boost::atomic<thread_state> current_state_; /////////////////////////////////////////////////////////////////////// // Debugging/logging information #ifdef HPX_HAVE_THREAD_TARGET_ADDRESS naming::address_type component_id_; #endif #ifdef HPX_HAVE_THREAD_DESCRIPTION util::thread_description description_; util::thread_description lco_description_; #endif #ifdef HPX_HAVE_THREAD_PARENT_REFERENCE std::uint32_t parent_locality_id_; thread_id_repr_type parent_thread_id_; std::size_t parent_thread_phase_; #endif #ifdef HPX_HAVE_THREAD_MINIMAL_DEADLOCK_DETECTION mutable thread_state_enum marked_state_; #endif #ifdef HPX_HAVE_THREAD_BACKTRACE_ON_SUSPENSION # ifdef HPX_HAVE_THREAD_FULLBACKTRACE_ON_SUSPENSION char const* backtrace_; # else util::backtrace const* backtrace_; # endif #endif /////////////////////////////////////////////////////////////////////// thread_priority priority_; bool requested_interrupt_; bool enabled_interrupt_; bool ran_exit_funcs_; // Singly linked list (heap-allocated) // FIXME: replace with forward_list eventually. std::deque<util::function_nonser<void()> > exit_funcs_; // reference to scheduler which created/manages this thread policies::scheduler_base* scheduler_base_; //reference count util::atomic_count count_; std::ptrdiff_t stacksize_; coroutine_type coroutine_; pool_type* pool_; }; typedef thread_data::pool_type thread_pool; }} #include <hpx/config/warnings_suffix.hpp> #endif /*HPX_RUNTIME_THREADS_THREAD_DATA_HPP*/
33.407609
88
0.578656
[ "object" ]
3359835e0faa0acf09a73b8d9cbf88c2e0dfb700
7,345
cpp
C++
plugin/AL_USDMayaTestPlugin/AL/usdmaya/nodes/proxy/test_DrivenTransforms.cpp
PaulDoessel/AL_USDMaya
912071b304748073299be08ba46a670390eee346
[ "Apache-2.0" ]
5
2017-12-04T16:56:32.000Z
2019-05-24T05:20:18.000Z
plugin/AL_USDMayaTestPlugin/AL/usdmaya/nodes/proxy/test_DrivenTransforms.cpp
PaulDoessel/AL_USDMaya
912071b304748073299be08ba46a670390eee346
[ "Apache-2.0" ]
null
null
null
plugin/AL_USDMayaTestPlugin/AL/usdmaya/nodes/proxy/test_DrivenTransforms.cpp
PaulDoessel/AL_USDMaya
912071b304748073299be08ba46a670390eee346
[ "Apache-2.0" ]
4
2018-03-17T15:55:28.000Z
2021-02-01T01:25:38.000Z
// // Copyright 2017 Animal Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License.// // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "test_usdmaya.h" #include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/Layer.h" #include "AL/usdmaya/nodes/proxy/PrimFilter.h" #include "AL/usdmaya/StageCache.h" #include "maya/MFnTransform.h" #include "maya/MSelectionList.h" #include "maya/MGlobal.h" #include "maya/MItDependencyNodes.h" #include "maya/MDagModifier.h" #include "maya/MFileIO.h" #include "maya/MStringArray.h" #include "pxr/usd/usd/stage.h" #include "pxr/usd/sdf/types.h" #include "pxr/usd/usd/attribute.h" #include "pxr/usd/usdGeom/xform.h" #include "pxr/usd/usdGeom/xformCommonAPI.h" #include <fstream> static const char* const g_drivenData = "#usda 1.0\n" "\n" "def XForm \"root\"\n" "{\n" " def XForm \"hip1\"\n" " {\n" " def XForm \"knee1\"\n" " {\n" " def XForm \"ankle1\"\n" " {\n" " def XForm \"ltoe1\"\n" " {\n" " }\n" " }\n" " }\n" " }\n" "}\n"; // DrivenTransforms(); // size_t transformCount() const; // void resizeDrivenTransforms(uint32_t index); // void constructDrivenPrimsArray(SdfPathVector& drivenPaths, std::vector<UsdPrim>& drivenPrims, UsdStageRefPtr stage); // void update(std::vector<UsdPrim>& drivenPrims, const MTime& currentTime); // void dirtyVisibility(int32_t primIndex, bool newValue); // void dirtyMatrix(int32_t primIndex, MMatrix newValue); // void setDrivenPrimPaths(const SdfPathVector& primPaths); // void visibilityReserve(uint32_t visibilityCount); // void matricesReserve(uint32_t matrixCount); // const SdfPathVector& drivenPrimPaths() const; // const std::vector<int32_t>& dirtyMatrices() const; // const std::vector<int32_t>& dirtyVisibilities() const; // const std::vector<MMatrix>& drivenMatrices() const; TEST(ProxyShape, DrivenTransforms) { AL::usdmaya::nodes::proxy::DrivenTransforms dt; // ensure constructor leaves arrays empty EXPECT_TRUE(dt.drivenPrimPaths().empty()); EXPECT_TRUE(dt.dirtyMatrices().empty()); EXPECT_TRUE(dt.dirtyVisibilities().empty()); EXPECT_TRUE(dt.drivenMatrices().empty()); EXPECT_EQ(0, dt.transformCount()); const std::string temp_path = "/tmp/AL_USDMayaTests_proxy_DrivenTransforms.usda"; std::string sessionLayerContents; // generate some data for the proxy shape { std::ofstream os(temp_path); os << g_drivenData; } MString shapeName; { MFnDagNode fn; MObject xform = fn.create("transform"); MObject shape = fn.create("AL_usdmaya_ProxyShape", xform); AL::usdmaya::nodes::ProxyShape* proxy = (AL::usdmaya::nodes::ProxyShape*)fn.userNode(); // force the stage to load proxy->filePathPlug().setString(temp_path.c_str()); auto stage = proxy->getUsdStage(); const SdfPathVector drivenPaths = { SdfPath("/root"), SdfPath("/root/hip1"), SdfPath("/root/hip1/knee1"), SdfPath("/root/hip1/knee1/ankle1"), SdfPath("/root/hip1/knee1/ankle1/ltoe1") }; // initialising the transforms should result in prim paths being allocated, dt.resizeDrivenTransforms(drivenPaths.size()); EXPECT_EQ(drivenPaths.size(), dt.drivenPrimPaths().size()); EXPECT_EQ(drivenPaths.size(), dt.drivenVisibilities().size()); EXPECT_EQ(drivenPaths.size(), dt.drivenMatrices().size()); for(size_t i = 0; i < drivenPaths.size(); ++i) { EXPECT_EQ(std::string(), dt.drivenPrimPaths()[i].GetString()); EXPECT_EQ(MMatrix::identity, dt.drivenMatrices()[i]); EXPECT_TRUE(dt.drivenVisibilities()[i]); } // ensure we can update the prim paths on the driven transforms object dt.setDrivenPrimPaths(drivenPaths); EXPECT_EQ(drivenPaths.size(), dt.drivenPrimPaths().size()); for(size_t i = 0; i < drivenPaths.size(); ++i) { EXPECT_EQ(drivenPaths[i].GetString(), dt.drivenPrimPaths()[i].GetString()); } // make sure nothing has happened to the dirty visibility array in the previous code EXPECT_TRUE(dt.dirtyVisibilities().empty()); // make sure that when we dirty visibility with index 3, that the correct dirty flags are set dt.dirtyVisibility(3, false); // we should now have an index is the visibility array EXPECT_EQ(1, dt.dirtyVisibilities().size()); EXPECT_EQ(3, dt.dirtyVisibilities()[0]); // the corresponding element in the visibilities should be set to false, the rest should remain true for(size_t i = 0; i < drivenPaths.size(); ++i) { if(i != 3) { EXPECT_TRUE(dt.drivenVisibilities()[i]); } else { EXPECT_FALSE(dt.drivenVisibilities()[i]); } } // test to make sure that a dirtyied visibility will correctly set a keyframe on the visibility attribute when updated. MTime time(10.0f, MTime::uiUnit()); dt.update(stage, time); for(size_t i = 0; i < drivenPaths.size(); ++i) { UsdGeomXform xform(stage->GetPrimAtPath(drivenPaths[i])); UsdAttribute attr = xform.GetVisibilityAttr(); if(i != 3) { EXPECT_FALSE(attr.HasValue()); } else { EXPECT_TRUE(attr.HasValue()); TfToken token; attr.Get(&token, 10.0f); EXPECT_TRUE(UsdGeomTokens->invisible == token); } } // after the visibilites have been updated, the dirtyVisibilities should have been cleared. EXPECT_EQ(0, dt.dirtyVisibilities().size()); // check to see that dirtyMatrix initialises the correct indices and transform values in the DrivenTransforms object MMatrix matrixValue = MMatrix::identity; matrixValue[3][0] = 3.0; dt.dirtyMatrix(2, matrixValue); // we should now have an index is the visibility array EXPECT_EQ(1, dt.dirtyMatrices().size()); EXPECT_EQ(2, dt.dirtyMatrices()[0]); for(size_t i = 0; i < drivenPaths.size(); ++i) { if(i != 2) { EXPECT_TRUE(dt.drivenMatrices()[i] == MMatrix::identity); } else { EXPECT_EQ(dt.drivenMatrices()[i], matrixValue); } } // test to make sure that updateDrivenVisibility adds a keyframe value in the visibility data for dt.update(stage, time); for(size_t i = 0; i < drivenPaths.size(); ++i) { UsdGeomXform xform(stage->GetPrimAtPath(drivenPaths[i])); bool resetsXformStack; std::vector<UsdGeomXformOp> ops = xform.GetOrderedXformOps(&resetsXformStack); if(i != 2) { EXPECT_TRUE(ops.empty()); } else { EXPECT_FALSE(ops.empty()); EXPECT_TRUE(ops[0].GetOpType() == UsdGeomXformOp::TypeTransform); MMatrix returnedMatrix; ops[0].Get((GfMatrix4d*)&returnedMatrix, 10.0); EXPECT_EQ(matrixValue, returnedMatrix); } } } }
32.074236
123
0.662355
[ "object", "shape", "vector", "transform" ]
335bb45afff4443a2c71e3e2fb9e341432049210
59,506
cpp
C++
mechanics/src/collision/bullet/SiconosBulletCollisionManager.cpp
michelanthony/CloneSiconosMaster
c1ba3525d21551fcb7226192be451cd6760dd4c0
[ "Apache-2.0" ]
null
null
null
mechanics/src/collision/bullet/SiconosBulletCollisionManager.cpp
michelanthony/CloneSiconosMaster
c1ba3525d21551fcb7226192be451cd6760dd4c0
[ "Apache-2.0" ]
null
null
null
mechanics/src/collision/bullet/SiconosBulletCollisionManager.cpp
michelanthony/CloneSiconosMaster
c1ba3525d21551fcb7226192be451cd6760dd4c0
[ "Apache-2.0" ]
null
null
null
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2016 INRIA. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file SiconosBulletCollisionManager.cpp \brief Definition of a Bullet-based interaction handler for contact detection. */ // Note, in general the "outside margin" is not implemented. What is // needed is a way to project the point detected on the external shell // back to the shape surface. This could be for example the closest // point on the convex hell. (For convex shapes.) #include <algorithm> #include <MechanicsFwd.hpp> #include <BulletSiconosFwd.hpp> #undef SICONOS_VISITABLES #define SICONOS_VISITABLES() \ KERNEL_CLASSES() \ MECHANICS_CLASSES() \ REGISTER(BodyShapeRecord) \ REGISTER(BodyBoxRecord) \ REGISTER(BodySphereRecord) \ REGISTER(BodyCHRecord) \ REGISTER(BodyPlaneRecord) \ REGISTER(BodyCylinderRecord) \ REGISTER(BodyMeshRecord) \ REGISTER(BodyHeightRecord) DEFINE_SPTR(UpdateShapeVisitor) #include "SiconosBulletCollisionManager.hpp" #include "BodyDS.hpp" #include "BulletR.hpp" #include "BulletFrom1DLocalFrameR.hpp" #include <map> #include <limits> #include <boost/format.hpp> #include <boost/make_shared.hpp> #include <CxxStd.hpp> #include <Relation.hpp> #include <Simulation.hpp> #include <NonSmoothDynamicalSystem.hpp> #include <SimulationTypeDef.hpp> #include <NonSmoothLaw.hpp> #include <OneStepIntegrator.hpp> #include <NewtonImpactFrictionNSL.hpp> #include <FrictionContact.hpp> #include <SiconosMatrix.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <NewtonEulerJointR.hpp> #include <Question.hpp> #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" #pragma clang diagnostic ignored "-Woverloaded-virtual" #elif !(__INTEL_COMPILER || __APPLE__ ) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverloaded-virtual" #endif #include <BulletCollision/CollisionDispatch/btCollisionWorld.h> #include <BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h> #include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h> #include <BulletCollision/BroadphaseCollision/btDbvtBroadphase.h> #include <BulletCollision/BroadphaseCollision/btAxisSweep3.h> #include <BulletCollision/CollisionShapes/btStaticPlaneShape.h> #include <BulletCollision/CollisionShapes/btSphereShape.h> #include <BulletCollision/CollisionShapes/btBoxShape.h> #include <BulletCollision/CollisionShapes/btCylinderShape.h> #include <BulletCollision/CollisionShapes/btConvexHullShape.h> #include <BulletCollision/CollisionShapes/btTriangleIndexVertexArray.h> #include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h> #include <LinearMath/btConvexHullComputer.h> #include <BulletCollision/Gimpact/btGImpactShape.h> #include <LinearMath/btQuaternion.h> #include <LinearMath/btVector3.h> #if defined(__clang__) #pragma clang diagnostic pop #elif !(__INTEL_COMPILER || __APPLE__ ) #pragma GCC diagnostic pop #endif //#define DEBUG_MESSAGES 1 #include <debug.h> // Comment this to try un-queued static contactor behaviour #define QUEUE_STATIC_CONTACTORS 1 // We can replace the primitives by alternative implementations. To date, // everything works (under test conditions, very tentative) except // btStaticPlaneShape, so we replace it with a large box. #define USE_CONVEXHULL_FOR_BOX 1 // #define USE_CONVEXHULL_FOR_SPHERE 1 // #define USE_BOX_FOR_PLANE 1 #define USE_CONVEXHULL_FOR_PLANE 1 // Bullet types (from USE flags above) #ifdef USE_CONVEXHULL_FOR_BOX #define BTBOXSHAPE btConvexHullShape #else #define BTBOXSHAPE btBoxShape #endif #define BTCYLSHAPE btCylinderShape #define BTCHSHAPE btConvexHullShape #ifdef USE_CONVEXHULL_FOR_SPHERE #define BTSPHERESHAPE btConvexHullShape #else #define BTSPHERESHAPE btSphereShape #endif #ifdef USE_BOX_FOR_PLANE #define BTPLANESHAPE btBoxShape #else #ifdef USE_CONVEXHULL_FOR_PLANE #define BTPLANESHAPE btConvexHullShape #else #define BTPLANESHAPE btStaticPlaneShape #endif #endif // We need a bit more space to hold mesh data class btSiconosMeshData : public btGImpactMeshShape { public: btSiconosMeshData(btStridingMeshInterface*i) : btGImpactMeshShape(i), btScalarVertices(0) {} ~btSiconosMeshData() { if (btScalarVertices) delete[] btScalarVertices; } btScalar* btScalarVertices; SP::btTriangleIndexVertexArray btTriData; }; #define BTMESHSHAPE btSiconosMeshData // Similarly, place to store height matrix class btSiconosHeightData : public btHeightfieldTerrainShape { public: btSiconosHeightData(int width, std11::shared_ptr< std::vector<btScalar> > data, btScalar min_height, btScalar max_height) : btHeightfieldTerrainShape(width, data->size()/width, data->data(), 0, // scale ignored for PHY_FLOAT min_height, max_height, 2, PHY_FLOAT, false), // up = z, flip = false _data(data), _min_height(min_height), _max_height(max_height) {} std11::shared_ptr< std::vector<btScalar> > _data; btScalar _min_height, _max_height; }; #define BTHEIGHTSHAPE btSiconosHeightData // Default Bullet options SiconosBulletOptions::SiconosBulletOptions() : contactBreakingThreshold(0.02) , contactProcessingThreshold(0.03) , worldScale(1.0) , useAxisSweep3(false) , clearOverlappingPairCache(false) , perturbationIterations(3) , minimumPointsPerturbationThreshold(3) , enableSatConvex(false) , enablePolyhedralContactClipping(false) { } // We need to maintain a record associating each body with a shape, // contactor, and collision object for each shape type. We also need // to access generic shape stuff (group, margin) by a pointer from the // collision callback, so we need a record base class. class BodyShapeRecord { public: BodyShapeRecord(SP::SiconosVector b, SP::BodyDS d, SP::SiconosShape sh, SP::btCollisionObject btobj, SP::SiconosContactor con) : base(b), ds(d), sshape(sh), btobject(btobj), contactor(con), shape_version(sh->version()) {} virtual ~BodyShapeRecord() {} SP::SiconosVector base; SP::BodyDS ds; SP::SiconosShape sshape; SP::btCollisionObject btobject; SP::SiconosContactor contactor; unsigned int shape_version; VIRTUAL_ACCEPT_VISITORS(); }; template <typename SICONOSSHAPE, typename BULLETSHAPE> class BodyShapeRecordT : BodyShapeRecord { public: BodyShapeRecordT(SP::SiconosVector base, SP::BodyDS ds, SICONOSSHAPE sh, BULLETSHAPE btsh, SP::btCollisionObject btobj, SP::SiconosContactor con) : BodyShapeRecord(base, ds, sh, btobj, con), shape(sh), btshape(btsh) {} SICONOSSHAPE shape; BULLETSHAPE btshape; }; #define SHAPE_RECORD(X,SICONOSSHAPE,BULLETSHAPE) \ class X : public BodyShapeRecord, \ public std11::enable_shared_from_this<X> { \ public: \ X(SP::SiconosVector base, SP::BodyDS ds, \ SICONOSSHAPE sh, BULLETSHAPE btsh, \ SP::btCollisionObject btobj, SP::SiconosContactor con) \ : BodyShapeRecord(base, ds, sh, btobj, con), shape(sh), btshape(btsh) {} \ SICONOSSHAPE shape; \ BULLETSHAPE btshape; \ ACCEPT_VISITORS(); \ }; // Body-Shape record types SHAPE_RECORD(BodyBoxRecord, SP::SiconosBox, SP::BTBOXSHAPE); SHAPE_RECORD(BodySphereRecord, SP::SiconosSphere, SP::BTSPHERESHAPE); SHAPE_RECORD(BodyCHRecord, SP::SiconosConvexHull, SP::BTCHSHAPE); SHAPE_RECORD(BodyPlaneRecord, SP::SiconosPlane, SP::BTPLANESHAPE); SHAPE_RECORD(BodyCylinderRecord, SP::SiconosCylinder, SP::BTCYLSHAPE); SHAPE_RECORD(BodyMeshRecord, SP::SiconosMesh, std11::shared_ptr<btSiconosMeshData>); SHAPE_RECORD(BodyHeightRecord, SP::SiconosHeightMap, std11::shared_ptr<btSiconosHeightData>); typedef std::map<const BodyDS*, std::vector<std11::shared_ptr<BodyShapeRecord> > > BodyShapeMap; /** For associating static contactor sets and their offsets. * Pointer to this is what is returned as the opaque and unique * StaticContactorSetID so that they can be removed. */ class StaticContactorSetRecord { public: SP::SiconosContactorSet contactorSet; SP::SiconosVector base; }; namespace SP { typedef std11::shared_ptr<StaticContactorSetRecord> StaticContactorSetRecord; }; class CollisionUpdater; class SiconosBulletCollisionManager_impl { protected: SP::btCollisionWorld _collisionWorld; SP::btDefaultCollisionConfiguration _collisionConfiguration; SP::btCollisionDispatcher _dispatcher; SP::btBroadphaseInterface _broadphase; /* Static contactor sets may be repeated with different positions, * thus each one is assocated with a list of base positions and * collision objects. */ std::map< StaticContactorSetRecord*, SP::StaticContactorSetRecord > _staticContactorSetRecords; /* During iteration over DSs for position updates we need to access * btCollisionObject, so need a map DS->btXShape. */ BodyShapeMap bodyShapeMap; SP::Simulation _simulation; /* Create collision objects for each shape type */ void createCollisionObject(const SP::SiconosVector base, const SP::BodyDS ds, const SP::SiconosPlane plane, const SP::SiconosContactor contactor); void createCollisionObject(const SP::SiconosVector base, const SP::BodyDS ds, const SP::SiconosSphere sphere, const SP::SiconosContactor contactor); void createCollisionObject(const SP::SiconosVector base, const SP::BodyDS ds, const SP::SiconosBox box, const SP::SiconosContactor contactor); void createCollisionObject(const SP::SiconosVector base, const SP::BodyDS ds, const SP::SiconosCylinder cyl, const SP::SiconosContactor contactor); void createCollisionObject(const SP::SiconosVector base, const SP::BodyDS ds, const SP::SiconosConvexHull ch, const SP::SiconosContactor contactor); void createCollisionObject(const SP::SiconosVector base, const SP::BodyDS ds, const SP::SiconosMesh mesh, const SP::SiconosContactor contactor); void createCollisionObject(const SP::SiconosVector base, const SP::BodyDS ds, const SP::SiconosHeightMap height, const SP::SiconosContactor contactor); /* Call the above functions for each shape associated with a body or contactor. */ void createCollisionObjectsForBodyContactorSet( const SP::BodyDS ds, const SP::SiconosVector base = SP::SiconosVector(), const SP::SiconosContactorSet contactor = SP::SiconosContactorSet()); /* A helper function used to initialise new shapes, generic to the * shape type */ template<typename ST, typename BT, typename BR> void createCollisionObjectHelper(SP::SiconosVector base, SP::BodyDS ds, ST& shape, BT& btshape, BodyShapeMap& bodyShapeMap, SP::SiconosContactor contactor); void updateShape(BodySphereRecord &record); void updateShape(BodyPlaneRecord &record); void updateShape(BodyBoxRecord &record); void updateShape(BodyCylinderRecord &record); void updateShape(BodyCHRecord &record); void updateShape(BodyMeshRecord &record); void updateShape(BodyHeightRecord &record); void updateAllShapesForDS(const BodyDS &bds); void updateShapePosition(const BodyShapeRecord &record); /* Helper to apply an offset transform to a position and return as a * btTransform */ btTransform offsetTransform(const SiconosVector& position, const SiconosVector& offset); /** Helper to set the inertia of a NewtonEulerDS based on a * btCollisionShape */ void updateContactorInertia(SP::NewtonEulerDS ds, SP::btCollisionShape btshape); SiconosBulletOptions &_options; std::vector<SP::btCollisionObject> _queuedCollisionObjects; public: SiconosBulletCollisionManager_impl(SiconosBulletOptions &op) : _options(op) {} ~SiconosBulletCollisionManager_impl() {} friend class SiconosBulletCollisionManager; friend class CollisionUpdateVisitor; friend class CreateCollisionObjectShapeVisitor; friend class UpdateShapeVisitor; }; SiconosCollisionManager::StaticContactorSetID SiconosBulletCollisionManager::insertStaticContactorSet( SP::SiconosContactorSet cs, SP::SiconosVector position) { SP::StaticContactorSetRecord rec(std11::make_shared<StaticContactorSetRecord>()); rec->contactorSet = cs; if (!position) { // Default at center position = std11::make_shared<SiconosVector>(7); position->zero(); (*position)(3) = 1.0; } rec->base = position; impl->createCollisionObjectsForBodyContactorSet(SP::BodyDS(), rec->base, cs); impl->_staticContactorSetRecords[&*rec] = rec; return static_cast<SiconosBulletCollisionManager::StaticContactorSetID>(&*rec); } bool SiconosBulletCollisionManager::removeStaticContactorSet(StaticContactorSetID id) { StaticContactorSetRecord *recptr = static_cast<StaticContactorSetRecord *>(id); if (impl->_staticContactorSetRecords.find(recptr) == impl->_staticContactorSetRecords.end()) return false; SP::StaticContactorSetRecord rec(impl->_staticContactorSetRecords[recptr]); // TODO assert(0 && "removeStaticContactorSet not implemented."); return false; } void SiconosBulletCollisionManager::initialize_impl() { impl.reset(new SiconosBulletCollisionManager_impl(_options)); impl->_collisionConfiguration.reset( new btDefaultCollisionConfiguration()); if (_options.perturbationIterations > 0 || _options.minimumPointsPerturbationThreshold > 0) { impl->_collisionConfiguration->setConvexConvexMultipointIterations( _options.perturbationIterations, _options.minimumPointsPerturbationThreshold); impl->_collisionConfiguration->setPlaneConvexMultipointIterations( _options.perturbationIterations, _options.minimumPointsPerturbationThreshold); } impl->_dispatcher.reset( new btCollisionDispatcher(&*impl->_collisionConfiguration)); if (_options.useAxisSweep3) impl->_broadphase.reset(new btAxisSweep3(btVector3(), btVector3())); else impl->_broadphase.reset(new btDbvtBroadphase()); impl->_collisionWorld.reset( new btCollisionWorld(&*impl->_dispatcher, &*impl->_broadphase, &*impl->_collisionConfiguration)); btGImpactCollisionAlgorithm::registerAlgorithm(&*impl->_dispatcher); impl->_collisionWorld->getDispatchInfo().m_useContinuous = false; impl->_collisionWorld->getDispatchInfo().m_enableSatConvex = _options.enableSatConvex; } SiconosBulletCollisionManager::SiconosBulletCollisionManager() : SiconosCollisionManager() { initialize_impl(); } SiconosBulletCollisionManager::SiconosBulletCollisionManager(const SiconosBulletOptions &options) : _options(options) { initialize_impl(); } SiconosBulletCollisionManager::~SiconosBulletCollisionManager() { // unlink() will be called on all remaining // contact points when world is destroyed // must be the first de-allocated, otherwise segfault impl->_collisionWorld.reset(); } class UpdateShapeVisitor : public SiconosVisitor { public: using SiconosVisitor::visit; SiconosBulletCollisionManager_impl &impl; UpdateShapeVisitor(SiconosBulletCollisionManager_impl &_impl) : impl(_impl) {} void visit(std11::shared_ptr<BodyPlaneRecord> record) { impl.updateShape(*record); } void visit(std11::shared_ptr<BodySphereRecord> record) { impl.updateShape(*record); } void visit(std11::shared_ptr<BodyBoxRecord> record) { impl.updateShape(*record); } void visit(std11::shared_ptr<BodyCylinderRecord> record) { impl.updateShape(*record); } void visit(std11::shared_ptr<BodyCHRecord> record) { impl.updateShape(*record); } void visit(std11::shared_ptr<BodyMeshRecord> record) { impl.updateShape(*record); } void visit(std11::shared_ptr<BodyHeightRecord> record) { impl.updateShape(*record); } }; void SiconosBulletCollisionManager_impl::updateAllShapesForDS(const BodyDS &bds) { SP::UpdateShapeVisitor updateShapeVisitor(new UpdateShapeVisitor(*this)); std::vector<std11::shared_ptr<BodyShapeRecord> >::iterator it; for (it = bodyShapeMap[&bds].begin(); it != bodyShapeMap[&bds].end(); it++) (*it)->acceptSP(updateShapeVisitor); } // helper for enabling polyhedral contact clipping for shape types // derived from btPolyhedralConvexShape static void initPolyhedralFeatures(btPolyhedralConvexShape& btshape) { btshape.initializePolyhedralFeatures(); } static void initPolyhedralFeatures(btCollisionShape& btshape) {} template<typename ST, typename BT, typename BR> void SiconosBulletCollisionManager_impl::createCollisionObjectHelper( SP::SiconosVector base, SP::BodyDS ds, ST& shape, BT& btshape, BodyShapeMap& bodyShapeMap, SP::SiconosContactor contactor) { assert(base && "Collision objects must have a base position."); // create corresponding Bullet object and shape SP::btCollisionObject btobject(new btCollisionObject()); // default parameters btobject->setContactProcessingThreshold(_options.contactProcessingThreshold); // associate the shape with the object btobject->setCollisionShape(&*btshape); // enable contact clipping for SAT if (_options.enablePolyhedralContactClipping) initPolyhedralFeatures(*btshape); if (!ds) btobject->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT); else btobject->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); // put it in the world #ifdef QUEUE_STATIC_CONTACTORS if (!ds) _queuedCollisionObjects.push_back(btobject); else _collisionWorld->addCollisionObject(&*btobject); #else _collisionWorld->addCollisionObject(&*btobject); #endif // create a record to keep track of things // (for static contactor, ds=nil) std11::shared_ptr<BR> record( std11::make_shared<BR>(base, ds, shape, btshape, btobject, contactor)); bodyShapeMap[ds ? &*ds : 0].push_back(record); assert(record->btobject); assert(record->sshape); assert(record->shape); assert(record->btshape); assert(record->contactor); assert(record->contactor->offset); assert(record->contactor->offset->size() == 7); // Allow Bullet to report colliding DSs. We need to access it from // the collision callback as the record base class so down-cast it. btobject->setUserPointer( reinterpret_cast<void*>( static_cast<BodyShapeRecord*>(&*record))); // initial parameter update (change version to make something happen) record->shape_version -= 1; updateShape(*record); } btTransform SiconosBulletCollisionManager_impl::offsetTransform(const SiconosVector& position, const SiconosVector& offset) { /* Adjust offset position according to current rotation */ btQuaternion rbase(position(4), position(5), position(6), position(3)); btVector3 rboffset = quatRotate(rbase, btVector3(offset(0), offset(1), offset(2))); /* Calculate total orientation */ btQuaternion roffset(offset(4), offset(5), offset(6), offset(3)); /* Set the absolute shape position */ return btTransform( rbase * roffset, btVector3(position(0), position(1), position(2)) + rboffset ); } void SiconosBulletCollisionManager_impl::updateShapePosition(const BodyShapeRecord &record) { SiconosVector q(7); if (record.base) q = *record.base; else { q.zero(); q(3) = 1; } DEBUG_PRINTF("updating shape position: %p(%ld) - %f, %f, %f\n", &*box,box.use_count(), q(0), q(1), q(2)); btTransform t = offsetTransform(q, *record.contactor->offset); t.setOrigin(t.getOrigin() * _options.worldScale); record.btobject->setWorldTransform( t ); } void SiconosBulletCollisionManager_impl::createCollisionObject( const SP::SiconosVector base, const SP::BodyDS ds, SP::SiconosSphere sphere, const SP::SiconosContactor contactor) { // set radius to 1.0 and use scaling instead of setting radius // directly, makes it easier to change during update #ifdef USE_CONVEXHULL_FOR_SPHERE // A sphere can be represented as a convex hull of a single point, with the // margin equal to the radius size SP::btConvexHullShape btsphere(new btConvexHullShape()); { btsphere->addPoint(btVector3(0.0, 0.0, 0.0)); btsphere->setMargin(0.0); } #else SP::btSphereShape btsphere(new btSphereShape(1.0)); btsphere->setMargin(0.0); #endif // initialization createCollisionObjectHelper<SP::SiconosSphere, SP::BTSPHERESHAPE, BodySphereRecord> (base, ds, sphere, btsphere, bodyShapeMap, contactor); } void SiconosBulletCollisionManager_impl::updateContactorInertia( SP::NewtonEulerDS ds, SP::btCollisionShape btshape) { btVector3 localinertia; btshape->calculateLocalInertia(ds->scalarMass(), localinertia); assert( ! ((localinertia.x() == 0.0 && localinertia.y() == 0.0 && localinertia.z() == 0.0) || isinf(localinertia.x()) || isinf(localinertia.y()) || isinf(localinertia.z())) && "calculateLocalInertia() returned garbage" ); ds->setInertia(localinertia[0], localinertia[1], localinertia[2]); } void SiconosBulletCollisionManager_impl::updateShape(BodySphereRecord &record) { SP::SiconosSphere sphere(record.shape); SP::BTSPHERESHAPE btsphere(record.btshape); if (sphere->version() != record.shape_version) { double r = (sphere->radius() + sphere->outsideMargin()) * _options.worldScale; // Update shape parameters #ifdef USE_CONVEXHULL_FOR_SPHERE btsphere->setMargin(r); #else btsphere->setLocalScaling(btVector3(r, r, r)); // btSphereShape has an internal margin btsphere->setMargin(sphere->insideMargin() * _options.worldScale); #endif if (record.ds && record.ds->useContactorInertia()) updateContactorInertia(record.ds, btsphere); if (record.btobject->getBroadphaseHandle()) { _collisionWorld->updateSingleAabb(&*record.btobject); _collisionWorld->getBroadphase()->getOverlappingPairCache()-> cleanProxyFromPairs(record.btobject->getBroadphaseHandle(), &*_dispatcher); } record.shape_version = sphere->version(); } updateShapePosition(record); } void SiconosBulletCollisionManager_impl::createCollisionObject( const SP::SiconosVector base, const SP::BodyDS ds, SP::SiconosPlane plane, SP::SiconosContactor contactor) { // create the initial plane with default parameters #ifdef USE_BOX_FOR_PLANE btScalar h = (1000 + plane->outsideMargin()) * _options.worldScale; SP::btBoxShape btplane(new btBoxShape(btVector3(h, h, h))); // Internal margin btplane->setMargin((plane->insideMargin() + plane->outsideMargin()) * _options.worldScale); #else #ifdef USE_CONVEXHULL_FOR_PLANE btScalar h = 1000 * _options.worldScale; const btScalar pts[] = { h, h, 0, h, -h, 0, -h, -h, 0, -h, h, 0, }; SP::btConvexHullShape btplane( new btConvexHullShape(pts, 4, sizeof(pts[0])*3)); // We ignore the desired internal margin for plane and just use a large one. plane->setInsideMargin(1000 * _options.worldScale); // External margin btplane->setMargin((plane->insideMargin() + plane->outsideMargin()) * _options.worldScale); #else SP::btStaticPlaneShape btplane( new btStaticPlaneShape(btVector3(0, 0, 1), 0.0)); btplane->setMargin(plane->outsideMargin() * _options.worldScale); #endif #endif // initialization createCollisionObjectHelper<SP::SiconosPlane, SP::BTPLANESHAPE, BodyPlaneRecord> (base, ds, plane, btplane, bodyShapeMap, contactor); } void SiconosBulletCollisionManager_impl::updateShape(BodyPlaneRecord& record) { SP::SiconosPlane plane(record.shape); SP::BTPLANESHAPE btplane(record.btshape); SiconosVector o(7); o = *record.contactor->offset; // Adjust the offset according to plane implementation #ifdef USE_BOX_FOR_PLANE o(2) -= -plane->outsideMargin() + 1000; #else #ifdef USE_CONVEXHULL_FOR_PLANE o(2) -= plane->insideMargin(); #else // USE_PLANE_FOR_PLANE o(2) -= plane->insideMargin(); #endif #endif // Note, we do not use generic updateShapePosition for plane btTransform t = offsetTransform(*record.base, o); t.setOrigin(t.getOrigin() * _options.worldScale); record.btobject->setWorldTransform( t ); } void SiconosBulletCollisionManager_impl::createCollisionObject( const SP::SiconosVector base, const SP::BodyDS ds, SP::SiconosBox box, SP::SiconosContactor contactor) { const btScalar half = 0.5; #ifdef USE_CONVEXHULL_FOR_BOX const btScalar pts[] = { -half, half, -half, -half, -half, -half, -half, -half, half, -half, half, half, half, half, half, half, half, -half, half, -half, -half, half, -half, half, }; SP::btConvexHullShape btbox( new btConvexHullShape(pts, 8, sizeof(pts[0])*3)); // External margin btbox->setMargin(box->outsideMargin()); #else SP::btBoxShape btbox(new btBoxShape(btVector3(half, half, half))); // btBoxShape has an internal margin btbox->setMargin(box->insideMargin() * _options.worldScale); #endif // initialization createCollisionObjectHelper<SP::SiconosBox, SP::BTBOXSHAPE, BodyBoxRecord> (base, ds, box, btbox, bodyShapeMap, contactor); } void SiconosBulletCollisionManager_impl::updateShape(BodyBoxRecord &record) { SP::SiconosBox box(record.shape); SP::BTBOXSHAPE btbox(record.btshape); // Update shape parameters if (box->version() != record.shape_version) { #ifdef USE_CONVEXHULL_FOR_BOX double m = -box->insideMargin(); #else double m = box->outsideMargin(); #endif double sx = ((*box->dimensions())(0) + m*2) * _options.worldScale; double sy = ((*box->dimensions())(1) + m*2) * _options.worldScale; double sz = ((*box->dimensions())(2) + m*2) * _options.worldScale; assert(sx > 0 && sy > 0 && sz > 0); btbox->setLocalScaling(btVector3(sx, sy, sz)); btbox->setMargin((box->insideMargin() + box->outsideMargin()) * _options.worldScale); if (record.ds && record.ds->useContactorInertia()) updateContactorInertia(record.ds, btbox); if (record.btobject->getBroadphaseHandle()) { _collisionWorld->updateSingleAabb(&*record.btobject); _collisionWorld->getBroadphase()->getOverlappingPairCache()-> cleanProxyFromPairs(record.btobject->getBroadphaseHandle(), &*_dispatcher); } record.shape_version = box->version(); } updateShapePosition(record); } void SiconosBulletCollisionManager_impl::createCollisionObject( const SP::SiconosVector base, const SP::BodyDS ds, SP::SiconosCylinder cylinder, SP::SiconosContactor contactor) { SP::BTCYLSHAPE btcylinder(new BTCYLSHAPE(btVector3(1.0, 1.0, 1.0))); // initialization createCollisionObjectHelper<SP::SiconosCylinder, SP::BTCYLSHAPE, BodyCylinderRecord> (base, ds, cylinder, btcylinder, bodyShapeMap, contactor); } void SiconosBulletCollisionManager_impl::updateShape(BodyCylinderRecord &record) { SP::SiconosCylinder cyl(record.shape); SP::BTCYLSHAPE btcyl(record.btshape); // Update shape parameters if (cyl->version() != record.shape_version) { // Bullet cylinder has an inside margin, so we add the outside // margin explicitly. double m = cyl->outsideMargin(); double radius = (cyl->radius() + m) * _options.worldScale; double length = (cyl->length()/2 + m) * _options.worldScale; assert(radius > 0 && length > 0); btcyl->setLocalScaling(btVector3(radius, length, radius)); btcyl->setMargin((cyl->insideMargin() + cyl->outsideMargin()) * _options.worldScale); if (record.ds && record.ds->useContactorInertia()) updateContactorInertia(record.ds, btcyl); if (record.btobject->getBroadphaseHandle()) { _collisionWorld->updateSingleAabb(&*record.btobject); _collisionWorld->getBroadphase()->getOverlappingPairCache()-> cleanProxyFromPairs(record.btobject->getBroadphaseHandle(), &*_dispatcher); } record.shape_version = cyl->version(); } updateShapePosition(record); } void SiconosBulletCollisionManager_impl::createCollisionObject( const SP::SiconosVector base, const SP::BodyDS ds, SP::SiconosConvexHull ch, SP::SiconosContactor contactor) { if (!ch->vertices()) throw SiconosException("No vertices matrix specified for convex hull."); if (ch->vertices()->size(1) != 3) throw SiconosException("Convex hull vertices matrix must have 3 columns."); // Copy and scale the points int rows = ch->vertices()->size(0); std::vector<btScalar> pts; pts.resize(rows*3); for (int r=0; r < rows; r++) { pts[r*3+0] = (*ch->vertices())(r, 0) * _options.worldScale; pts[r*3+1] = (*ch->vertices())(r, 1) * _options.worldScale; pts[r*3+2] = (*ch->vertices())(r, 2) * _options.worldScale; } SP::btConvexHullShape btch; if (ch->insideMargin() == 0) { // Create a convex hull directly with no further processing. // TODO: In case of worldScale=1, maybe we could avoid the copy to pts. btch.reset(new btConvexHullShape(&pts[0], rows, sizeof(btScalar)*3)); } else { // Internal margin implemented by shrinking the hull // TODO: Do we need the shrink clamp? (last parameter) btConvexHullComputer shrinkCH; btScalar shrunkBy = shrinkCH.compute(&pts[0], sizeof(btScalar)*3, rows, ch->insideMargin() * _options.worldScale, 0); if (shrunkBy < 0) { // TODO: Warning // "insideMargin is too large, convex hull would be too small."; btch.reset(new btConvexHullShape(&pts[0], rows, sizeof(btScalar)*3)); ch->setInsideMargin(0); } else { btch.reset(new btConvexHullShape); for (int i=0; i < shrinkCH.vertices.size(); i++) { const btVector3 &v(shrinkCH.vertices[i]); #if defined(BT_BULLET_VERSION) && (BT_BULLET_VERSION <= 281) btch->addPoint(v); #else btch->addPoint(v, false); #endif } ch->setInsideMargin(shrunkBy / _options.worldScale); } } // Add external margin and recalc bounding box btch->setMargin((ch->insideMargin() + ch->outsideMargin()) * _options.worldScale); btch->recalcLocalAabb(); // initialization createCollisionObjectHelper<SP::SiconosConvexHull, SP::BTCHSHAPE, BodyCHRecord> (base, ds, ch, btch, bodyShapeMap, contactor); } void SiconosBulletCollisionManager_impl::updateShape(BodyCHRecord &record) { SP::SiconosConvexHull ch(record.shape); SP::BTCHSHAPE btch(record.btshape); // Update shape parameters if (ch->version() != record.shape_version) { // TODO //btbox->setLocalScaling(btVector3(sx, sy, sz)); btch->setMargin((ch->insideMargin() + ch->outsideMargin()) * _options.worldScale); if (record.ds && record.ds->useContactorInertia()) updateContactorInertia(record.ds, btch); if (record.btobject->getBroadphaseHandle()) { _collisionWorld->updateSingleAabb(&*record.btobject); _collisionWorld->getBroadphase()->getOverlappingPairCache()-> cleanProxyFromPairs(record.btobject->getBroadphaseHandle(), &*_dispatcher); } record.shape_version = ch->version(); } updateShapePosition(record); } // If type of SiconosMatrix is the same as btScalar, we can avoid a copy template<typename SCALAR> std::pair<SP::btTriangleIndexVertexArray, SCALAR*> make_bt_vertex_array(SP::SiconosMesh mesh, SCALAR _s1, SCALAR _s2) { assert(mesh->vertices()->size(0) == 3); SP::btTriangleIndexVertexArray bttris( std11::make_shared<btTriangleIndexVertexArray>( mesh->indexes()->size()/3, (int*)mesh->indexes()->data(), sizeof(int)*3, mesh->vertices()->size(1), mesh->vertices()->getArray(), sizeof(btScalar)*3)); return std::make_pair(bttris, (btScalar*)NULL); } // If type of SiconosMatrix is not the same as btScalar, we must copy template<typename SCALAR1, typename SCALAR2> std::pair<SP::btTriangleIndexVertexArray, btScalar*> make_bt_vertex_array(SP::SiconosMesh mesh, SCALAR1 _s1, SCALAR2 _s2) { assert(mesh->vertices()->size(0) == 3); unsigned int numIndices = mesh->indexes()->size(); unsigned int numVertices = mesh->vertices()->size(1); btScalar *vertices = new btScalar[numVertices*3]; for (unsigned int i=0; i < numVertices; i++) { vertices[i*3+0] = (*mesh->vertices())(0,i); vertices[i*3+1] = (*mesh->vertices())(1,i); vertices[i*3+2] = (*mesh->vertices())(2,i); } SP::btTriangleIndexVertexArray bttris( std11::make_shared<btTriangleIndexVertexArray>( numIndices/3, (int*)mesh->indexes()->data(), sizeof(int)*3, numVertices, vertices, sizeof(btScalar)*3)); return std::make_pair(bttris, vertices); } void SiconosBulletCollisionManager_impl::createCollisionObject( const SP::SiconosVector base, const SP::BodyDS ds, SP::SiconosMesh mesh, SP::SiconosContactor contactor) { if (!mesh->indexes()) throw SiconosException("No indexes matrix specified for mesh."); if ((mesh->indexes()->size() % 3) != 0) throw SiconosException("Mesh indexes size must be divisible by 3."); if (!mesh->vertices()) throw SiconosException("No vertices matrix specified for mesh."); if (mesh->vertices()->size(0) != 3) throw SiconosException("Convex hull vertices matrix must have 3 columns."); // Create Bullet triangle list, either by copying on non-copying method // TODO: worldScale on vertices std::pair<SP::btTriangleIndexVertexArray, btScalar*> datapair( make_bt_vertex_array(mesh, (btScalar)0, (*mesh->vertices())(0,0))); SP::btTriangleIndexVertexArray bttris(datapair.first); // Create Bullet mesh object SP::BTMESHSHAPE btmesh(std11::make_shared<BTMESHSHAPE>(&*bttris)); // Hold on to the data since Bullet does not make a copy btmesh->btTriData = bttris; btmesh->btScalarVertices = datapair.second; // Initial bound update for btGImpaceMeshShape btmesh->updateBound(); // initialization createCollisionObjectHelper<SP::SiconosMesh, SP::BTMESHSHAPE, BodyMeshRecord> (base, ds, mesh, btmesh, bodyShapeMap, contactor); } void SiconosBulletCollisionManager_impl::updateShape(BodyMeshRecord &record) { SP::SiconosMesh mesh(record.shape); SP::BTMESHSHAPE btmesh(record.btshape); // Update shape parameters if (mesh->version() != record.shape_version) { // btBvhTriangleMeshShape supports only outsideMargin. // TODO: support insideMargin, scale the points by their normals. btmesh->setMargin(mesh->outsideMargin() * _options.worldScale); btmesh->postUpdate(); // TODO: Calculate inertia from a mesh. For now we leave it at // identity, the user can provide an inertia if desired. // if (record.ds && record.ds->useContactorInertia()) // updateContactorInertia(record.ds, btmesh); if (record.btobject->getBroadphaseHandle()) { _collisionWorld->updateSingleAabb(&*record.btobject); _collisionWorld->getBroadphase()->getOverlappingPairCache()-> cleanProxyFromPairs(record.btobject->getBroadphaseHandle(), &*_dispatcher); } record.shape_version = mesh->version(); } updateShapePosition(record); } void SiconosBulletCollisionManager_impl::createCollisionObject( const SP::SiconosVector base, const SP::BodyDS ds, SP::SiconosHeightMap heightmap, SP::SiconosContactor contactor) { if (!heightmap->height_data()) throw SiconosException("No height matrix specified for heightmap."); SP::SiconosMatrix data = heightmap->height_data(); if (!data || data->size(0) < 2 || data->size(1) < 2) throw SiconosException("Height matrix does not have sufficient dimensions " "to represent a plane."); // Create heightfield data for Bullet. Make a copy in case data // type btScalar is different from SiconosMatrix. // Calculate min and max value at the same time. double vmin = std::numeric_limits<double>::infinity(); double vmax = -vmin; std11::shared_ptr< std::vector<btScalar> > heightfield( std11::make_shared< std::vector<btScalar> >()); heightfield->resize(data->size(0) * data->size(1)); for (unsigned int i=0; i < data->size(0); i++) { for (unsigned int j=0; j < data->size(1); j++) { double v = data->getValue(i,j); (*heightfield)[j*data->size(0)+i] = v; if (v > vmax) vmax = v; if (v < vmin) vmin = v; } } // Create Bullet height object SP::BTHEIGHTSHAPE btheight(std11::make_shared<BTHEIGHTSHAPE>( data->size(0), heightfield, vmin, vmax)); // initialization createCollisionObjectHelper<SP::SiconosHeightMap, SP::BTHEIGHTSHAPE, BodyHeightRecord> (base, ds, heightmap, btheight, bodyShapeMap, contactor); } void SiconosBulletCollisionManager_impl::updateShape(BodyHeightRecord &record) { SP::SiconosHeightMap height(record.shape); SP::BTHEIGHTSHAPE btheight(record.btshape); // Update shape parameters if (height->version() != record.shape_version) { // btBvhTriangleHeightShape supports only outsideMargin. // TODO: support insideMargin, scale the points by their normals. btheight->setMargin((height->insideMargin() + height->outsideMargin()) * _options.worldScale); // The local scaling determines the extents of the base of the heightmap btheight->setLocalScaling(btVector3( height->length_x() / (height->height_data()->size(0)-1), height->length_y() / (height->height_data()->size(1)-1), 1)); //TODO vertical position offset to compensate for Bullet's centering // TODO: Calculate the local Aabb //btheight->recalcLocalAabb(); // TODO: Calculate inertia from a height. For now we leave it at // identity, the user can provide an inertia if desired. // if (record.ds && record.ds->useContactorInertia()) // updateContactorInertia(record.ds, btheight); if (record.btobject->getBroadphaseHandle()) { _collisionWorld->updateSingleAabb(&*record.btobject); _collisionWorld->getBroadphase()->getOverlappingPairCache()-> cleanProxyFromPairs(record.btobject->getBroadphaseHandle(), &*_dispatcher); } record.shape_version = height->version(); } // Like updateShapePosition(record), but we have to pre-compensate // the Bullet vertical centering of btHeightfieldTerrainShape. Must // be done before body rotation. // Bullet automatically moves the center of the object to the // vertical center of the heightfield, so combine it here with the // contactor offset. btScalar mnz = btheight->_min_height, mxz = btheight->_max_height; btScalar z_offset = (mxz-mnz)/2 + mnz - height->insideMargin(); SiconosVector o(7); o.zero(); o(2) = z_offset; o(3) = 1; btTransform t = offsetTransform(*record.contactor->offset, o); o(0) = t.getOrigin().getX(); o(1) = t.getOrigin().getY(); o(2) = t.getOrigin().getZ(); o(3) = t.getRotation().getW(); o(4) = t.getRotation().getX(); o(5) = t.getRotation().getY(); o(6) = t.getRotation().getZ(); // Now apply the combined height and contactor offset o to the base // transform q SiconosVector q(7); if (record.base) q = *record.base; else { q.zero(); q(3) = 1; } t = offsetTransform(q, o); DEBUG_PRINTF("updating shape position: %p(%ld) - %f, %f, %f\n", &*box,box.use_count(), q(0), q(1), q(2)); t.setOrigin(t.getOrigin() * _options.worldScale); record.btobject->setWorldTransform( t ); } class CreateCollisionObjectShapeVisitor : public SiconosVisitor { public: using SiconosVisitor::visit; SiconosBulletCollisionManager_impl &impl; const SP::BodyDS ds; const SP::SiconosVector base; SP::SiconosContactor contactor; CreateCollisionObjectShapeVisitor(SiconosBulletCollisionManager_impl &_impl, const SP::BodyDS _ds, const SP::SiconosVector _base) : impl(_impl), ds(_ds), base(_base) {} void visit(SP::SiconosPlane shape) { impl.createCollisionObject(base, ds, shape, contactor); } void visit(SP::SiconosSphere shape) { impl.createCollisionObject(base, ds, shape, contactor); } void visit(SP::SiconosBox shape) { impl.createCollisionObject(base, ds, shape, contactor); } void visit(SP::SiconosCylinder shape) { impl.createCollisionObject(base, ds, shape, contactor); } void visit(SP::SiconosConvexHull shape) { impl.createCollisionObject(base, ds, shape, contactor); } void visit(SP::SiconosMesh shape) { impl.createCollisionObject(base, ds, shape, contactor); } void visit(SP::SiconosHeightMap shape) { impl.createCollisionObject(base, ds, shape, contactor); } }; void SiconosBulletCollisionManager_impl::createCollisionObjectsForBodyContactorSet( const SP::BodyDS ds, SP::SiconosVector base, SP::SiconosContactorSet contactors) { // ensure consistency between ds and base and contactor -- if they // can be taken from the DS, ensure nothing else is provided. assert (!(ds && base) && "Provide either DS or base, but not both!"); assert (!(ds && contactors) && "Provide either DS or contactor set, but not both!"); // of course, we need at least one of the two combinations assert (ds || (base && contactors)); SP::SiconosContactorSet con(contactors); if (ds) { con = ds->contactors(); base = ds->q(); } if (!con) return; std11::shared_ptr<CreateCollisionObjectShapeVisitor> ccosv(new CreateCollisionObjectShapeVisitor(*this, ds, base)); /* Call createCollisionObject for each shape type using the visitor * defined above */ std::vector< SP::SiconosContactor >::const_iterator it; for (it=con->begin(); it!=con->end(); it++) { // special collision group -1 = do not collide, thus we can skip // creation of associated collision objects if ((*it)->collision_group == -1) continue; // otherwise visit the object with createCollisionObject ccosv->contactor = *it; ccosv->contactor->shape->acceptSP(ccosv); } } void SiconosBulletCollisionManager::removeBody(const SP::BodyDS& body) { BodyShapeMap::iterator it( impl->bodyShapeMap.find(&*body) ); if (it == impl->bodyShapeMap.end()) return; std::vector<std11::shared_ptr<BodyShapeRecord> >::iterator it2; for (it2 = it->second.begin(); it2 != it->second.end(); it2++) { impl->_collisionWorld->removeCollisionObject( &* (*it2)->btobject ); } impl->bodyShapeMap.erase(it); } /** This class allows to iterate over all the contact points in a * btCollisionWorld, returning a tuple containing the two btCollisionObjects * and the btManifoldPoint. To be called after * performDiscreteCollisionDetection(). */ class IterateContactPoints { public: SP::btCollisionWorld world; IterateContactPoints(SP::btCollisionWorld _world) : world(_world) {} struct ContactPointTuple { const btCollisionObject* objectA; const btCollisionObject* objectB; btManifoldPoint* point; btPersistentManifold* manifold; }; class iterator { protected: SP::btCollisionWorld world; ContactPointTuple data; unsigned int numManifolds; unsigned int numContacts; unsigned int manifold_index; unsigned int contact_index; iterator(SP::btCollisionWorld _world) { numManifolds = 0; manifold_index = -1; contact_index = -1; numContacts = 0; world = _world; numManifolds = world->getDispatcher()->getNumManifolds(); ++(*this); } public: const ContactPointTuple& operator*() { return data; }; const ContactPointTuple* operator->() { return &data; }; iterator() { numManifolds = 0; manifold_index = -1; contact_index = -1; numContacts = 0; } iterator& operator++() { if (numManifolds == 0) return *this; contact_index ++; while (contact_index >= numContacts) { manifold_index ++; if (manifold_index < numManifolds) { data.manifold = world->getDispatcher()-> getManifoldByIndexInternal(manifold_index); data.objectA = data.manifold->getBody0(); data.objectB = data.manifold->getBody1(); numContacts = data.manifold->getNumContacts(); contact_index = 0; } else { numManifolds = 0; return *this; } } data.point = &(data.manifold->getContactPoint(contact_index)); return *this; }; bool operator!=(const iterator &it) { if (it.numManifolds==0) return numManifolds!=0; return data.objectA != it.data.objectA || data.objectB != it.data.objectB || data.point != it.data.point; }; friend class IterateContactPoints; }; iterator begin() { return iterator(world); }; iterator end() { return iterator(); }; }; // called once for each contact point as it is destroyed Simulation* SiconosBulletCollisionManager::gSimulation; bool SiconosBulletCollisionManager::bulletContactClear(void* userPersistentData) { /* note: stored pointer to shared_ptr! */ SP::Interaction *p_inter = (SP::Interaction*)userPersistentData; assert(p_inter!=NULL && "Contact point's stored (SP::Interaction*) is null!"); DEBUG_PRINTF("unlinking interaction %p\n", &**p_inter); std11::static_pointer_cast<BulletR>((*p_inter)->relation())->preDelete(); gSimulation->unlink(*p_inter); delete p_inter; return false; } SP::BulletR SiconosBulletCollisionManager::makeBulletR(SP::BodyDS ds1, SP::SiconosShape shape1, SP::BodyDS ds2, SP::SiconosShape shape2, const btManifoldPoint &p) { return std11::make_shared<BulletR>(); } class CollisionUpdateVisitor : public SiconosVisitor { public: using SiconosVisitor::visit; SiconosBulletCollisionManager_impl &impl; CollisionUpdateVisitor(SiconosBulletCollisionManager_impl& _impl) : impl(_impl) {} void visit(SP::BodyDS bds) { if (bds->contactors()) { if (impl.bodyShapeMap.find(&*bds) == impl.bodyShapeMap.end()) { impl.createCollisionObjectsForBodyContactorSet(bds); } impl.updateAllShapesForDS(*bds); } } }; void SiconosBulletCollisionManager::updateInteractions(SP::Simulation simulation) { // -2. update collision objects from all BodyDS dynamical systems SP::SiconosVisitor updateVisitor(new CollisionUpdateVisitor(*impl)); simulation->nonSmoothDynamicalSystem()->visitDynamicalSystems(updateVisitor); // Clear cache automatically before collision detection if requested if (_options.clearOverlappingPairCache) clearOverlappingPairCache(); if (! impl->_queuedCollisionObjects.empty()) { std::vector<SP::btCollisionObject>::iterator it; for (it = impl->_queuedCollisionObjects.begin(); it != impl->_queuedCollisionObjects.end(); ++ it) { impl->_collisionWorld->addCollisionObject(&**it); } impl->_queuedCollisionObjects.clear(); } // -1. reset statistical counters resetStatistics(); // 0. set up bullet callbacks gSimulation = &*simulation; gContactDestroyedCallback = this->bulletContactClear; // Important parameter controlling contact point making and breaking gContactBreakingThreshold = _options.contactBreakingThreshold; // 1. perform bullet collision detection impl->_collisionWorld->performDiscreteCollisionDetection(); // 2. deleted contact points have been removed from the graph during the // bullet collision detection callbacks // 3. for each contact point, if there is no interaction, create one IterateContactPoints t(impl->_collisionWorld); IterateContactPoints::iterator it, itend=t.end(); DEBUG_PRINT("iterating contact points:\n"); for (it=t.begin(); it!=itend; ++it) { DEBUG_PRINTF(" -- %p, %p, %p\n", it->objectA, it->objectB, it->point); // Get the BodyDS and SiconosShape pointers const BodyShapeRecord *pairA, *pairB; pairA = reinterpret_cast<const BodyShapeRecord*>(it->objectA->getUserPointer()); pairB = reinterpret_cast<const BodyShapeRecord*>(it->objectB->getUserPointer()); assert(pairA && pairB && "btCollisionObject had a null user pointer!"); // The first pair will always be the non-static object bool flip = false; if (pairB->ds && !pairA->ds) { pairA = reinterpret_cast<const BodyShapeRecord*>(it->objectB->getUserPointer()); pairB = reinterpret_cast<const BodyShapeRecord*>(it->objectA->getUserPointer()); flip = true; } // If both collision objects belong to the same body (or no body), // no interaction is created. if (pairA->ds == pairB->ds) continue; // If the two bodies are already connected by another type of // relation (e.g. EqualityCondition == they have a joint between // them), then don't create contact constraints, because it leads // to an ill-conditioned problem. if (pairA->ds && pairB->ds) { InteractionsGraph::VIterator ui, uiend; SP::InteractionsGraph indexSet0 = simulation->nonSmoothDynamicalSystem()->topology()->indexSet0(); bool match = false; for (std11::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui) { SP::Interaction inter( indexSet0->bundle(*ui) ); SP::BodyDS ds1( std11::dynamic_pointer_cast<BodyDS>( indexSet0->properties(*ui).source) ); SP::BodyDS ds2( std11::dynamic_pointer_cast<BodyDS>( indexSet0->properties(*ui).target) ); if (ds1 && ds2 && (((&*ds1==&*pairA->ds) && (&*ds2==&*pairB->ds)) || ((&*ds1==&*pairB->ds) && (&*ds2==&*pairA->ds)))) { // Only match on non-BulletR interactions, i.e. non-contact relations SP::BulletR br ( std11::dynamic_pointer_cast<BulletR>(inter->relation()) ); if (!br) { SP::NewtonEulerJointR jr ( std11::dynamic_pointer_cast<NewtonEulerJointR>(inter->relation()) ); /* If it is a joint, check the joint self-collide property */ if (jr && !jr->allowSelfCollide()) match = true; /* If any non-contact relation is found, both bodies must * allow self-collide */ if (!pairA->ds->allowSelfCollide() || !pairB->ds->allowSelfCollide()) match = true; } if (match) break; } } if (match) continue; } if (it->point->m_userPersistentData) { /* interaction already exists */ SP::Interaction *p_inter = (SP::Interaction*)it->point->m_userPersistentData; /* update the relation */ SP::BulletR rel(std11::static_pointer_cast<BulletR>((*p_inter)->relation())); rel->updateContactPointsFromManifoldPoint(*it->manifold, *it->point, flip, _options.worldScale, pairA->ds, pairB->ds ? pairB->ds : SP::NewtonEulerDS()); _stats.existing_interactions_processed ++; } else { /* new interaction */ SP::Interaction inter; int g1 = pairA->contactor->collision_group; int g2 = pairB->contactor->collision_group; SP::NonSmoothLaw nslaw = nonSmoothLaw(g1,g2); if (nslaw && nslaw->size() == 3) { SP::BulletR rel(makeBulletR(pairA->ds, pairA->sshape, pairB->ds, pairB->sshape, *it->point)); if (!rel) continue; // Fill in extra contact information rel->base[0] = pairA->base; rel->base[1] = pairB->base; rel->shape[0] = pairA->sshape; rel->shape[1] = pairB->sshape; rel->contactor[0] = pairA->contactor; rel->contactor[1] = pairB->contactor; rel->ds[0] = pairA->ds; rel->ds[1] = pairB->ds; rel->btObject[0] = pairA->btobject; rel->btObject[1] = pairB->btobject; // TODO cast down btshape from BodyShapeRecord-derived classes // rel->btShape[0] = pairA->btshape; // rel->btShape[1] = pairB->btshape; rel->updateContactPointsFromManifoldPoint(*it->manifold, *it->point, flip, _options.worldScale, pairA->ds ? pairA->ds : SP::NewtonEulerDS(), pairB->ds ? pairB->ds : SP::NewtonEulerDS()); // We wish to be sure that no Interactions are created without // sufficient warning before contact. TODO: Replace with exception or // flag. if (rel->distance() < 0.0) { DEBUG_PRINTF(stderr, "Interactions must be created with positive " "distance (%f).\n", rel->distance()); _stats.interaction_warnings ++; } inter = std11::make_shared<Interaction>(nslaw, rel); _stats.new_interactions_created ++; } else { if (nslaw && nslaw->size() == 1) { SP::BulletFrom1DLocalFrameR rel( std11::make_shared<BulletFrom1DLocalFrameR>( createSPtrbtManifoldPoint(*it->point))); inter = std11::make_shared<Interaction>(nslaw, rel); } } if (inter) { /* store interaction in the contact point data, it will be freed by the * Bullet callback gContactDestroyedCallback */ /* note: storing pointer to shared_ptr! */ it->point->m_userPersistentData = (void*)(new SP::Interaction(inter)); /* link bodies by the new interaction */ simulation->link(inter, pairA->ds, pairB->ds); } } } } void SiconosBulletCollisionManager::clearOverlappingPairCache() { if (!impl->_collisionWorld) return; BodyShapeMap::iterator it; btOverlappingPairCache *pairCache = impl->_collisionWorld->getBroadphase()->getOverlappingPairCache(); for (it = impl->bodyShapeMap.begin(); it != impl->bodyShapeMap.end(); it++) { std::vector< std11::shared_ptr<BodyShapeRecord> >::iterator rec; for (rec = it->second.begin(); rec != it->second.end(); rec++) { if ((*rec)->btobject) { pairCache-> cleanProxyFromPairs((*rec)->btobject->getBroadphaseHandle(), &*impl->_dispatcher); } } } } /** Implement comparison for std::sort(). */ static bool cmpQueryResult(const SP::SiconosCollisionQueryResult &a, const SP::SiconosCollisionQueryResult &b) { return a->distance < b->distance; } std::vector<SP::SiconosCollisionQueryResult> SiconosBulletCollisionManager::lineIntersectionQuery(const SiconosVector& start, const SiconosVector& end, bool closestOnly, bool sorted) { std::vector<SP::SiconosCollisionQueryResult> result_list; btVector3 btstart(start(0), start(1), start(2)); btVector3 btend(end(0), end(1), end(2)); // Return at most one object if (closestOnly) { btCollisionWorld::ClosestRayResultCallback rayResult(btstart, btend); impl->_collisionWorld->rayTest(btstart, btend, rayResult); if (rayResult.hasHit()) { const BodyShapeRecord *rec = reinterpret_cast<const BodyShapeRecord*>( rayResult.m_collisionObject->getUserPointer()); if (rec) { SP::SiconosCollisionQueryResult result( std11::make_shared<SiconosCollisionQueryResult>()); result->point.resize(3); result->point.setValue(0, rayResult.m_hitPointWorld.getX()); result->point.setValue(1, rayResult.m_hitPointWorld.getY()); result->point.setValue(2, rayResult.m_hitPointWorld.getZ()); result->distance = (result->point - start).norm2(); result->body = rec->ds; // note: may be null for static contactors result->shape = rec->sshape; result->contactor = rec->contactor; result_list.push_back(result); } else { DEBUG_PRINTF("Siconos warning: BodyShapeRecord found by intersection was null."); } } } // Return more than one object, Bullet provides a different // interface else { btCollisionWorld::AllHitsRayResultCallback rayResult(btstart, btend); impl->_collisionWorld->rayTest(btstart, btend, rayResult); if (rayResult.hasHit()) { for (int i=0; i < rayResult.m_collisionObjects.size(); i++) { const BodyShapeRecord *rec = reinterpret_cast<const BodyShapeRecord*>( rayResult.m_collisionObjects[i]->getUserPointer()); if (rec) { SP::SiconosCollisionQueryResult result( std11::make_shared<SiconosCollisionQueryResult>()); result->point.resize(3); result->point.setValue(0, rayResult.m_hitPointWorld[i].getX()); result->point.setValue(1, rayResult.m_hitPointWorld[i].getY()); result->point.setValue(2, rayResult.m_hitPointWorld[i].getZ()); result->distance = (result->point - start).norm2(); result->body = rec->ds; // note: null for static contactors result->shape = rec->sshape; result->contactor = rec->contactor; result_list.push_back(result); } else { DEBUG_PRINTF("Siconos warning: BodyShapeRecord found by intersection was null."); } } } } if (sorted && result_list.size() > 1) std::sort(result_list.begin(), result_list.end(), cmpQueryResult); return result_list; }
34.65696
104
0.675831
[ "mesh", "object", "shape", "vector", "transform" ]
335d0e3140a7eb6cc6808daa62be508936b9753e
40,245
hpp
C++
ThirdParty-mod/java2cpp/android/app/Dialog.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/android/app/Dialog.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/android/app/Dialog.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.app.Dialog ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_APP_DIALOG_HPP_DECL #define J2CPP_ANDROID_APP_DIALOG_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class CharSequence; } } } namespace j2cpp { namespace android { namespace net { class Uri; } } } namespace j2cpp { namespace android { namespace app { class Activity; } } } namespace j2cpp { namespace android { namespace graphics { namespace drawable { class Drawable; } } } } namespace j2cpp { namespace android { namespace content { class DialogInterface; } } } namespace j2cpp { namespace android { namespace content { namespace DialogInterface_ { class OnDismissListener; } } } } namespace j2cpp { namespace android { namespace content { class Context; } } } namespace j2cpp { namespace android { namespace content { namespace DialogInterface_ { class OnCancelListener; } } } } namespace j2cpp { namespace android { namespace content { namespace DialogInterface_ { class OnKeyListener; } } } } namespace j2cpp { namespace android { namespace view { class View; } } } namespace j2cpp { namespace android { namespace view { class Window; } } } namespace j2cpp { namespace android { namespace view { namespace Window_ { class Callback; } } } } namespace j2cpp { namespace android { namespace view { class LayoutInflater; } } } namespace j2cpp { namespace android { namespace view { class KeyEvent; } } } namespace j2cpp { namespace android { namespace view { class ContextMenu; } } } namespace j2cpp { namespace android { namespace view { class MotionEvent; } } } namespace j2cpp { namespace android { namespace view { namespace accessibility { class AccessibilityEvent; } } } } namespace j2cpp { namespace android { namespace view { class MenuItem; } } } namespace j2cpp { namespace android { namespace view { namespace ViewGroup_ { class LayoutParams; } } } } namespace j2cpp { namespace android { namespace view { class Menu; } } } namespace j2cpp { namespace android { namespace view { namespace View_ { class OnCreateContextMenuListener; } } } } namespace j2cpp { namespace android { namespace view { namespace ContextMenu_ { class ContextMenuInfo; } } } } namespace j2cpp { namespace android { namespace view { namespace WindowManager_ { class LayoutParams; } } } } namespace j2cpp { namespace android { namespace os { class Bundle; } } } namespace j2cpp { namespace android { namespace os { class Message; } } } #include <android/app/Activity.hpp> #include <android/content/Context.hpp> #include <android/content/DialogInterface.hpp> #include <android/graphics/drawable/Drawable.hpp> #include <android/net/Uri.hpp> #include <android/os/Bundle.hpp> #include <android/os/Message.hpp> #include <android/view/ContextMenu.hpp> #include <android/view/KeyEvent.hpp> #include <android/view/LayoutInflater.hpp> #include <android/view/Menu.hpp> #include <android/view/MenuItem.hpp> #include <android/view/MotionEvent.hpp> #include <android/view/View.hpp> #include <android/view/ViewGroup.hpp> #include <android/view/Window.hpp> #include <android/view/WindowManager.hpp> #include <android/view/accessibility/AccessibilityEvent.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/Object.hpp> namespace j2cpp { namespace android { namespace app { class Dialog; class Dialog : public object<Dialog> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) J2CPP_DECLARE_METHOD(15) J2CPP_DECLARE_METHOD(16) J2CPP_DECLARE_METHOD(17) J2CPP_DECLARE_METHOD(18) J2CPP_DECLARE_METHOD(19) J2CPP_DECLARE_METHOD(20) J2CPP_DECLARE_METHOD(21) J2CPP_DECLARE_METHOD(22) J2CPP_DECLARE_METHOD(23) J2CPP_DECLARE_METHOD(24) J2CPP_DECLARE_METHOD(25) J2CPP_DECLARE_METHOD(26) J2CPP_DECLARE_METHOD(27) J2CPP_DECLARE_METHOD(28) J2CPP_DECLARE_METHOD(29) J2CPP_DECLARE_METHOD(30) J2CPP_DECLARE_METHOD(31) J2CPP_DECLARE_METHOD(32) J2CPP_DECLARE_METHOD(33) J2CPP_DECLARE_METHOD(34) J2CPP_DECLARE_METHOD(35) J2CPP_DECLARE_METHOD(36) J2CPP_DECLARE_METHOD(37) J2CPP_DECLARE_METHOD(38) J2CPP_DECLARE_METHOD(39) J2CPP_DECLARE_METHOD(40) J2CPP_DECLARE_METHOD(41) J2CPP_DECLARE_METHOD(42) J2CPP_DECLARE_METHOD(43) J2CPP_DECLARE_METHOD(44) J2CPP_DECLARE_METHOD(45) J2CPP_DECLARE_METHOD(46) J2CPP_DECLARE_METHOD(47) J2CPP_DECLARE_METHOD(48) J2CPP_DECLARE_METHOD(49) J2CPP_DECLARE_METHOD(50) J2CPP_DECLARE_METHOD(51) J2CPP_DECLARE_METHOD(52) J2CPP_DECLARE_METHOD(53) J2CPP_DECLARE_METHOD(54) J2CPP_DECLARE_METHOD(55) J2CPP_DECLARE_METHOD(56) J2CPP_DECLARE_METHOD(57) J2CPP_DECLARE_METHOD(58) J2CPP_DECLARE_METHOD(59) J2CPP_DECLARE_METHOD(60) J2CPP_DECLARE_METHOD(61) J2CPP_DECLARE_METHOD(62) J2CPP_DECLARE_METHOD(63) J2CPP_DECLARE_METHOD(64) J2CPP_DECLARE_METHOD(65) J2CPP_DECLARE_METHOD(66) J2CPP_DECLARE_METHOD(67) J2CPP_DECLARE_METHOD(68) J2CPP_DECLARE_METHOD(69) J2CPP_DECLARE_METHOD(70) J2CPP_DECLARE_METHOD(71) J2CPP_DECLARE_METHOD(72) J2CPP_DECLARE_METHOD(73) J2CPP_DECLARE_METHOD(74) J2CPP_DECLARE_METHOD(75) explicit Dialog(jobject jobj) : object<Dialog>(jobj) { } operator local_ref<java::lang::Object>() const; operator local_ref<android::content::DialogInterface>() const; operator local_ref<android::view::Window_::Callback>() const; operator local_ref<android::view::View_::OnCreateContextMenuListener>() const; Dialog(local_ref< android::content::Context > const&); Dialog(local_ref< android::content::Context > const&, jint); local_ref< android::content::Context > getContext(); void setOwnerActivity(local_ref< android::app::Activity > const&); local_ref< android::app::Activity > getOwnerActivity(); jboolean isShowing(); void show(); void hide(); void dismiss(); local_ref< android::os::Bundle > onSaveInstanceState(); void onRestoreInstanceState(local_ref< android::os::Bundle > const&); local_ref< android::view::Window > getWindow(); local_ref< android::view::View > getCurrentFocus(); local_ref< android::view::View > findViewById(jint); void setContentView(jint); void setContentView(local_ref< android::view::View > const&); void setContentView(local_ref< android::view::View > const&, local_ref< android::view::ViewGroup_::LayoutParams > const&); void addContentView(local_ref< android::view::View > const&, local_ref< android::view::ViewGroup_::LayoutParams > const&); void setTitle(local_ref< java::lang::CharSequence > const&); void setTitle(jint); jboolean onKeyDown(jint, local_ref< android::view::KeyEvent > const&); jboolean onKeyLongPress(jint, local_ref< android::view::KeyEvent > const&); jboolean onKeyUp(jint, local_ref< android::view::KeyEvent > const&); jboolean onKeyMultiple(jint, jint, local_ref< android::view::KeyEvent > const&); void onBackPressed(); jboolean onTouchEvent(local_ref< android::view::MotionEvent > const&); jboolean onTrackballEvent(local_ref< android::view::MotionEvent > const&); void onWindowAttributesChanged(local_ref< android::view::WindowManager_::LayoutParams > const&); void onContentChanged(); void onWindowFocusChanged(jboolean); void onAttachedToWindow(); void onDetachedFromWindow(); jboolean dispatchKeyEvent(local_ref< android::view::KeyEvent > const&); jboolean dispatchTouchEvent(local_ref< android::view::MotionEvent > const&); jboolean dispatchTrackballEvent(local_ref< android::view::MotionEvent > const&); jboolean dispatchPopulateAccessibilityEvent(local_ref< android::view::accessibility::AccessibilityEvent > const&); local_ref< android::view::View > onCreatePanelView(jint); jboolean onCreatePanelMenu(jint, local_ref< android::view::Menu > const&); jboolean onPreparePanel(jint, local_ref< android::view::View > const&, local_ref< android::view::Menu > const&); jboolean onMenuOpened(jint, local_ref< android::view::Menu > const&); jboolean onMenuItemSelected(jint, local_ref< android::view::MenuItem > const&); void onPanelClosed(jint, local_ref< android::view::Menu > const&); jboolean onCreateOptionsMenu(local_ref< android::view::Menu > const&); jboolean onPrepareOptionsMenu(local_ref< android::view::Menu > const&); jboolean onOptionsItemSelected(local_ref< android::view::MenuItem > const&); void onOptionsMenuClosed(local_ref< android::view::Menu > const&); void openOptionsMenu(); void closeOptionsMenu(); void onCreateContextMenu(local_ref< android::view::ContextMenu > const&, local_ref< android::view::View > const&, local_ref< android::view::ContextMenu_::ContextMenuInfo > const&); void registerForContextMenu(local_ref< android::view::View > const&); void unregisterForContextMenu(local_ref< android::view::View > const&); void openContextMenu(local_ref< android::view::View > const&); jboolean onContextItemSelected(local_ref< android::view::MenuItem > const&); void onContextMenuClosed(local_ref< android::view::Menu > const&); jboolean onSearchRequested(); void takeKeyEvents(jboolean); jboolean requestWindowFeature(jint); void setFeatureDrawableResource(jint, jint); void setFeatureDrawableUri(jint, local_ref< android::net::Uri > const&); void setFeatureDrawable(jint, local_ref< android::graphics::drawable::Drawable > const&); void setFeatureDrawableAlpha(jint, jint); local_ref< android::view::LayoutInflater > getLayoutInflater(); void setCancelable(jboolean); void setCanceledOnTouchOutside(jboolean); void cancel(); void setOnCancelListener(local_ref< android::content::DialogInterface_::OnCancelListener > const&); void setCancelMessage(local_ref< android::os::Message > const&); void setOnDismissListener(local_ref< android::content::DialogInterface_::OnDismissListener > const&); void setDismissMessage(local_ref< android::os::Message > const&); void setVolumeControlStream(jint); jint getVolumeControlStream(); void setOnKeyListener(local_ref< android::content::DialogInterface_::OnKeyListener > const&); }; //class Dialog } //namespace app } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_APP_DIALOG_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_APP_DIALOG_HPP_IMPL #define J2CPP_ANDROID_APP_DIALOG_HPP_IMPL namespace j2cpp { android::app::Dialog::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::app::Dialog::operator local_ref<android::content::DialogInterface>() const { return local_ref<android::content::DialogInterface>(get_jobject()); } android::app::Dialog::operator local_ref<android::view::Window_::Callback>() const { return local_ref<android::view::Window_::Callback>(get_jobject()); } android::app::Dialog::operator local_ref<android::view::View_::OnCreateContextMenuListener>() const { return local_ref<android::view::View_::OnCreateContextMenuListener>(get_jobject()); } android::app::Dialog::Dialog(local_ref< android::content::Context > const &a0) : object<android::app::Dialog>( call_new_object< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(0), android::app::Dialog::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } android::app::Dialog::Dialog(local_ref< android::content::Context > const &a0, jint a1) : object<android::app::Dialog>( call_new_object< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(1), android::app::Dialog::J2CPP_METHOD_SIGNATURE(1) >(a0, a1) ) { } local_ref< android::content::Context > android::app::Dialog::getContext() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(3), android::app::Dialog::J2CPP_METHOD_SIGNATURE(3), local_ref< android::content::Context > >(get_jobject()); } void android::app::Dialog::setOwnerActivity(local_ref< android::app::Activity > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(4), android::app::Dialog::J2CPP_METHOD_SIGNATURE(4), void >(get_jobject(), a0); } local_ref< android::app::Activity > android::app::Dialog::getOwnerActivity() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(5), android::app::Dialog::J2CPP_METHOD_SIGNATURE(5), local_ref< android::app::Activity > >(get_jobject()); } jboolean android::app::Dialog::isShowing() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(6), android::app::Dialog::J2CPP_METHOD_SIGNATURE(6), jboolean >(get_jobject()); } void android::app::Dialog::show() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(7), android::app::Dialog::J2CPP_METHOD_SIGNATURE(7), void >(get_jobject()); } void android::app::Dialog::hide() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(8), android::app::Dialog::J2CPP_METHOD_SIGNATURE(8), void >(get_jobject()); } void android::app::Dialog::dismiss() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(9), android::app::Dialog::J2CPP_METHOD_SIGNATURE(9), void >(get_jobject()); } local_ref< android::os::Bundle > android::app::Dialog::onSaveInstanceState() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(13), android::app::Dialog::J2CPP_METHOD_SIGNATURE(13), local_ref< android::os::Bundle > >(get_jobject()); } void android::app::Dialog::onRestoreInstanceState(local_ref< android::os::Bundle > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(14), android::app::Dialog::J2CPP_METHOD_SIGNATURE(14), void >(get_jobject(), a0); } local_ref< android::view::Window > android::app::Dialog::getWindow() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(15), android::app::Dialog::J2CPP_METHOD_SIGNATURE(15), local_ref< android::view::Window > >(get_jobject()); } local_ref< android::view::View > android::app::Dialog::getCurrentFocus() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(16), android::app::Dialog::J2CPP_METHOD_SIGNATURE(16), local_ref< android::view::View > >(get_jobject()); } local_ref< android::view::View > android::app::Dialog::findViewById(jint a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(17), android::app::Dialog::J2CPP_METHOD_SIGNATURE(17), local_ref< android::view::View > >(get_jobject(), a0); } void android::app::Dialog::setContentView(jint a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(18), android::app::Dialog::J2CPP_METHOD_SIGNATURE(18), void >(get_jobject(), a0); } void android::app::Dialog::setContentView(local_ref< android::view::View > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(19), android::app::Dialog::J2CPP_METHOD_SIGNATURE(19), void >(get_jobject(), a0); } void android::app::Dialog::setContentView(local_ref< android::view::View > const &a0, local_ref< android::view::ViewGroup_::LayoutParams > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(20), android::app::Dialog::J2CPP_METHOD_SIGNATURE(20), void >(get_jobject(), a0, a1); } void android::app::Dialog::addContentView(local_ref< android::view::View > const &a0, local_ref< android::view::ViewGroup_::LayoutParams > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(21), android::app::Dialog::J2CPP_METHOD_SIGNATURE(21), void >(get_jobject(), a0, a1); } void android::app::Dialog::setTitle(local_ref< java::lang::CharSequence > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(22), android::app::Dialog::J2CPP_METHOD_SIGNATURE(22), void >(get_jobject(), a0); } void android::app::Dialog::setTitle(jint a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(23), android::app::Dialog::J2CPP_METHOD_SIGNATURE(23), void >(get_jobject(), a0); } jboolean android::app::Dialog::onKeyDown(jint a0, local_ref< android::view::KeyEvent > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(24), android::app::Dialog::J2CPP_METHOD_SIGNATURE(24), jboolean >(get_jobject(), a0, a1); } jboolean android::app::Dialog::onKeyLongPress(jint a0, local_ref< android::view::KeyEvent > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(25), android::app::Dialog::J2CPP_METHOD_SIGNATURE(25), jboolean >(get_jobject(), a0, a1); } jboolean android::app::Dialog::onKeyUp(jint a0, local_ref< android::view::KeyEvent > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(26), android::app::Dialog::J2CPP_METHOD_SIGNATURE(26), jboolean >(get_jobject(), a0, a1); } jboolean android::app::Dialog::onKeyMultiple(jint a0, jint a1, local_ref< android::view::KeyEvent > const &a2) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(27), android::app::Dialog::J2CPP_METHOD_SIGNATURE(27), jboolean >(get_jobject(), a0, a1, a2); } void android::app::Dialog::onBackPressed() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(28), android::app::Dialog::J2CPP_METHOD_SIGNATURE(28), void >(get_jobject()); } jboolean android::app::Dialog::onTouchEvent(local_ref< android::view::MotionEvent > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(29), android::app::Dialog::J2CPP_METHOD_SIGNATURE(29), jboolean >(get_jobject(), a0); } jboolean android::app::Dialog::onTrackballEvent(local_ref< android::view::MotionEvent > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(30), android::app::Dialog::J2CPP_METHOD_SIGNATURE(30), jboolean >(get_jobject(), a0); } void android::app::Dialog::onWindowAttributesChanged(local_ref< android::view::WindowManager_::LayoutParams > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(31), android::app::Dialog::J2CPP_METHOD_SIGNATURE(31), void >(get_jobject(), a0); } void android::app::Dialog::onContentChanged() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(32), android::app::Dialog::J2CPP_METHOD_SIGNATURE(32), void >(get_jobject()); } void android::app::Dialog::onWindowFocusChanged(jboolean a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(33), android::app::Dialog::J2CPP_METHOD_SIGNATURE(33), void >(get_jobject(), a0); } void android::app::Dialog::onAttachedToWindow() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(34), android::app::Dialog::J2CPP_METHOD_SIGNATURE(34), void >(get_jobject()); } void android::app::Dialog::onDetachedFromWindow() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(35), android::app::Dialog::J2CPP_METHOD_SIGNATURE(35), void >(get_jobject()); } jboolean android::app::Dialog::dispatchKeyEvent(local_ref< android::view::KeyEvent > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(36), android::app::Dialog::J2CPP_METHOD_SIGNATURE(36), jboolean >(get_jobject(), a0); } jboolean android::app::Dialog::dispatchTouchEvent(local_ref< android::view::MotionEvent > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(37), android::app::Dialog::J2CPP_METHOD_SIGNATURE(37), jboolean >(get_jobject(), a0); } jboolean android::app::Dialog::dispatchTrackballEvent(local_ref< android::view::MotionEvent > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(38), android::app::Dialog::J2CPP_METHOD_SIGNATURE(38), jboolean >(get_jobject(), a0); } jboolean android::app::Dialog::dispatchPopulateAccessibilityEvent(local_ref< android::view::accessibility::AccessibilityEvent > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(39), android::app::Dialog::J2CPP_METHOD_SIGNATURE(39), jboolean >(get_jobject(), a0); } local_ref< android::view::View > android::app::Dialog::onCreatePanelView(jint a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(40), android::app::Dialog::J2CPP_METHOD_SIGNATURE(40), local_ref< android::view::View > >(get_jobject(), a0); } jboolean android::app::Dialog::onCreatePanelMenu(jint a0, local_ref< android::view::Menu > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(41), android::app::Dialog::J2CPP_METHOD_SIGNATURE(41), jboolean >(get_jobject(), a0, a1); } jboolean android::app::Dialog::onPreparePanel(jint a0, local_ref< android::view::View > const &a1, local_ref< android::view::Menu > const &a2) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(42), android::app::Dialog::J2CPP_METHOD_SIGNATURE(42), jboolean >(get_jobject(), a0, a1, a2); } jboolean android::app::Dialog::onMenuOpened(jint a0, local_ref< android::view::Menu > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(43), android::app::Dialog::J2CPP_METHOD_SIGNATURE(43), jboolean >(get_jobject(), a0, a1); } jboolean android::app::Dialog::onMenuItemSelected(jint a0, local_ref< android::view::MenuItem > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(44), android::app::Dialog::J2CPP_METHOD_SIGNATURE(44), jboolean >(get_jobject(), a0, a1); } void android::app::Dialog::onPanelClosed(jint a0, local_ref< android::view::Menu > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(45), android::app::Dialog::J2CPP_METHOD_SIGNATURE(45), void >(get_jobject(), a0, a1); } jboolean android::app::Dialog::onCreateOptionsMenu(local_ref< android::view::Menu > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(46), android::app::Dialog::J2CPP_METHOD_SIGNATURE(46), jboolean >(get_jobject(), a0); } jboolean android::app::Dialog::onPrepareOptionsMenu(local_ref< android::view::Menu > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(47), android::app::Dialog::J2CPP_METHOD_SIGNATURE(47), jboolean >(get_jobject(), a0); } jboolean android::app::Dialog::onOptionsItemSelected(local_ref< android::view::MenuItem > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(48), android::app::Dialog::J2CPP_METHOD_SIGNATURE(48), jboolean >(get_jobject(), a0); } void android::app::Dialog::onOptionsMenuClosed(local_ref< android::view::Menu > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(49), android::app::Dialog::J2CPP_METHOD_SIGNATURE(49), void >(get_jobject(), a0); } void android::app::Dialog::openOptionsMenu() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(50), android::app::Dialog::J2CPP_METHOD_SIGNATURE(50), void >(get_jobject()); } void android::app::Dialog::closeOptionsMenu() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(51), android::app::Dialog::J2CPP_METHOD_SIGNATURE(51), void >(get_jobject()); } void android::app::Dialog::onCreateContextMenu(local_ref< android::view::ContextMenu > const &a0, local_ref< android::view::View > const &a1, local_ref< android::view::ContextMenu_::ContextMenuInfo > const &a2) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(52), android::app::Dialog::J2CPP_METHOD_SIGNATURE(52), void >(get_jobject(), a0, a1, a2); } void android::app::Dialog::registerForContextMenu(local_ref< android::view::View > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(53), android::app::Dialog::J2CPP_METHOD_SIGNATURE(53), void >(get_jobject(), a0); } void android::app::Dialog::unregisterForContextMenu(local_ref< android::view::View > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(54), android::app::Dialog::J2CPP_METHOD_SIGNATURE(54), void >(get_jobject(), a0); } void android::app::Dialog::openContextMenu(local_ref< android::view::View > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(55), android::app::Dialog::J2CPP_METHOD_SIGNATURE(55), void >(get_jobject(), a0); } jboolean android::app::Dialog::onContextItemSelected(local_ref< android::view::MenuItem > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(56), android::app::Dialog::J2CPP_METHOD_SIGNATURE(56), jboolean >(get_jobject(), a0); } void android::app::Dialog::onContextMenuClosed(local_ref< android::view::Menu > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(57), android::app::Dialog::J2CPP_METHOD_SIGNATURE(57), void >(get_jobject(), a0); } jboolean android::app::Dialog::onSearchRequested() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(58), android::app::Dialog::J2CPP_METHOD_SIGNATURE(58), jboolean >(get_jobject()); } void android::app::Dialog::takeKeyEvents(jboolean a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(59), android::app::Dialog::J2CPP_METHOD_SIGNATURE(59), void >(get_jobject(), a0); } jboolean android::app::Dialog::requestWindowFeature(jint a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(60), android::app::Dialog::J2CPP_METHOD_SIGNATURE(60), jboolean >(get_jobject(), a0); } void android::app::Dialog::setFeatureDrawableResource(jint a0, jint a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(61), android::app::Dialog::J2CPP_METHOD_SIGNATURE(61), void >(get_jobject(), a0, a1); } void android::app::Dialog::setFeatureDrawableUri(jint a0, local_ref< android::net::Uri > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(62), android::app::Dialog::J2CPP_METHOD_SIGNATURE(62), void >(get_jobject(), a0, a1); } void android::app::Dialog::setFeatureDrawable(jint a0, local_ref< android::graphics::drawable::Drawable > const &a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(63), android::app::Dialog::J2CPP_METHOD_SIGNATURE(63), void >(get_jobject(), a0, a1); } void android::app::Dialog::setFeatureDrawableAlpha(jint a0, jint a1) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(64), android::app::Dialog::J2CPP_METHOD_SIGNATURE(64), void >(get_jobject(), a0, a1); } local_ref< android::view::LayoutInflater > android::app::Dialog::getLayoutInflater() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(65), android::app::Dialog::J2CPP_METHOD_SIGNATURE(65), local_ref< android::view::LayoutInflater > >(get_jobject()); } void android::app::Dialog::setCancelable(jboolean a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(66), android::app::Dialog::J2CPP_METHOD_SIGNATURE(66), void >(get_jobject(), a0); } void android::app::Dialog::setCanceledOnTouchOutside(jboolean a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(67), android::app::Dialog::J2CPP_METHOD_SIGNATURE(67), void >(get_jobject(), a0); } void android::app::Dialog::cancel() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(68), android::app::Dialog::J2CPP_METHOD_SIGNATURE(68), void >(get_jobject()); } void android::app::Dialog::setOnCancelListener(local_ref< android::content::DialogInterface_::OnCancelListener > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(69), android::app::Dialog::J2CPP_METHOD_SIGNATURE(69), void >(get_jobject(), a0); } void android::app::Dialog::setCancelMessage(local_ref< android::os::Message > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(70), android::app::Dialog::J2CPP_METHOD_SIGNATURE(70), void >(get_jobject(), a0); } void android::app::Dialog::setOnDismissListener(local_ref< android::content::DialogInterface_::OnDismissListener > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(71), android::app::Dialog::J2CPP_METHOD_SIGNATURE(71), void >(get_jobject(), a0); } void android::app::Dialog::setDismissMessage(local_ref< android::os::Message > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(72), android::app::Dialog::J2CPP_METHOD_SIGNATURE(72), void >(get_jobject(), a0); } void android::app::Dialog::setVolumeControlStream(jint a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(73), android::app::Dialog::J2CPP_METHOD_SIGNATURE(73), void >(get_jobject(), a0); } jint android::app::Dialog::getVolumeControlStream() { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(74), android::app::Dialog::J2CPP_METHOD_SIGNATURE(74), jint >(get_jobject()); } void android::app::Dialog::setOnKeyListener(local_ref< android::content::DialogInterface_::OnKeyListener > const &a0) { return call_method< android::app::Dialog::J2CPP_CLASS_NAME, android::app::Dialog::J2CPP_METHOD_NAME(75), android::app::Dialog::J2CPP_METHOD_SIGNATURE(75), void >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(android::app::Dialog,"android/app/Dialog") J2CPP_DEFINE_METHOD(android::app::Dialog,0,"<init>","(Landroid/content/Context;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,1,"<init>","(Landroid/content/Context;I)V") J2CPP_DEFINE_METHOD(android::app::Dialog,2,"<init>","(Landroid/content/Context;ZLandroid/content/DialogInterface$OnCancelListener;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,3,"getContext","()Landroid/content/Context;") J2CPP_DEFINE_METHOD(android::app::Dialog,4,"setOwnerActivity","(Landroid/app/Activity;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,5,"getOwnerActivity","()Landroid/app/Activity;") J2CPP_DEFINE_METHOD(android::app::Dialog,6,"isShowing","()Z") J2CPP_DEFINE_METHOD(android::app::Dialog,7,"show","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,8,"hide","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,9,"dismiss","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,10,"onCreate","(Landroid/os/Bundle;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,11,"onStart","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,12,"onStop","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,13,"onSaveInstanceState","()Landroid/os/Bundle;") J2CPP_DEFINE_METHOD(android::app::Dialog,14,"onRestoreInstanceState","(Landroid/os/Bundle;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,15,"getWindow","()Landroid/view/Window;") J2CPP_DEFINE_METHOD(android::app::Dialog,16,"getCurrentFocus","()Landroid/view/View;") J2CPP_DEFINE_METHOD(android::app::Dialog,17,"findViewById","(I)Landroid/view/View;") J2CPP_DEFINE_METHOD(android::app::Dialog,18,"setContentView","(I)V") J2CPP_DEFINE_METHOD(android::app::Dialog,19,"setContentView","(Landroid/view/View;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,20,"setContentView","(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,21,"addContentView","(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,22,"setTitle","(Ljava/lang/CharSequence;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,23,"setTitle","(I)V") J2CPP_DEFINE_METHOD(android::app::Dialog,24,"onKeyDown","(ILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,25,"onKeyLongPress","(ILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,26,"onKeyUp","(ILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,27,"onKeyMultiple","(IILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,28,"onBackPressed","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,29,"onTouchEvent","(Landroid/view/MotionEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,30,"onTrackballEvent","(Landroid/view/MotionEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,31,"onWindowAttributesChanged","(Landroid/view/WindowManager$LayoutParams;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,32,"onContentChanged","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,33,"onWindowFocusChanged","(Z)V") J2CPP_DEFINE_METHOD(android::app::Dialog,34,"onAttachedToWindow","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,35,"onDetachedFromWindow","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,36,"dispatchKeyEvent","(Landroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,37,"dispatchTouchEvent","(Landroid/view/MotionEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,38,"dispatchTrackballEvent","(Landroid/view/MotionEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,39,"dispatchPopulateAccessibilityEvent","(Landroid/view/accessibility/AccessibilityEvent;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,40,"onCreatePanelView","(I)Landroid/view/View;") J2CPP_DEFINE_METHOD(android::app::Dialog,41,"onCreatePanelMenu","(ILandroid/view/Menu;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,42,"onPreparePanel","(ILandroid/view/View;Landroid/view/Menu;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,43,"onMenuOpened","(ILandroid/view/Menu;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,44,"onMenuItemSelected","(ILandroid/view/MenuItem;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,45,"onPanelClosed","(ILandroid/view/Menu;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,46,"onCreateOptionsMenu","(Landroid/view/Menu;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,47,"onPrepareOptionsMenu","(Landroid/view/Menu;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,48,"onOptionsItemSelected","(Landroid/view/MenuItem;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,49,"onOptionsMenuClosed","(Landroid/view/Menu;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,50,"openOptionsMenu","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,51,"closeOptionsMenu","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,52,"onCreateContextMenu","(Landroid/view/ContextMenu;Landroid/view/View;Landroid/view/ContextMenu$ContextMenuInfo;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,53,"registerForContextMenu","(Landroid/view/View;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,54,"unregisterForContextMenu","(Landroid/view/View;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,55,"openContextMenu","(Landroid/view/View;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,56,"onContextItemSelected","(Landroid/view/MenuItem;)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,57,"onContextMenuClosed","(Landroid/view/Menu;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,58,"onSearchRequested","()Z") J2CPP_DEFINE_METHOD(android::app::Dialog,59,"takeKeyEvents","(Z)V") J2CPP_DEFINE_METHOD(android::app::Dialog,60,"requestWindowFeature","(I)Z") J2CPP_DEFINE_METHOD(android::app::Dialog,61,"setFeatureDrawableResource","(II)V") J2CPP_DEFINE_METHOD(android::app::Dialog,62,"setFeatureDrawableUri","(ILandroid/net/Uri;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,63,"setFeatureDrawable","(ILandroid/graphics/drawable/Drawable;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,64,"setFeatureDrawableAlpha","(II)V") J2CPP_DEFINE_METHOD(android::app::Dialog,65,"getLayoutInflater","()Landroid/view/LayoutInflater;") J2CPP_DEFINE_METHOD(android::app::Dialog,66,"setCancelable","(Z)V") J2CPP_DEFINE_METHOD(android::app::Dialog,67,"setCanceledOnTouchOutside","(Z)V") J2CPP_DEFINE_METHOD(android::app::Dialog,68,"cancel","()V") J2CPP_DEFINE_METHOD(android::app::Dialog,69,"setOnCancelListener","(Landroid/content/DialogInterface$OnCancelListener;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,70,"setCancelMessage","(Landroid/os/Message;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,71,"setOnDismissListener","(Landroid/content/DialogInterface$OnDismissListener;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,72,"setDismissMessage","(Landroid/os/Message;)V") J2CPP_DEFINE_METHOD(android::app::Dialog,73,"setVolumeControlStream","(I)V") J2CPP_DEFINE_METHOD(android::app::Dialog,74,"getVolumeControlStream","()I") J2CPP_DEFINE_METHOD(android::app::Dialog,75,"setOnKeyListener","(Landroid/content/DialogInterface$OnKeyListener;)V") } //namespace j2cpp #endif //J2CPP_ANDROID_APP_DIALOG_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
36.98989
211
0.729233
[ "object" ]
335de93c9761cf424a80312b249b4193b59a64c1
36,167
cpp
C++
cpp/tests/binaryop/binop-compiled-fixed_point-test.cpp
Matt711/cudf
b8521c336a59dd651b6db17d5c0902a0886ac324
[ "Apache-2.0" ]
1
2022-03-04T16:36:48.000Z
2022-03-04T16:36:48.000Z
cpp/tests/binaryop/binop-compiled-fixed_point-test.cpp
Matt711/cudf
b8521c336a59dd651b6db17d5c0902a0886ac324
[ "Apache-2.0" ]
1
2022-02-28T05:17:59.000Z
2022-02-28T05:17:59.000Z
cpp/tests/binaryop/binop-compiled-fixed_point-test.cpp
abhishesh/cudf
4c9ef5161268e2486938546deef00f7fc84c9a95
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cudf/binaryop.hpp> #include <cudf/detail/iterator.cuh> #include <cudf/fixed_point/fixed_point.hpp> #include <cudf/scalar/scalar_factories.hpp> #include <cudf/types.hpp> #include <cudf/unary.hpp> #include <cudf/utilities/type_dispatcher.hpp> #include <cudf_test/column_utilities.hpp> #include <cudf_test/column_wrapper.hpp> #include <cudf_test/type_lists.hpp> #include "cudf/utilities/error.hpp" #include <tests/binaryop/assert-binops.h> #include <tests/binaryop/binop-fixture.hpp> namespace cudf::test::binop { template <typename T> struct FixedPointCompiledTest : public cudf::test::BaseFixture { }; template <typename T> using wrapper = cudf::test::fixed_width_column_wrapper<T>; TYPED_TEST_SUITE(FixedPointCompiledTest, cudf::test::FixedPointTypes); TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd) { using namespace numeric; using decimalXX = TypeParam; auto const sz = std::size_t{1000}; auto begin = cudf::detail::make_counting_transform_iterator(1, [](auto i) { return decimalXX{i, scale_type{0}}; }); auto const vec1 = std::vector<decimalXX>(begin, begin + sz); auto const vec2 = std::vector<decimalXX>(sz, decimalXX{2, scale_type{0}}); auto expected = std::vector<decimalXX>(sz); std::transform(std::cbegin(vec1), std::cend(vec1), std::cbegin(vec2), std::begin(expected), std::plus<decimalXX>()); auto const lhs = wrapper<decimalXX>(vec1.begin(), vec1.end()); auto const rhs = wrapper<decimalXX>(vec2.begin(), vec2.end()); auto const expected_col = wrapper<decimalXX>(expected.begin(), expected.end()); auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::ADD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_col, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpMultiply) { using namespace numeric; using decimalXX = TypeParam; auto const sz = std::size_t{1000}; auto begin = cudf::detail::make_counting_transform_iterator(1, [](auto i) { return decimalXX{i, scale_type{0}}; }); auto const vec1 = std::vector<decimalXX>(begin, begin + sz); auto const vec2 = std::vector<decimalXX>(sz, decimalXX{2, scale_type{0}}); auto expected = std::vector<decimalXX>(sz); std::transform(std::cbegin(vec1), std::cend(vec1), std::cbegin(vec2), std::begin(expected), std::multiplies<decimalXX>()); auto const lhs = wrapper<decimalXX>(vec1.begin(), vec1.end()); auto const rhs = wrapper<decimalXX>(vec2.begin(), vec2.end()); auto const expected_col = wrapper<decimalXX>(expected.begin(), expected.end()); auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::MUL, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::MUL, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected_col, result->view()); } template <typename T> using fp_wrapper = cudf::test::fixed_point_column_wrapper<T>; TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpMultiply2) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}}; auto const rhs = fp_wrapper<RepType>{{10, 10, 10, 10, 10}, scale_type{0}}; auto const expected = fp_wrapper<RepType>{{110, 220, 330, 440, 550}, scale_type{-1}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::MUL, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::MUL, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpDiv) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{-1}}; auto const rhs = fp_wrapper<RepType>{{4, 4, 4, 4}, scale_type{0}}; auto const expected = fp_wrapper<RepType>{{2, 7, 12, 17}, scale_type{-1}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::DIV, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpDiv2) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{-1}}; auto const rhs = fp_wrapper<RepType>{{4, 4, 4, 4}, scale_type{-2}}; auto const expected = fp_wrapper<RepType>{{2, 7, 12, 17}, scale_type{1}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::DIV, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpDiv3) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{-1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(12, scale_type{-1}); auto const expected = fp_wrapper<RepType>{{0, 2, 4, 5}, scale_type{0}}; auto const type = cudf::binary_operation_fixed_point_output_type( cudf::binary_operator::DIV, static_cast<cudf::column_view>(lhs).type(), rhs->type()); auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpDiv4) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto begin = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return i * 11; }); auto result_begin = cudf::detail::make_counting_transform_iterator(0, [](auto i) { return (i * 11) / 12; }); auto const lhs = fp_wrapper<RepType>(begin, begin + 1000, scale_type{-1}); auto const rhs = make_fixed_point_scalar<decimalXX>(12, scale_type{-1}); auto const expected = fp_wrapper<RepType>(result_begin, result_begin + 1000, scale_type{0}); auto const type = cudf::binary_operation_fixed_point_output_type( cudf::binary_operator::DIV, static_cast<cudf::column_view>(lhs).type(), rhs->type()); auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd2) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}}; auto const rhs = fp_wrapper<RepType>{{100, 200, 300, 400, 500}, scale_type{-2}}; auto const expected = fp_wrapper<RepType>{{210, 420, 630, 840, 1050}, scale_type{-2}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::ADD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd3) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{1100, 2200, 3300, 4400, 5500}, scale_type{-3}}; auto const rhs = fp_wrapper<RepType>{{100, 200, 300, 400, 500}, scale_type{-2}}; auto const expected = fp_wrapper<RepType>{{2100, 4200, 6300, 8400, 10500}, scale_type{-3}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::ADD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd4) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(100, scale_type{-2}); auto const expected = fp_wrapper<RepType>{{210, 320, 430, 540, 650}, scale_type{-2}}; auto const type = cudf::binary_operation_fixed_point_output_type( cudf::binary_operator::ADD, static_cast<cudf::column_view>(lhs).type(), rhs->type()); auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::ADD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd5) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = make_fixed_point_scalar<decimalXX>(100, scale_type{-2}); auto const rhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}}; auto const expected = fp_wrapper<RepType>{{210, 320, 430, 540, 650}, scale_type{-2}}; auto const type = cudf::binary_operation_fixed_point_output_type( cudf::binary_operator::ADD, lhs->type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(*lhs, rhs, cudf::binary_operator::ADD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpAdd6) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const col = fp_wrapper<RepType>{{30, 4, 5, 6, 7, 8}, scale_type{0}}; auto const expected1 = fp_wrapper<RepType>{{60, 8, 10, 12, 14, 16}, scale_type{0}}; auto const expected2 = fp_wrapper<RepType>{{6, 0, 1, 1, 1, 1}, scale_type{1}}; auto const type1 = cudf::data_type{cudf::type_to_id<decimalXX>(), 0}; auto const type2 = cudf::data_type{cudf::type_to_id<decimalXX>(), 1}; auto const result1 = cudf::binary_operation(col, col, cudf::binary_operator::ADD, type1); auto const result2 = cudf::binary_operation(col, col, cudf::binary_operator::ADD, type2); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected2, result2->view()); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected1, result1->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointCast) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const col = fp_wrapper<RepType>{{6, 8, 10, 12, 14, 16}, scale_type{0}}; auto const expected = fp_wrapper<RepType>{{0, 0, 1, 1, 1, 1}, scale_type{1}}; auto const type = cudf::data_type{cudf::type_to_id<decimalXX>(), 1}; auto const result = cudf::cast(col, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpMultiplyScalar) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{11, 22, 33, 44, 55}, scale_type{-1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(100, scale_type{-1}); auto const expected = fp_wrapper<RepType>{{1100, 2200, 3300, 4400, 5500}, scale_type{-2}}; auto const type = cudf::binary_operation_fixed_point_output_type( cudf::binary_operator::MUL, static_cast<cudf::column_view>(lhs).type(), rhs->type()); auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::MUL, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpSimplePlus) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{150, 200}, scale_type{-2}}; auto const rhs = fp_wrapper<RepType>{{2250, 1005}, scale_type{-3}}; auto const expected = fp_wrapper<RepType>{{3750, 3005}, scale_type{-3}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::ADD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualSimple) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const trues = std::vector<bool>(4, true); auto const col1 = fp_wrapper<RepType>{{1, 2, 3, 4}, scale_type{0}}; auto const col2 = fp_wrapper<RepType>{{100, 200, 300, 400}, scale_type{-2}}; auto const expected = wrapper<bool>(trues.begin(), trues.end()); auto const result = cudf::binary_operation(col1, col2, binary_operator::EQUAL, cudf::data_type{type_id::BOOL8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualSimpleScale0) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const trues = std::vector<bool>(4, true); auto const col = fp_wrapper<RepType>{{1, 2, 3, 4}, scale_type{0}}; auto const expected = wrapper<bool>(trues.begin(), trues.end()); auto const result = cudf::binary_operation(col, col, binary_operator::EQUAL, cudf::data_type{type_id::BOOL8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualSimpleScale0Null) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const col1 = fp_wrapper<RepType>{{1, 2, 3, 4}, {1, 1, 1, 1}, scale_type{0}}; auto const col2 = fp_wrapper<RepType>{{1, 2, 3, 4}, {0, 0, 0, 0}, scale_type{0}}; auto const expected = wrapper<bool>{{0, 1, 0, 1}, {0, 0, 0, 0}}; auto const result = cudf::binary_operation(col1, col2, binary_operator::EQUAL, cudf::data_type{type_id::BOOL8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualSimpleScale2Null) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const col1 = fp_wrapper<RepType>{{1, 2, 3, 4}, {1, 1, 1, 1}, scale_type{-2}}; auto const col2 = fp_wrapper<RepType>{{1, 2, 3, 4}, {0, 0, 0, 0}, scale_type{0}}; auto const expected = wrapper<bool>{{0, 1, 0, 1}, {0, 0, 0, 0}}; auto const result = cudf::binary_operation(col1, col2, binary_operator::EQUAL, cudf::data_type{type_id::BOOL8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpEqualLessGreater) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const sz = std::size_t{1000}; // TESTING binary op ADD auto begin = cudf::detail::make_counting_transform_iterator(1, [](auto e) { return e * 1000; }); auto const vec1 = std::vector<RepType>(begin, begin + sz); auto const vec2 = std::vector<RepType>(sz, 0); auto const iota_3 = fp_wrapper<RepType>(vec1.begin(), vec1.end(), scale_type{-3}); auto const zeros_3 = fp_wrapper<RepType>(vec2.begin(), vec2.end(), scale_type{-1}); auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::ADD, static_cast<cudf::column_view>(iota_3).type(), static_cast<cudf::column_view>(zeros_3).type()); auto const iota_3_after_add = cudf::binary_operation(zeros_3, iota_3, binary_operator::ADD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(iota_3, iota_3_after_add->view()); // TESTING binary op EQUAL, LESS, GREATER auto const trues = std::vector<bool>(sz, true); auto const true_col = wrapper<bool>(trues.begin(), trues.end()); auto const btype = cudf::data_type{type_id::BOOL8}; auto const equal_result = cudf::binary_operation(iota_3, iota_3_after_add->view(), binary_operator::EQUAL, btype); CUDF_TEST_EXPECT_COLUMNS_EQUAL(true_col, equal_result->view()); auto const less_result = cudf::binary_operation(zeros_3, iota_3_after_add->view(), binary_operator::LESS, btype); CUDF_TEST_EXPECT_COLUMNS_EQUAL(true_col, less_result->view()); auto const greater_result = cudf::binary_operation(iota_3_after_add->view(), zeros_3, binary_operator::GREATER, btype); CUDF_TEST_EXPECT_COLUMNS_EQUAL(true_col, greater_result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpNullMaxSimple) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const trues = std::vector<bool>(4, true); auto const col1 = fp_wrapper<RepType>{{40, 30, 20, 10, 0}, {1, 0, 1, 1, 0}, scale_type{-2}}; auto const col2 = fp_wrapper<RepType>{{10, 20, 30, 40, 0}, {1, 1, 1, 0, 0}, scale_type{-2}}; auto const expected = fp_wrapper<RepType>{{40, 20, 30, 10, 0}, {1, 1, 1, 1, 0}, scale_type{-2}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::NULL_MAX, static_cast<cudf::column_view>(col1).type(), static_cast<cudf::column_view>(col2).type()); auto const result = cudf::binary_operation(col1, col2, binary_operator::NULL_MAX, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpNullMinSimple) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const trues = std::vector<bool>(4, true); auto const col1 = fp_wrapper<RepType>{{40, 30, 20, 10, 0}, {1, 1, 1, 0, 0}, scale_type{-1}}; auto const col2 = fp_wrapper<RepType>{{10, 20, 30, 40, 0}, {1, 0, 1, 1, 0}, scale_type{-1}}; auto const expected = fp_wrapper<RepType>{{10, 30, 20, 40, 0}, {1, 1, 1, 1, 0}, scale_type{-1}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::NULL_MIN, static_cast<cudf::column_view>(col1).type(), static_cast<cudf::column_view>(col2).type()); auto const result = cudf::binary_operation(col1, col2, binary_operator::NULL_MIN, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpNullEqualsSimple) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const trues = std::vector<bool>(4, true); auto const col1 = fp_wrapper<RepType>{{400, 300, 300, 100}, {1, 1, 1, 0}, scale_type{-2}}; auto const col2 = fp_wrapper<RepType>{{40, 200, 20, 400}, {1, 0, 1, 0}, scale_type{-1}}; auto const expected = wrapper<bool>{{1, 0, 0, 1}, {1, 1, 1, 1}}; auto const result = cudf::binary_operation( col1, col2, binary_operator::NULL_EQUALS, cudf::data_type{type_id::BOOL8}); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{100, 300, 500, 700}, scale_type{-2}}; auto const rhs = fp_wrapper<RepType>{{4, 4, 4, 4}, scale_type{0}}; auto const expected = fp_wrapper<RepType>{{25, 75, 125, 175}, scale_type{-2}}; auto const type = data_type{type_to_id<decimalXX>(), -2}; auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div2) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{100000, 300000, 500000, 700000}, scale_type{-3}}; auto const rhs = fp_wrapper<RepType>{{20, 20, 20, 20}, scale_type{-1}}; auto const expected = fp_wrapper<RepType>{{5000, 15000, 25000, 35000}, scale_type{-2}}; auto const type = data_type{type_to_id<decimalXX>(), -2}; auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div3) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{10000, 30000, 50000, 70000}, scale_type{-2}}; auto const rhs = fp_wrapper<RepType>{{3, 9, 3, 3}, scale_type{0}}; auto const expected = fp_wrapper<RepType>{{3333, 3333, 16666, 23333}, scale_type{-2}}; auto const type = data_type{type_to_id<decimalXX>(), -2}; auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div4) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(3, scale_type{0}); auto const expected = fp_wrapper<RepType>{{3, 10, 16, 23}, scale_type{1}}; auto const type = data_type{type_to_id<decimalXX>(), 1}; auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div6) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = make_fixed_point_scalar<decimalXX>(3000, scale_type{-3}); auto const rhs = fp_wrapper<RepType>{{10, 30, 50, 70}, scale_type{-1}}; auto const expected = fp_wrapper<RepType>{{300, 100, 60, 42}, scale_type{-2}}; auto const type = data_type{type_to_id<decimalXX>(), -2}; auto const result = cudf::binary_operation(*lhs, rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div7) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = make_fixed_point_scalar<decimalXX>(1200, scale_type{0}); auto const rhs = fp_wrapper<RepType>{{100, 200, 300, 500, 600, 800, 1200, 1300}, scale_type{-2}}; auto const expected = fp_wrapper<RepType>{{12, 6, 4, 2, 2, 1, 1, 0}, scale_type{2}}; auto const type = data_type{type_to_id<decimalXX>(), 2}; auto const result = cudf::binary_operation(*lhs, rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div8) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{4000, 6000, 80000}, scale_type{-1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(5000, scale_type{-3}); auto const expected = fp_wrapper<RepType>{{0, 1, 16}, scale_type{2}}; auto const type = data_type{type_to_id<decimalXX>(), 2}; auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div9) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{10, 20, 30}, scale_type{2}}; auto const rhs = make_fixed_point_scalar<decimalXX>(7, scale_type{1}); auto const expected = fp_wrapper<RepType>{{1, 2, 4}, scale_type{1}}; auto const type = data_type{type_to_id<decimalXX>(), 1}; auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div10) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{100, 200, 300}, scale_type{1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(7, scale_type{0}); auto const expected = fp_wrapper<RepType>{{14, 28, 42}, scale_type{1}}; auto const type = data_type{type_to_id<decimalXX>(), 1}; auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOp_Div11) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{1000, 2000, 3000}, scale_type{1}}; auto const rhs = fp_wrapper<RepType>{{7, 7, 7}, scale_type{0}}; auto const expected = fp_wrapper<RepType>{{142, 285, 428}, scale_type{1}}; auto const type = data_type{type_to_id<decimalXX>(), 1}; auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::DIV, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpThrows) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const col = fp_wrapper<RepType>{{100, 300, 500, 700}, scale_type{-2}}; auto const non_bool_type = data_type{type_to_id<decimalXX>(), -2}; EXPECT_THROW(cudf::binary_operation(col, col, cudf::binary_operator::LESS, non_bool_type), cudf::logic_error); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpModSimple) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{-33, -22, -11, 11, 22, 33, 44, 55}, scale_type{-1}}; auto const rhs = fp_wrapper<RepType>{{10, 10, 10, 10, 10, 10, 10, 10}, scale_type{-1}}; auto const expected = fp_wrapper<RepType>{{-3, -2, -1, 1, 2, 3, 4, 5}, scale_type{-1}}; auto const type = cudf::binary_operation_fixed_point_output_type(cudf::binary_operator::MOD, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, cudf::binary_operator::MOD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpPModSimple) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{-33, -22, -11, 11, 22, 33, 44, 55}, scale_type{-1}}; auto const rhs = fp_wrapper<RepType>{{10, 10, 10, 10, 10, 10, 10, 10}, scale_type{-1}}; auto const expected = fp_wrapper<RepType>{{7, 8, 9, 1, 2, 3, 4, 5}, scale_type{-1}}; for (auto const op : {cudf::binary_operator::PMOD, cudf::binary_operator::PYMOD}) { auto const type = cudf::binary_operation_fixed_point_output_type( op, static_cast<cudf::column_view>(lhs).type(), static_cast<cudf::column_view>(rhs).type()); auto const result = cudf::binary_operation(lhs, rhs, op, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpModSimple2) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{-33, -22, -11, 11, 22, 33, 44, 55}, scale_type{-1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(10, scale_type{-1}); auto const expected = fp_wrapper<RepType>{{-3, -2, -1, 1, 2, 3, 4, 5}, scale_type{-1}}; auto const type = cudf::binary_operation_fixed_point_output_type( cudf::binary_operator::MOD, static_cast<cudf::column_view>(lhs).type(), rhs->type()); auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::MOD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpPModAndPyModSimple2) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto const lhs = fp_wrapper<RepType>{{-33, -22, -11, 11, 22, 33, 44, 55}, scale_type{-1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(10, scale_type{-1}); auto const expected = fp_wrapper<RepType>{{7, 8, 9, 1, 2, 3, 4, 5}, scale_type{-1}}; for (auto const op : {cudf::binary_operator::PMOD, cudf::binary_operator::PYMOD}) { auto const type = cudf::binary_operation_fixed_point_output_type( op, static_cast<cudf::column_view>(lhs).type(), rhs->type()); auto const result = cudf::binary_operation(lhs, *rhs, op, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpMod) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto constexpr N = 1000; for (auto scale : {-1, -2, -3}) { auto const iota = thrust::make_counting_iterator(-500); auto const lhs = fp_wrapper<RepType>{iota, iota + N, scale_type{-1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(7, scale_type{scale}); auto const factor = static_cast<int>(std::pow(10, -1 - scale)); auto const f = [factor](auto i) { return (i * factor) % 7; }; auto const exp_iter = cudf::detail::make_counting_transform_iterator(-500, f); auto const expected = fp_wrapper<RepType>{exp_iter, exp_iter + N, scale_type{scale}}; auto const type = cudf::binary_operation_fixed_point_output_type( cudf::binary_operator::MOD, static_cast<cudf::column_view>(lhs).type(), rhs->type()); auto const result = cudf::binary_operation(lhs, *rhs, cudf::binary_operator::MOD, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } TYPED_TEST(FixedPointCompiledTest, FixedPointBinaryOpPModAndPyMod) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; auto constexpr N = 1000; for (auto const scale : {-1, -2, -3}) { auto const iota = thrust::make_counting_iterator(-500); auto const lhs = fp_wrapper<RepType>{iota, iota + N, scale_type{-1}}; auto const rhs = make_fixed_point_scalar<decimalXX>(7, scale_type{scale}); auto const factor = static_cast<int>(std::pow(10, -1 - scale)); auto const f = [factor](auto i) { return (((i * factor) % 7) + 7) % 7; }; auto const exp_iter = cudf::detail::make_counting_transform_iterator(-500, f); auto const expected = fp_wrapper<RepType>{exp_iter, exp_iter + N, scale_type{scale}}; for (auto const op : {cudf::binary_operator::PMOD, cudf::binary_operator::PYMOD}) { auto const type = cudf::binary_operation_fixed_point_output_type( op, static_cast<cudf::column_view>(lhs).type(), rhs->type()); auto const result = cudf::binary_operation(lhs, *rhs, op, type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(expected, result->view()); } } } template <typename T> struct FixedPointTest_64_128_Reps : public cudf::test::BaseFixture { }; using Decimal64And128Types = cudf::test::Types<numeric::decimal64, numeric::decimal128>; TYPED_TEST_SUITE(FixedPointTest_64_128_Reps, Decimal64And128Types); TYPED_TEST(FixedPointTest_64_128_Reps, FixedPoint_64_128_ComparisonTests) { using namespace numeric; using decimalXX = TypeParam; using RepType = device_storage_type_t<decimalXX>; for (auto const rhs_value : {10000000000000000, 100000000000000000}) { auto const lhs = fp_wrapper<RepType>{{33041, 97290, 36438, 25379, 48473}, scale_type{2}}; auto const rhs = make_fixed_point_scalar<decimalXX>(rhs_value, scale_type{0}); auto const trues = wrapper<bool>{{1, 1, 1, 1, 1}}; auto const falses = wrapper<bool>{{0, 0, 0, 0, 0}}; auto const bool_type = cudf::data_type{type_id::BOOL8}; auto const a = cudf::binary_operation(lhs, *rhs, binary_operator::LESS, bool_type); auto const b = cudf::binary_operation(lhs, *rhs, binary_operator::LESS_EQUAL, bool_type); auto const c = cudf::binary_operation(lhs, *rhs, binary_operator::GREATER, bool_type); auto const d = cudf::binary_operation(lhs, *rhs, binary_operator::GREATER_EQUAL, bool_type); auto const e = cudf::binary_operation(*rhs, lhs, binary_operator::GREATER, bool_type); auto const f = cudf::binary_operation(*rhs, lhs, binary_operator::GREATER_EQUAL, bool_type); auto const g = cudf::binary_operation(*rhs, lhs, binary_operator::LESS, bool_type); auto const h = cudf::binary_operation(*rhs, lhs, binary_operator::LESS_EQUAL, bool_type); CUDF_TEST_EXPECT_COLUMNS_EQUAL(a->view(), trues); CUDF_TEST_EXPECT_COLUMNS_EQUAL(b->view(), trues); CUDF_TEST_EXPECT_COLUMNS_EQUAL(c->view(), falses); CUDF_TEST_EXPECT_COLUMNS_EQUAL(d->view(), falses); CUDF_TEST_EXPECT_COLUMNS_EQUAL(e->view(), trues); CUDF_TEST_EXPECT_COLUMNS_EQUAL(f->view(), trues); CUDF_TEST_EXPECT_COLUMNS_EQUAL(g->view(), falses); CUDF_TEST_EXPECT_COLUMNS_EQUAL(h->view(), falses); } } } // namespace cudf::test::binop
42.350117
100
0.693948
[ "vector", "transform" ]
33618ef90317cde945e448b3d7b0175e57106a54
8,743
hh
C++
dune/xt/functions/checkerboard.hh
renefritze/dune-xt-functions
aea4ef43bb0177466be2ec3cb56e3f4f5ced2c25
[ "BSD-2-Clause" ]
null
null
null
dune/xt/functions/checkerboard.hh
renefritze/dune-xt-functions
aea4ef43bb0177466be2ec3cb56e3f4f5ced2c25
[ "BSD-2-Clause" ]
1
2018-07-09T10:57:27.000Z
2018-07-09T10:57:27.000Z
dune/xt/functions/checkerboard.hh
TiKeil/dune-xt-functions
aea4ef43bb0177466be2ec3cb56e3f4f5ced2c25
[ "BSD-2-Clause" ]
null
null
null
// This file is part of the dune-xt-functions project: // https://github.com/dune-community/dune-xt-functions // Copyright 2009-2018 dune-xt-functions developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Andreas Buhr (2014) // Felix Schindler (2012 - 2018) // René Fritze (2013 - 2018) // TiKeil (2018) // Tobias Leibner (2014 - 2017) #ifndef DUNE_XT_FUNCTIONS_CHECKERBOARD_HH #define DUNE_XT_FUNCTIONS_CHECKERBOARD_HH #include <dune/xt/common/configuration.hh> #include <dune/xt/functions/interfaces/grid-function.hh> namespace Dune { namespace XT { namespace Functions { /** * Note: This function does not allow for functions on the subdomains anymore. Only constant values are possible. */ template <class E, size_t r = 1, size_t rC = 1, class R = double> class CheckerboardFunction : public GridFunctionInterface<E, r, rC, R> { using BaseType = GridFunctionInterface<E, r, rC, R>; using ThisType = CheckerboardFunction<E, r, rC, R>; using BaseType::domain_dim; static_assert(domain_dim <= 3, "Not implemented for domain_dim > 3 (see find_subdomain method)!"); class LocalCheckerboardFunction : public ElementFunctionInterface<E, r, rC, R> { using InterfaceType = ElementFunctionInterface<E, r, rC, R>; public: using typename InterfaceType::DerivativeRangeReturnType; using typename InterfaceType::DerivativeRangeType; using typename InterfaceType::DomainType; using typename InterfaceType::ElementType; using typename InterfaceType::RangeReturnType; using typename InterfaceType::RangeType; using GeometryType = typename ElementType::Geometry; LocalCheckerboardFunction(const DomainType& lower_left, const DomainType& upper_right, const FieldVector<size_t, domain_dim>& num_elements, std::vector<RangeType>& values) : InterfaceType() , lower_left_(lower_left) , upper_right_(upper_right) , num_elements_(num_elements) , values_(values) {} protected: void post_bind(const ElementType& element) override final { current_value_ = 0; if (is_in_checkerboard(element)) { const size_t subdomain = find_subdomain(element); current_value_ = values_[subdomain]; } } public: int order(const Common::Parameter& /*param*/ = {}) const override final { return 0; } RangeReturnType evaluate(const DomainType& point_in_reference_element, const Common::Parameter& /*param*/ = {}) const override final { this->assert_inside_reference_element(point_in_reference_element); return current_value_; } DerivativeRangeReturnType jacobian(const DomainType& point_in_reference_element, const Common::Parameter& /*param*/ = {}) const override final { this->assert_inside_reference_element(point_in_reference_element); return DerivativeRangeReturnType(); } private: bool is_in_checkerboard(const ElementType& element) const { const auto center = element.geometry().center(); if (Common::FloatCmp::le(lower_left_, center) && Common::FloatCmp::lt(center, upper_right_)) return 1; else return 0; } size_t find_subdomain(const ElementType& element) const { // decide to which subdomain the center of the element belongs to const auto center = element.geometry().center(); std::vector<size_t> which_partition(domain_dim, 0); const auto& ll = lower_left_; const auto& ur = upper_right_; const auto& ne = num_elements_; for (size_t dd = 0; dd < domain_dim; ++dd) { // for points that are on upper_right_[d], this selects one partition too much // so we need to cap this which_partition[dd] = std::min(size_t(std::floor(ne[dd] * ((center[dd] - ll[dd]) / (ur[dd] - ll[dd])))), ne[dd] - 1); } size_t subdomain = 0; if (domain_dim == 1) subdomain = which_partition[0]; else if (domain_dim == 2) subdomain = which_partition[0] + which_partition[1] * ne[0]; else subdomain = which_partition[0] + which_partition[1] * ne[0] + which_partition[2] * ne[1] * ne[0]; return subdomain; } // ... find_subdomain(...) const DomainType lower_left_; const DomainType upper_right_; const FieldVector<size_t, domain_dim> num_elements_; const std::vector<RangeType>& values_; RangeType current_value_; }; // class LocalCheckerboardFunction public: using typename BaseType::ElementType; using typename BaseType::LocalFunctionType; using RangeType = typename LocalFunctionType::RangeType; using DomainType = typename LocalFunctionType::DomainType; static const bool available = true; static std::string static_id() { return BaseType::static_id() + ".checkerboard"; } static Common::Configuration defaults() { Common::Configuration config; config["lower_left"] = "[0.0 0.0 0.0]"; config["upper_right"] = "[1.0 1.0 1.0]"; config["num_elements"] = "[2 2 2]"; config["values"] = "[1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0]"; config["name"] = static_id(); return config; } // ... defaults(...) CheckerboardFunction(const DomainType& lower_left, const DomainType& upper_right, const FieldVector<size_t, domain_dim>& num_elements, const std::vector<RangeType>& values, const std::string nm = "checkerboard") : lower_left_(lower_left) , upper_right_(upper_right) , num_elements_(num_elements) , values_(new std::vector<RangeType>(values)) , name_(nm) { #ifndef NDEBUG // checks size_t total_subdomains = 1; for (size_t dd = 0; dd < domain_dim; ++dd) { const auto& ll = (lower_left_)[dd]; const auto& ur = (upper_right_)[dd]; const auto& ne = (num_elements_)[dd]; if (!(ll < ur)) DUNE_THROW(Dune::RangeError, "lower_left has to be elementwise smaller than upper_right!"); total_subdomains *= ne; } if (values_->size() < total_subdomains) DUNE_THROW(Dune::RangeError, "values too small (is " << values_->size() << ", should be " << total_subdomains << ")"); #endif } // CheckerboardFunction(...) CheckerboardFunction(const ThisType& other) = default; CheckerboardFunction(ThisType&& source) = default; ThisType& operator=(const ThisType& other) = delete; ThisType& operator=(ThisType&& source) = delete; std::string name() const override { return name_; } std::unique_ptr<LocalFunctionType> local_function() const override final { return std::make_unique<LocalCheckerboardFunction>(lower_left_, upper_right_, num_elements_, *values_); } size_t subdomain(const ElementType& element) const { return find_subdomain(element); } size_t subdomains() const { return values_->size(); } const std::vector<std::shared_ptr<const RangeType>>& values() const { return values_; } private: size_t find_subdomain(const ElementType& element) const { // decide on the subdomain the center of the element belongs to const auto center = element.geometry().center(); std::vector<size_t> which_partition(domain_dim, 0); const auto& ll = lower_left_; const auto& ur = upper_right_; const auto& ne = num_elements_; for (size_t dd = 0; dd < domain_dim; ++dd) { // for points that are on upper_right_[d], this selects one partition too much // so we need to cap this which_partition[dd] = std::min(size_t(std::floor(ne[dd] * ((center[dd] - ll[dd]) / (ur[dd] - ll[dd])))), ne[dd] - 1); } size_t subdomain = 0; if (domain_dim == 1) subdomain = which_partition[0]; else if (domain_dim == 2) subdomain = which_partition[0] + which_partition[1] * ne[0]; else subdomain = which_partition[0] + which_partition[1] * ne[0] + which_partition[2] * ne[1] * ne[0]; return subdomain; } // ... find_subdomain(...) const DomainType lower_left_; const DomainType upper_right_; const FieldVector<size_t, domain_dim> num_elements_; std::shared_ptr<std::vector<RangeType>> values_; std::string name_; }; // class CheckerboardFunction } // namespace Functions } // namespace XT } // namespace Dune #endif // DUNE_XT_FUNCTIONS_CHECKERBOARD_HH
34.286275
113
0.659613
[ "geometry", "vector" ]
3362073b4ece704ce5fb3a1b3b236cc47b0e6514
2,088
cpp
C++
kmercode/bound.cpp
camaclean/bella
c80c012cda05bc15b69db7fd54424823f75b5a21
[ "BSD-3-Clause-LBNL" ]
8
2021-01-29T09:07:10.000Z
2022-02-11T13:17:45.000Z
kmercode/bound.cpp
camaclean/bella
c80c012cda05bc15b69db7fd54424823f75b5a21
[ "BSD-3-Clause-LBNL" ]
5
2020-12-04T20:45:08.000Z
2022-03-28T12:31:51.000Z
kmercode/bound.cpp
camaclean/bella
c80c012cda05bc15b69db7fd54424823f75b5a21
[ "BSD-3-Clause-LBNL" ]
3
2021-04-17T00:32:59.000Z
2021-11-25T12:14:38.000Z
#include <iostream> #include <cstdio> #include <cstdlib> #include <fstream> #include <istream> #include <vector> #include <string> #include <stdlib.h> #include <algorithm> #include <utility> #include <array> #include <tuple> #include <queue> #include <memory> #include <stack> #include <functional> #include <cstring> #include <string.h> #include <cassert> #include <ios> #include <sys/stat.h> #include <sys/types.h> #include <sys/sysctl.h> #include <math.h> #include <map> #include <omp.h> #include "bound.hpp" // GG: parallel factorial long double factorial(long double number) { long double fac = 1; #pragma omp parallel for reduction(*:fac) for(int n = 2; n <= (int)number; ++n) fac *= n; return fac; } // GG: depth, error rate, and k-mer length int computeUpper(int myCoverage, double errorRate, int kmerSize, double minProbability) { long double a, b, c; long double dfact = factorial(myCoverage); long double bbase = (1-errorRate); long double cbase = (1-pow(bbase, kmerSize)); long double probability = 1; long double sum = 0, prev; int m = myCoverage; while(sum < minProbability) { a = dfact / (factorial(m) * factorial(myCoverage - m)); b = pow(bbase, (m * kmerSize)); c = pow(cbase, (myCoverage - m)); probability = a * b * c; sum = sum + probability; if(sum == prev && sum < minProbability) break; --m; prev = sum; } return (m+1); } // GG: depth, error rate, and k-mer length int computeLower(int myCoverage, double errorRate, int kmerSize, double minProbability) { long double a, b, c; long double dfact = factorial(myCoverage); long double bbase = (1-errorRate); long double cbase = (1-pow(bbase, kmerSize)); long double probability = 1; long double sum = 0, prev; int mymin = 2; int m = mymin; while(sum < minProbability) { a = dfact / (factorial(m) * factorial(myCoverage - m)); b = pow(bbase, (m * kmerSize)); c = pow(cbase, (myCoverage - m)); probability = a * b * c; sum = sum + probability; if(sum == prev && sum < minProbability) break; ++m; prev = sum; } return std::max(m-1, mymin); }
20.88
87
0.662356
[ "vector" ]
336bc9527e4aac7c48ff8703f345e2e9e5ae782b
4,125
cc
C++
common/swaglog.cc
Pistachio504/openpilot
2bb5df8ff722918ccc6361a8f588f8447a9cce36
[ "MIT" ]
null
null
null
common/swaglog.cc
Pistachio504/openpilot
2bb5df8ff722918ccc6361a8f588f8447a9cce36
[ "MIT" ]
null
null
null
common/swaglog.cc
Pistachio504/openpilot
2bb5df8ff722918ccc6361a8f588f8447a9cce36
[ "MIT" ]
null
null
null
#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include "common/swaglog.h" #include <cassert> #include <cstring> #include <limits> #include <mutex> #include <string> #include <zmq.h> #include "json11.hpp" #include "common/util.h" #include "common/version.h" #include "selfdrive/hardware/hw.h" class SwaglogState : public LogState { public: SwaglogState() : LogState("ipc:///tmp/logmessage") {} json11::Json::object ctx_j; inline void initialize() { ctx_j = json11::Json::object {}; print_level = CLOUDLOG_WARNING; const char* print_lvl = getenv("LOGPRINT"); if (print_lvl) { if (strcmp(print_lvl, "debug") == 0) { print_level = CLOUDLOG_DEBUG; } else if (strcmp(print_lvl, "info") == 0) { print_level = CLOUDLOG_INFO; } else if (strcmp(print_lvl, "warning") == 0) { print_level = CLOUDLOG_WARNING; } } // openpilot bindings char* dongle_id = getenv("DONGLE_ID"); if (dongle_id) { ctx_j["dongle_id"] = dongle_id; } char* daemon_name = getenv("MANAGER_DAEMON"); if (daemon_name) { ctx_j["daemon"] = daemon_name; } ctx_j["version"] = COMMA_VERSION; ctx_j["dirty"] = !getenv("CLEAN"); // device type if (Hardware::EON()) { ctx_j["device"] = "eon"; } else if (Hardware::TICI()) { ctx_j["device"] = "tici"; } else { ctx_j["device"] = "pc"; } LogState::initialize(); } }; static SwaglogState s = {}; bool LOG_TIMESTAMPS = getenv("LOG_TIMESTAMPS"); uint32_t NO_FRAME_ID = std::numeric_limits<uint32_t>::max(); static void log(int levelnum, const char* filename, int lineno, const char* func, const char* msg, const std::string& log_s) { if (levelnum >= s.print_level) { printf("%s: %s\n", filename, msg); } char levelnum_c = levelnum; zmq_send(s.sock, (levelnum_c + log_s).c_str(), log_s.length() + 1, ZMQ_NOBLOCK); } static void cloudlog_common(int levelnum, const char* filename, int lineno, const char* func, char* msg_buf, json11::Json::object msg_j={}) { std::lock_guard lk(s.lock); if (!s.initialized) s.initialize(); json11::Json::object log_j = json11::Json::object { {"ctx", s.ctx_j}, {"levelnum", levelnum}, {"filename", filename}, {"lineno", lineno}, {"funcname", func}, {"created", seconds_since_epoch()} }; if (msg_j.empty()) { log_j["msg"] = msg_buf; } else { log_j["msg"] = msg_j; } std::string log_s = ((json11::Json)log_j).dump(); log(levelnum, filename, lineno, func, msg_buf, log_s); free(msg_buf); } void cloudlog_e(int levelnum, const char* filename, int lineno, const char* func, const char* fmt, ...) { va_list args; va_start(args, fmt); char* msg_buf = nullptr; int ret = vasprintf(&msg_buf, fmt, args); va_end(args); if (ret <= 0 || !msg_buf) return; cloudlog_common(levelnum, filename, lineno, func, msg_buf); } void cloudlog_t_common(int levelnum, const char* filename, int lineno, const char* func, uint32_t frame_id, const char* fmt, va_list args) { if (!LOG_TIMESTAMPS) return; char* msg_buf = nullptr; int ret = vasprintf(&msg_buf, fmt, args); if (ret <= 0 || !msg_buf) return; json11::Json::object tspt_j = json11::Json::object{ {"event", msg_buf}, {"time", std::to_string(nanos_since_boot())} }; if (frame_id < NO_FRAME_ID) { tspt_j["frame_id"] = std::to_string(frame_id); } tspt_j = json11::Json::object{{"timestamp", tspt_j}}; cloudlog_common(levelnum, filename, lineno, func, msg_buf, tspt_j); } void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func, const char* fmt, ...) { va_list args; va_start(args, fmt); cloudlog_t_common(levelnum, filename, lineno, func, NO_FRAME_ID, fmt, args); va_end(args); } void cloudlog_te(int levelnum, const char* filename, int lineno, const char* func, uint32_t frame_id, const char* fmt, ...) { va_list args; va_start(args, fmt); cloudlog_t_common(levelnum, filename, lineno, func, frame_id, fmt, args); va_end(args); }
28.846154
126
0.634667
[ "object" ]
336d0ece8c8943a4e70bff50e08a6b7b48f06596
1,574
cpp
C++
Source/XsollaLogin/Private/XsollaLogin.cpp
xsolla/store-ue4-sdk
e25440e9d0b82663929ee7f49807e9b6bb09606b
[ "Apache-2.0" ]
14
2019-08-28T19:49:07.000Z
2021-12-04T14:34:18.000Z
Source/XsollaLogin/Private/XsollaLogin.cpp
xsolla/inventory-ue4-sdk
bbe8fbc7384c0c34992145329a4dbd61aa3ae362
[ "Apache-2.0" ]
34
2019-08-17T08:23:18.000Z
2021-12-08T08:25:14.000Z
Source/XsollaLogin/Private/XsollaLogin.cpp
xsolla/store-ue4-sdk
e25440e9d0b82663929ee7f49807e9b6bb09606b
[ "Apache-2.0" ]
12
2019-09-25T15:14:58.000Z
2022-03-21T09:27:58.000Z
// Copyright 2021 Xsolla Inc. All Rights Reserved. #include "XsollaLogin.h" #include "XsollaLoginDefines.h" #include "XsollaLoginSettings.h" #include "Developer/Settings/Public/ISettingsModule.h" #define LOCTEXT_NAMESPACE "FXsollaLoginModule" const FName FXsollaLoginModule::ModuleName = "XsollaLogin"; void FXsollaLoginModule::StartupModule() { XsollaLoginSettings = NewObject<UXsollaLoginSettings>(GetTransientPackage(), "XsollaLoginSettings", RF_Standalone); XsollaLoginSettings->AddToRoot(); // Register settings if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings")) { SettingsModule->RegisterSettings("Project", "Plugins", ModuleName, LOCTEXT("RuntimeSettingsName", "Xsolla Login"), LOCTEXT("RuntimeSettingsDescription", "Configure Xsolla Login"), XsollaLoginSettings); } UE_LOG(LogXsollaLogin, Log, TEXT("%s: XsollaLogin module started"), *VA_FUNC_LINE); } void FXsollaLoginModule::ShutdownModule() { if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings")) { SettingsModule->UnregisterSettings("Project", "Plugins", ModuleName); } if (!GExitPurge) { // If we're in exit purge, this object has already been destroyed XsollaLoginSettings->RemoveFromRoot(); } else { XsollaLoginSettings = nullptr; } } UXsollaLoginSettings* FXsollaLoginModule::GetSettings() const { check(XsollaLoginSettings); return XsollaLoginSettings; } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FXsollaLoginModule, XsollaLogin) DEFINE_LOG_CATEGORY(LogXsollaLogin);
26.233333
116
0.782719
[ "object" ]
336e0ec2b62f88848cfdbaacdfb1a26a0362333d
9,079
cpp
C++
cocos/renderer/CCTextureCube.cpp
cocos2d-cpp/mini
1ba95aee89ac421890f70f168d22ae6a3a2bbd13
[ "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "BSD-3-Clause-No-Nuclear-License-2014", "MIT-0", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
cocos/renderer/CCTextureCube.cpp
cocos2d-cpp/mini
1ba95aee89ac421890f70f168d22ae6a3a2bbd13
[ "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "BSD-3-Clause-No-Nuclear-License-2014", "MIT-0", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
cocos/renderer/CCTextureCube.cpp
cocos2d-cpp/mini
1ba95aee89ac421890f70f168d22ae6a3a2bbd13
[ "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "BSD-3-Clause-No-Nuclear-License-2014", "MIT-0", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
/**************************************************************************** Copyright (c) 2015 Chukong Technologies Inc. http://www.cocos2d-x.org 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 "renderer/CCTextureCube.h" #include "platform/CCImage.h" #include "platform/CCFileUtils.h" #include "renderer/ccGLStateCache.h" namespace cocos2d { unsigned char* getImageData(Image* img, Texture2D::PixelFormat& ePixFmt) { unsigned char* pTmpData = img->getData(); unsigned int* inPixel32 = nullptr; unsigned char* inPixel8 = nullptr; unsigned short* outPixel16 = nullptr; bool bHasAlpha = img->hasAlpha(); size_t uBPP = img->getBitPerPixel(); int nWidth = img->getWidth(); int nHeight = img->getHeight(); // compute pixel format if (bHasAlpha) { ePixFmt = Texture2D::PixelFormat::DEFAULT; } else { if (uBPP >= 8) { ePixFmt = Texture2D::PixelFormat::RGB888; } else { ePixFmt = Texture2D::PixelFormat::RGB565; } } // Repack the pixel data into the right format unsigned int uLen = nWidth * nHeight; if (ePixFmt == Texture2D::PixelFormat::RGB565) { if (bHasAlpha) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" inPixel32 = (unsigned int*)img->getData(); pTmpData = new (std::nothrow) unsigned char[nWidth * nHeight * 2]; outPixel16 = (unsigned short*)pTmpData; for (unsigned int i = 0; i < uLen; ++i, ++inPixel32) { *outPixel16++ = ((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | // R ((((*inPixel32 >> 8) & 0xFF) >> 2) << 5) | // G ((((*inPixel32 >> 16) & 0xFF) >> 3) << 0); // B } } else { // Convert "RRRRRRRRGGGGGGGGBBBBBBBB" to "RRRRRGGGGGGBBBBB" pTmpData = new (std::nothrow) unsigned char[nWidth * nHeight * 2]; outPixel16 = (unsigned short*)pTmpData; inPixel8 = (unsigned char*)img->getData(); for (unsigned int i = 0; i < uLen; ++i) { unsigned char R = *inPixel8++; unsigned char G = *inPixel8++; unsigned char B = *inPixel8++; *outPixel16++ = ((R >> 3) << 11) | // R ((G >> 2) << 5) | // G ((B >> 3) << 0); // B } } } if (bHasAlpha && ePixFmt == Texture2D::PixelFormat::RGB888) { // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRRRRGGGGGGGGBBBBBBBB" inPixel32 = (unsigned int*)img->getData(); pTmpData = new (std::nothrow) unsigned char[nWidth * nHeight * 3]; unsigned char* outPixel8 = pTmpData; for (unsigned int i = 0; i < uLen; ++i, ++inPixel32) { *outPixel8++ = (*inPixel32 >> 0) & 0xFF; // R *outPixel8++ = (*inPixel32 >> 8) & 0xFF; // G *outPixel8++ = (*inPixel32 >> 16) & 0xFF; // B } } return pTmpData; } Image* createImage(const std::string& path) { // Split up directory and filename // MUTEX: // Needed since addImageAsync calls this method from a different thread std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path); if (fullpath.size() == 0) { return nullptr; } // all images are handled by UIImage except PVR extension that is handled by our own handler Image* image = nullptr; do { image = new (std::nothrow) Image(); CC_BREAK_IF(nullptr == image); bool bRet = image->initWithImageFile(fullpath); CC_BREAK_IF(!bRet); } while (0); return image; } TextureCube::TextureCube() { _imgPath.resize(6); } TextureCube::~TextureCube() { } TextureCube* TextureCube::create(const std::string& positive_x, const std::string& negative_x, const std::string& positive_y, const std::string& negative_y, const std::string& positive_z, const std::string& negative_z) { auto ret = new (std::nothrow) TextureCube(); if (ret && ret->init(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z)) { ret->autorelease(); return ret; } CC_SAFE_DELETE(ret); return nullptr; } bool TextureCube::init(const std::string& positive_x, const std::string& negative_x, const std::string& positive_y, const std::string& negative_y, const std::string& positive_z, const std::string& negative_z) { _imgPath[0] = positive_x; _imgPath[1] = negative_x; _imgPath[2] = positive_y; _imgPath[3] = negative_y; _imgPath[4] = positive_z; _imgPath[5] = negative_z; std::vector<Image*> images(6); images[0] = createImage(positive_x); images[1] = createImage(negative_x); images[2] = createImage(positive_y); images[3] = createImage(negative_y); images[4] = createImage(positive_z); images[5] = createImage(negative_z); GLuint handle; glGenTextures(1, &handle); GL::bindTextureN(0, handle, GL_TEXTURE_CUBE_MAP); for (int i = 0; i < 6; i++) { Image* img = images[i]; Texture2D::PixelFormat ePixelFmt; unsigned char* pData = getImageData(img, ePixelFmt); if (ePixelFmt == Texture2D::PixelFormat::RGBA8888 || ePixelFmt == Texture2D::PixelFormat::DEFAULT) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, // level GL_RGBA, // internal format img->getWidth(), // width img->getHeight(), // height 0, // border GL_RGBA, // format GL_UNSIGNED_BYTE, // type pData); // pixel data } else if (ePixelFmt == Texture2D::PixelFormat::RGB888) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, // level GL_RGB, // internal format img->getWidth(), // width img->getHeight(), // height 0, // border GL_RGB, // format GL_UNSIGNED_BYTE, // type pData); // pixel data } if (pData != img->getData()) delete[] pData; } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); _name = handle; GL::bindTextureN(0, 0, GL_TEXTURE_CUBE_MAP); for (auto img: images) { CC_SAFE_RELEASE(img); } return true; } void TextureCube::setTexParameters(const TexParams& texParams) { CC_ASSERT(_name != 0); GL::bindTextureN(0, _name, GL_TEXTURE_CUBE_MAP); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, texParams.minFilter); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, texParams.magFilter); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, texParams.wrapS); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, texParams.wrapT); GL::bindTextureN(0, 0, GL_TEXTURE_CUBE_MAP); } bool TextureCube::reloadTexture() { return init(_imgPath[0], _imgPath[1], _imgPath[2], _imgPath[3], _imgPath[4], _imgPath[5]); } } // namespace cocos2d
33.750929
106
0.569226
[ "vector" ]
33707dce5b080fd12a484a889f8cdec63a6c00e3
1,547
cc
C++
test/mutex.cc
mcx/XNNPACK
4aa243068e71f1064e8db37f6240e4c85f1f5314
[ "BSD-3-Clause" ]
null
null
null
test/mutex.cc
mcx/XNNPACK
4aa243068e71f1064e8db37f6240e4c85f1f5314
[ "BSD-3-Clause" ]
null
null
null
test/mutex.cc
mcx/XNNPACK
4aa243068e71f1064e8db37f6240e4c85f1f5314
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2022 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <thread> #include <random> #include <xnnpack.h> #include <xnnpack/common.h> #include <xnnpack/mutex.h> #include <gtest/gtest.h> TEST(MUTEX, init_lock_unlock_destroy) { xnn_mutex m; ASSERT_EQ(xnn_status_success, xnn_mutex_init(&m)); ASSERT_EQ(xnn_status_success, xnn_mutex_lock(&m)); ASSERT_EQ(xnn_status_success, xnn_mutex_unlock(&m)); ASSERT_EQ(xnn_status_success, xnn_mutex_destroy(&m)); } TEST(MUTEX, counter) { // Skip if we are not targeting pthread. #if XNN_PLATFORM_WEB && !defined(__EMSCRIPTEN_PTHREADS__) GTEST_SKIP(); #endif xnn_mutex m; constexpr size_t num_threads = 50; std::vector<std::thread> threads; threads.reserve(num_threads); volatile size_t counter = 0; std::random_device random_device; auto rng = std::mt19937(random_device()); auto dist = std::uniform_int_distribution<int>(100, 200); ASSERT_EQ(xnn_status_success, xnn_mutex_init(&m)); for (size_t i = 0; i < num_threads; i++) { threads.emplace_back(([&] () { ASSERT_EQ(xnn_status_success, xnn_mutex_lock(&m)); std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng))); counter += 1; ASSERT_EQ(xnn_status_success, xnn_mutex_unlock(&m)); })); } for (int i = num_threads - 1; i >= 0; i--) { threads[i].join(); } ASSERT_EQ(counter, num_threads); ASSERT_EQ(xnn_status_success, xnn_mutex_destroy(&m)); }
26.672414
72
0.709761
[ "vector" ]
337424311092ee2539e7c7c6101dcffffff110e0
8,006
cc
C++
src/trusted/sel_universal/rpc_universal_system.cc
kapkic/native_client
51c8bc8c249d55606232ae011bdfc8b4cab3d794
[ "BSD-3-Clause" ]
1
2021-12-23T00:36:43.000Z
2021-12-23T00:36:43.000Z
src/trusted/sel_universal/rpc_universal_system.cc
kapkic/native_client
51c8bc8c249d55606232ae011bdfc8b4cab3d794
[ "BSD-3-Clause" ]
null
null
null
src/trusted/sel_universal/rpc_universal_system.cc
kapkic/native_client
51c8bc8c249d55606232ae011bdfc8b4cab3d794
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <fcntl.h> #include <string.h> #if NACL_LINUX && !NACL_ANDROID // for shmem cleanup #include <sys/ipc.h> #include <sys/shm.h> #include "native_client/src/trusted/desc/linux/nacl_desc_sysv_shm.h" #endif #include <map> #include <string> #include <sstream> using std::stringstream; #include "native_client/src/shared/platform/nacl_log.h" #include "native_client/src/trusted/desc/nacl_desc_base.h" #include "native_client/src/trusted/desc/nacl_desc_sync_socket.h" #include "native_client/src/trusted/desc/nacl_desc_wrapper.h" #include "native_client/src/trusted/sel_universal/parsing.h" #include "native_client/src/trusted/sel_universal/rpc_universal.h" #include "native_client/src/trusted/service_runtime/include/sys/fcntl.h" namespace { const uintptr_t k64KBytes = 0x10000; // The main point of this class is to ensure automatic cleanup. // If the destructor is not invoked you need to manually cleanup // the shared memory descriptors via "ipcs -m" and "ipcrm -m <id>" class AddressMap { public: AddressMap() {} ~AddressMap() { // NOTE: you CANNOT call NaClLog - this is called too late // NaClLog(1, "cleanup\n"); #if NACL_LINUX && !NACL_ANDROID typedef map<NaClDesc*, uintptr_t>::iterator IT; for (IT it = map_.begin(); it != map_.end(); ++it) { shmctl(reinterpret_cast<NaClDescSysvShm*>(it->first)->id, IPC_RMID, NULL); } #endif } void Add(NaClDesc* desc, uintptr_t addr) { map_[desc] = addr; } uintptr_t Get(NaClDesc* desc) { return map_[desc]; } private: map<NaClDesc*, uintptr_t> map_; }; AddressMap GlobalAddressMap; } // namespace bool HandlerSyncSocketCreate(NaClCommandLoop* ncl, const vector<string>& args) { if (args.size() < 3) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } NaClHandle handles[2] = {NACL_INVALID_HANDLE, NACL_INVALID_HANDLE}; if (NaClSocketPair(handles) != 0) { return false; } nacl::DescWrapperFactory factory; nacl::DescWrapper* desc1 = factory.ImportSyncSocketHandle(handles[0]); ncl->AddDesc(desc1->desc(), args[1]); nacl::DescWrapper* desc2 = factory.ImportSyncSocketHandle(handles[1]); ncl->AddDesc(desc2->desc(), args[2]); return true; } bool HandlerSyncSocketWrite(NaClCommandLoop* ncl, const vector<string>& args) { if (args.size() < 3) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } NaClDesc* raw_desc = ExtractDesc(args[1], ncl); if (raw_desc == NULL) { NaClLog(LOG_ERROR, "cannot find desciptor %s\n", args[1].c_str()); return false; } const int value = ExtractInt32(args[2]); nacl::DescWrapperFactory factory; // TODO(robertm): eliminate use of NaClDesc in sel_universal and standardize // on DescWrapper to eliminate the memory leak here factory.MakeGeneric(raw_desc)->Write(&value, sizeof value); return true; } // create a descriptor representing a readonly file bool HandlerReadonlyFile(NaClCommandLoop* ncl, const vector<string>& args) { if (args.size() < 3) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } nacl::DescWrapperFactory factory; nacl::DescWrapper* desc = factory.OpenHostFile(args[2].c_str(), NACL_ABI_O_RDONLY, 0); if (NULL == desc) { NaClLog(LOG_ERROR, "cound not create file desc for %s\n", args[2].c_str()); return false; } ncl->AddDesc(desc->desc(), args[1]); return true; } // create a descriptor representing a read-write file. // Used for temporary files created by the pnacl translator. bool HandlerReadwriteFile(NaClCommandLoop* ncl, const vector<string>& args) { if (args.size() < 3) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } nacl::DescWrapperFactory factory; nacl::DescWrapper* desc = factory.OpenHostFile(args[2].c_str(), NACL_ABI_O_RDWR | NACL_ABI_O_CREAT, 0666); if (NULL == desc) { NaClLog(LOG_ERROR, "cound not create file desc for %s\n", args[2].c_str()); return false; } ncl->AddDesc(desc->desc(), args[1]); return true; } // create a descriptor representing a read-write file with quota management. bool HandlerReadwriteFileQuota(NaClCommandLoop* ncl, const vector<string>& args) { if (args.size() < 3) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } static const uint8_t kFileId[] = "SelUniversal000"; nacl::DescWrapperFactory factory; nacl::DescWrapper* desc = factory.OpenHostFileQuota(args[2].c_str(), NACL_ABI_O_RDWR | NACL_ABI_O_CREAT, 0666, kFileId); if (NULL == desc) { NaClLog(LOG_ERROR, "cound not create file desc for %s\n", args[2].c_str()); return false; } ncl->AddDesc(desc->desc(), args[1]); return true; } // sleep for a given number of seconds bool HandlerSleep(NaClCommandLoop* ncl, const vector<string>& args) { UNREFERENCED_PARAMETER(ncl); if (args.size() < 2) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } const int secs = ExtractInt32(args[1]); #if (NACL_LINUX || NACL_OSX) sleep(secs); #elif NACL_WINDOWS Sleep(secs * 1000); #else #error "Please specify platform as NACL_LINUX, NACL_OSX or NACL_WINDOWS" #endif return true; } // save a memory region to a file bool HandlerSaveToFile(NaClCommandLoop* ncl, const vector<string>& args) { UNREFERENCED_PARAMETER(ncl); if (args.size() < 5) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } const char* filename = args[1].c_str(); const char* start = reinterpret_cast<char*>(ExtractInt64(args[2])); const int offset = ExtractInt32(args[3]); const int size = ExtractInt32(args[4]); NaClLog(1, "opening %s\n", filename); FILE* fp = fopen(filename, "wb"); if (fp == NULL) { NaClLog(LOG_ERROR, "cannot open %s\n", filename); return false; } NaClLog(1, "writing %d bytes from %p\n", (int) size, start + offset); const size_t n = fwrite(start + offset, 1, size, fp); if (static_cast<int>(n) != size) { NaClLog(LOG_ERROR, "wrote %d bytes, expected %d\n", static_cast<int>(n), size); fclose(fp); return false; } fclose(fp); return true; } // load file into memory region bool HandlerLoadFromFile(NaClCommandLoop* ncl, const vector<string>& args) { UNREFERENCED_PARAMETER(ncl); if (args.size() < 5) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } const char* filename = args[1].c_str(); char* start = reinterpret_cast<char*>(ExtractInt64(args[2])); const int offset = ExtractInt32(args[3]); const int size = ExtractInt32(args[4]); NaClLog(1, "opening %s\n", filename); FILE* fp = fopen(filename, "rb"); if (fp == NULL) { NaClLog(LOG_ERROR, "cannot open %s\n", filename); return false; } NaClLog(1, "loading %d bytes to %p\n", (int) size, start + offset); const size_t n = fread(start + offset, 1, size, fp); if (static_cast<int>(n) != size) { NaClLog(LOG_ERROR, "read %d bytes, expected %d\n", static_cast<int>(n), size); fclose(fp); return false; } fclose(fp); return true; } // Determine filesize and write it into a variable bool HandlerFileSize(NaClCommandLoop* ncl, const vector<string>& args) { UNREFERENCED_PARAMETER(ncl); if (args.size() < 3) { NaClLog(LOG_ERROR, "not enough args\n"); return false; } const char* filename = args[1].c_str(); FILE* fp = fopen(filename, "rb"); if (fp == NULL) { NaClLog(LOG_ERROR, "cannot open %s\n", filename); return false; } fseek(fp, 0, SEEK_END); int size = static_cast<int>(ftell(fp)); fclose(fp); NaClLog(1, "filesize is %d\n", size); stringstream str; str << size; ncl->SetVariable(args[2], str.str()); return true; }
29.112727
80
0.663128
[ "vector" ]
337446ee86dadac24311a08682f28115b66cc11d
3,358
cxx
C++
smtk/extension/qt/qtOverlay.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
smtk/extension/qt/qtOverlay.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
4
2016-11-10T15:49:51.000Z
2017-02-06T23:24:16.000Z
smtk/extension/qt/qtOverlay.cxx
yumin/SMTK
d280f10c5b70953b2a0196f71832955c7fc75e7f
[ "BSD-3-Clause-Clear" ]
null
null
null
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/extension/qt/qtOverlay.h" #include <QHBoxLayout> #include <QLabel> #include <QPainter> #include <QEvent> #include <QComboBox> #include <QStringList> using namespace smtk::attribute; qtOverlay::qtOverlay(QWidget * parentW ) : QWidget(parentW) { setAttribute(Qt::WA_NoSystemBackground); //setAttribute(Qt::WA_TransparentForMouseEvents); new QHBoxLayout(this); this->layout()->setAlignment(Qt::AlignRight); this->layout()->setMargin(0); this->m_overlayColor = QColor(80, 80, 255, 128); } void qtOverlay::addOverlayWidget(QWidget*w) { if(w) { w->setAttribute(Qt::WA_NoSystemBackground); w->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QString strStyle(" QWidget { background-color: rgba("); strStyle.append(QString::number(this->m_overlayColor.red()) + ", ") .append(QString::number(this->m_overlayColor.green()) + ", ") .append(QString::number(this->m_overlayColor.blue()) + ", ") .append(QString::number(this->m_overlayColor.alpha()) + ") } "); w->setStyleSheet(w->styleSheet() + strStyle); this->layout()->addWidget(w); } } void qtOverlay::paintEvent(QPaintEvent *) { QPainter p(this); p.fillRect(rect(), this->m_overlayColor); } //---------------------------------------------------------------------------- qtOverlayFilter::qtOverlayFilter(QWidget* onWidget, QObject * parentO) : QObject(parentO) { m_Active = true; m_overlay = new qtOverlay(onWidget->parentWidget()); m_overlay->setGeometry(onWidget->geometry()); m_overlayOn = onWidget; onWidget->installEventFilter(this); } //---------------------------------------------------------------------------- qtOverlayFilter::~qtOverlayFilter() { delete this->m_overlay; } void qtOverlayFilter::setActive(bool val) { if (m_overlay && m_overlayOn) { m_overlay->setGeometry(m_overlayOn->geometry()); } this->m_overlay->setVisible(val); this->m_Active = val; } void qtOverlayFilter::addOverlayWidget(QWidget*w) { m_overlay->addOverlayWidget(w); } bool qtOverlayFilter::eventFilter(QObject * obj, QEvent * ev) { if (!obj->isWidgetType()) { return false; } if(this->m_overlay) { this->m_overlay->setVisible(this->m_Active); } if(!this->m_Active) { return false; } QWidget * w = static_cast<QWidget*>(obj); if (ev->type() == QEvent::Paint || ev->type() == QEvent::Show) { if (!m_overlay) { m_overlay = new qtOverlay(w->parentWidget()); m_overlay->setGeometry(w->geometry()); m_overlayOn = w; } if (m_overlay && m_overlayOn == w) { m_overlay->setGeometry(w->geometry()); m_overlay->show(); // m_overlay->repaint(); } } else if (ev->type() == QEvent::Resize) { if (m_overlay && m_overlayOn == w) { m_overlay->setGeometry(w->geometry()); } } return false; }
27.52459
89
0.597379
[ "geometry" ]
33752a1f9230f8d37e964811ba859a15899e7d22
1,974
cpp
C++
third-party/llvm/llvm-src/lib/CodeGen/LowLevelType.cpp
nldias/chapel
3a63044cd50b639dca8e851d4a505546b57bc299
[ "ECL-2.0", "Apache-2.0" ]
1,602
2015-01-06T11:26:31.000Z
2022-03-30T06:17:21.000Z
third-party/llvm/llvm-src/lib/CodeGen/LowLevelType.cpp
nldias/chapel
3a63044cd50b639dca8e851d4a505546b57bc299
[ "ECL-2.0", "Apache-2.0" ]
11,789
2015-01-05T04:50:15.000Z
2022-03-31T23:39:19.000Z
third-party/llvm/llvm-src/lib/CodeGen/LowLevelType.cpp
nldias/chapel
3a63044cd50b639dca8e851d4a505546b57bc299
[ "ECL-2.0", "Apache-2.0" ]
498
2015-01-08T18:58:18.000Z
2022-03-20T15:37:45.000Z
//===-- llvm/CodeGen/LowLevelType.cpp -------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// \file This file implements the more header-heavy bits of the LLT class to /// avoid polluting users' namespaces. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/LowLevelType.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; LLT llvm::getLLTForType(Type &Ty, const DataLayout &DL) { if (auto VTy = dyn_cast<VectorType>(&Ty)) { auto NumElements = cast<FixedVectorType>(VTy)->getNumElements(); LLT ScalarTy = getLLTForType(*VTy->getElementType(), DL); if (NumElements == 1) return ScalarTy; return LLT::vector(NumElements, ScalarTy); } if (auto PTy = dyn_cast<PointerType>(&Ty)) { unsigned AddrSpace = PTy->getAddressSpace(); return LLT::pointer(AddrSpace, DL.getPointerSizeInBits(AddrSpace)); } if (Ty.isSized()) { // Aggregates are no different from real scalars as far as GlobalISel is // concerned. auto SizeInBits = DL.getTypeSizeInBits(&Ty); assert(SizeInBits != 0 && "invalid zero-sized type"); return LLT::scalar(SizeInBits); } return LLT(); } MVT llvm::getMVTForLLT(LLT Ty) { if (!Ty.isVector()) return MVT::getIntegerVT(Ty.getSizeInBits()); return MVT::getVectorVT( MVT::getIntegerVT(Ty.getElementType().getSizeInBits()), Ty.getNumElements()); } LLT llvm::getLLTForMVT(MVT Ty) { if (!Ty.isVector()) return LLT::scalar(Ty.getSizeInBits()); return LLT::vector(Ty.getVectorNumElements(), Ty.getVectorElementType().getSizeInBits()); }
32.360656
80
0.618034
[ "vector" ]
33779062d194f0116e5694d979f56f293e1aaa36
971
cpp
C++
C++/push-dominoes.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/push-dominoes.cpp
pnandini/LeetCode
e746c3298be96dec8e160da9378940568ef631b1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/push-dominoes.cpp
pnandini/LeetCode
e746c3298be96dec8e160da9378940568ef631b1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) // Space: O(n) class Solution { public: string pushDominoes(string dominoes) { vector<int> force(dominoes.length()); int f = 0; for (int i = 0; i < dominoes.length(); ++i) { if (dominoes[i] == 'R') { f = dominoes.length(); } else if (dominoes[i] == 'L') { f = 0; } else { f = max(f - 1, 0); } force[i] += f; } f = 0; for (int i = dominoes.length() - 1; i >= 0; --i) { if (dominoes[i] == 'L') { f = dominoes.length(); } else if (dominoes[i] == 'R') { f = 0; } else { f = max(f - 1, 0); } force[i] -= f; } string result; for (const auto& f : force) { result.push_back((f == 0) ? '.' : ((f > 0) ? 'R' : 'L')); } return result; } };
24.897436
69
0.347065
[ "vector" ]
337b81b5fa8e953b0e45e2b80d3aba2e11661e1c
3,306
cc
C++
third_party/incubator-tvm/src/relay/pass/combine_parallel_dense.cc
KnowingNothing/akg-test
114d8626b824b9a31af50a482afc07ab7121862b
[ "Apache-2.0" ]
286
2020-06-23T06:40:44.000Z
2022-03-30T01:27:49.000Z
third_party/incubator-tvm/src/relay/pass/combine_parallel_dense.cc
KnowingNothing/akg-test
114d8626b824b9a31af50a482afc07ab7121862b
[ "Apache-2.0" ]
10
2020-07-31T03:26:59.000Z
2021-12-27T15:00:54.000Z
third_party/incubator-tvm/src/relay/pass/combine_parallel_dense.cc
KnowingNothing/akg-test
114d8626b824b9a31af50a482afc07ab7121862b
[ "Apache-2.0" ]
30
2020-07-17T01:04:14.000Z
2021-12-27T14:05:19.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * * \file combine_parallel_dense.cc * \brief Combine parallel dense ops into a single dense. * * This pass replaces dense ops that share the same input node, same shape, * and don't have "units" defined with a single batch matrix multiplication. * The inputs of the new batch_matmul is the stack of the original inputs. * Elemwise and broadcast ops following dense are also combined if possible. * * This prevents launching multiple kernels in networks with multiple * dense branches, such as BERT. */ #include <tvm/relay/analysis.h> #include <tvm/relay/expr_functor.h> #include <tvm/relay/attrs/nn.h> #include <tvm/relay/attrs/transform.h> #include <tvm/relay/op_attr_types.h> #include <tvm/relay/transform.h> #include <unordered_map> #include <unordered_set> #include "./expr_subst.h" #include "./pattern_util.h" #include "./combine_parallel_op_batch.h" namespace air { namespace relay { class ParallelDenseCombiner : public ParallelOpBatchCombiner { public: explicit ParallelDenseCombiner(uint64_t min_num_branches) : ParallelOpBatchCombiner("nn.dense", "nn.batch_matmul", min_num_branches) { } protected: virtual bool CanOpsBeCombined(const CallNode* a, const CallNode* b) { AttrsEqual eq; const auto* attrs_a = a->attrs.as<DenseAttrs>(); const auto* attrs_b = b->attrs.as<DenseAttrs>(); CHECK(attrs_a); CHECK(attrs_b); const auto* weight_a = a->args[1]->type_as<TensorTypeNode>(); const auto* weight_b = b->args[1]->type_as<TensorTypeNode>(); return eq(attrs_a->out_dtype, attrs_b->out_dtype) && eq(weight_a->shape[0], weight_b->shape[0]) && eq(weight_a->shape[1], weight_b->shape[1]); } }; /*! \brief Combine parallel dense if number of branches >= min_num_branches */ Expr CombineParallelDense(const Expr& expr, uint64_t min_num_branches) { return ParallelDenseCombiner(min_num_branches).Combine(expr); } namespace transform { Pass CombineParallelDense(uint64_t min_num_branches) { runtime::TypedPackedFunc<Function(Function, Module, PassContext)> pass_func = [=](Function f, Module m, PassContext pc) { return Downcast<Function>(CombineParallelDense(f, min_num_branches)); }; return CreateFunctionPass(pass_func, 4, "CombineParallelDense", {ir::StringImm::make("InferType")}); } TVM_REGISTER_API("relay._transform.CombineParallelDense") .set_body_typed(CombineParallelDense); } // namespace transform } // namespace relay } // namespace air
35.170213
80
0.732607
[ "shape", "transform" ]
337cfd057801a2b7ec1e1c9a60a3df4cbbb71f3f
15,408
cc
C++
ash/app_list/views/app_list_main_view_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
ash/app_list/views/app_list_main_view_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/app_list/views/app_list_main_view_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/app_list/views/app_list_main_view.h" #include <memory> #include <string> #include "ash/app_list/app_list_test_view_delegate.h" #include "ash/app_list/model/app_list_test_model.h" #include "ash/app_list/views/app_list_folder_view.h" #include "ash/app_list/views/app_list_item_view.h" #include "ash/app_list/views/app_list_view.h" #include "ash/app_list/views/apps_container_view.h" #include "ash/app_list/views/apps_grid_view.h" #include "ash/app_list/views/apps_grid_view_test_api.h" #include "ash/app_list/views/contents_view.h" #include "ash/app_list/views/page_switcher.h" #include "ash/app_list/views/paged_apps_grid_view.h" #include "ash/app_list/views/search_box_view.h" #include "ash/public/cpp/app_list/app_list_features.h" #include "ash/public/cpp/test/test_app_list_color_provider.h" #include "base/test/scoped_feature_list.h" #include "ui/compositor/layer.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/events/base_event_utils.h" #include "ui/events/keycodes/keyboard_codes_posix.h" #include "ui/events/types/event_type.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/test/button_test_api.h" #include "ui/views/test/views_test_base.h" #include "ui/views/view_model.h" #include "ui/views/widget/widget.h" namespace ash { namespace test { namespace { const int kInitialItems = 2; } // namespace class AppListMainViewTest : public views::ViewsTestBase, public testing::WithParamInterface<bool> { public: AppListMainViewTest() = default; AppListMainViewTest(const AppListMainViewTest& other) = delete; AppListMainViewTest& operator=(const AppListMainViewTest& other) = delete; ~AppListMainViewTest() override = default; // testing::Test overrides: void SetUp() override { views::ViewsTestBase::SetUp(); zero_duration_mode_ = std::make_unique<ui::ScopedAnimationDurationScaleMode>( ui::ScopedAnimationDurationScaleMode::ZERO_DURATION); // Allow TEST_F for tests that don't need to be parameterized. if (testing::UnitTest::GetInstance()->current_test_info()->value_param()) { feature_list_.InitWithFeatureState( app_list_features::kNewDragSpecInLauncher, GetParam()); } // Create, and show the app list is fullscreen apps grid state. delegate_ = std::make_unique<AppListTestViewDelegate>(); app_list_view_ = new AppListView(delegate_.get()); app_list_view_->InitView(GetContext()); app_list_view_->Show(AppListViewState::kFullscreenAllApps, /*is_side_shelf=*/false); EXPECT_TRUE(app_list_view_->GetWidget()->IsVisible()); } void TearDown() override { app_list_view_->GetWidget()->Close(); zero_duration_mode_.reset(); views::ViewsTestBase::TearDown(); } // |point| is in |grid_view|'s coordinates. AppListItemView* GetItemViewAtPointInGrid(AppsGridView* grid_view, const gfx::Point& point) { const auto& entries = grid_view->view_model()->entries(); const auto iter = std::find_if( entries.begin(), entries.end(), [&point](const auto& entry) { return entry.view->bounds().Contains(point); }); return iter == entries.end() ? nullptr : static_cast<AppListItemView*>(iter->view); } void SimulateKeyPress(ui::KeyboardCode key_code) { ui::KeyEvent key_press(ui::ET_KEY_PRESSED, key_code, ui::EF_NONE); app_list_view_->GetWidget()->OnKeyEvent(&key_press); ui::KeyEvent key_release(ui::ET_KEY_RELEASED, key_code, ui::EF_NONE); app_list_view_->GetWidget()->OnKeyEvent(&key_release); } void SimulateClick(views::View* view) { gfx::Point center = view->GetLocalBounds().CenterPoint(); views::View::ConvertPointToWidget(view, &center); ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON); view->GetWidget()->OnMouseEvent(&press_event); ui::MouseEvent release_event( ui::ET_MOUSE_RELEASED, center, center, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_RIGHT_MOUSE_BUTTON); view->GetWidget()->OnMouseEvent(&release_event); } // |point| is in |grid_view|'s coordinates. AppListItemView* SimulateInitiateDrag(AppsGridView* grid_view, const gfx::Point& point) { AppListItemView* view = GetItemViewAtPointInGrid(grid_view, point); DCHECK(view); // NOTE: Assumes that the app list view window bounds match the root window // bounds. gfx::Point root_window_point = point; views::View::ConvertPointToWidget(grid_view, &root_window_point); view->InitiateDrag(point, root_window_point); return view; } // |point| is in |grid_view|'s coordinates. void SimulateUpdateDrag(AppsGridView* grid_view, AppsGridView::Pointer pointer, AppListItemView* drag_view, const gfx::Point& point) { DCHECK(drag_view); // NOTE: Assumes that the app list view window bounds match the root window // bounds. gfx::Point root_window_point = point; views::View::ConvertPointToWidget(grid_view, &root_window_point); ui::MouseEvent drag_event(ui::ET_MOUSE_DRAGGED, point, root_window_point, ui::EventTimeForNow(), 0, 0); grid_view->UpdateDragFromItem(pointer, drag_event); } AppListMainView* main_view() { return app_list_view_->app_list_main_view(); } ContentsView* contents_view() { return main_view()->contents_view(); } SearchBoxView* search_box_view() { return main_view()->search_box_view(); } AppsGridView* GetRootGridView() { return contents_view()->apps_container_view()->apps_grid_view(); } AppListFolderView* GetFolderView() { return contents_view()->apps_container_view()->app_list_folder_view(); } PageSwitcher* GetPageSwitcherView() { return contents_view()->apps_container_view()->page_switcher(); } AppsGridView* GetFolderGridView() { return GetFolderView()->items_grid_view(); } const views::ViewModelT<AppListItemView>* GetRootViewModel() { return GetRootGridView()->view_model(); } const views::ViewModelT<AppListItemView>* GetFolderViewModel() { return GetFolderGridView()->view_model(); } AppListItemView* CreateAndOpenSingleItemFolder() { // Prepare single folder with a single item in it. AppListFolderItem* folder_item = delegate_->GetTestModel()->CreateSingleItemFolder("single_item_folder", "single"); GetRootGridView()->Layout(); EXPECT_EQ(folder_item, delegate_->GetTestModel()->FindFolderItem("single_item_folder")); EXPECT_EQ(AppListFolderItem::kItemType, folder_item->GetItemType()); EXPECT_EQ(1, GetRootViewModel()->view_size()); AppListItemView* folder_item_view = static_cast<AppListItemView*>(GetRootViewModel()->view_at(0)); EXPECT_EQ(folder_item_view->item(), folder_item); // Click on the folder to open it. EXPECT_FALSE(GetFolderView()->GetVisible()); SimulateClick(folder_item_view); EXPECT_TRUE(GetFolderView()->GetVisible()); return folder_item_view; } AppListItemView* StartDragForReparent(int index_in_folder) { // Start to drag the item in folder. views::View* item_view = GetFolderViewModel()->view_at(index_in_folder); AppListItemView* dragged = SimulateInitiateDrag( GetFolderGridView(), item_view->bounds().CenterPoint()); EXPECT_EQ(item_view, dragged); EXPECT_TRUE(GetRootGridView()->GetVisible()); EXPECT_TRUE(GetFolderView()->GetVisible()); // Drag the item completely outside the folder bounds. gfx::Point drag_target = gfx::Point(-(item_view->width() + 1) / 2, -(item_view->height() + 1) / 2); // Two update drags needed to actually drag the view. The first changes // state and the 2nd one actually moves the view. The 2nd call can be // removed when UpdateDrag is fixed. SimulateUpdateDrag(GetFolderGridView(), AppsGridView::MOUSE, dragged, drag_target); SimulateUpdateDrag(GetFolderGridView(), AppsGridView::MOUSE, dragged, drag_target); // Fire reparent timer, which should start when the item exits the folder // bounds. The timer closes the folder view. EXPECT_TRUE(GetFolderGridView()->FireFolderItemReparentTimerForTest()); // Note: the folder item is expected to remain visible so it keeps getting // drag events, but it should become completely transparent. EXPECT_TRUE(GetFolderView()->GetVisible()); EXPECT_EQ(0.0f, GetFolderGridView()->layer()->opacity()); return dragged; } bool IsPaginationPreviewActive() { return GetParam(); } void PressKeyInSearchBox(ui::KeyboardCode key_code) { ui::KeyEvent press(ui::ET_KEY_PRESSED, key_code, ui::EF_NONE); search_box_view()->search_box()->OnKeyEvent(&press); } void ClickButton(views::Button* button) { views::test::ButtonTestApi(button).NotifyClick(ui::MouseEvent( ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), base::TimeTicks(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON)); } protected: TestAppListColorProvider color_provider_; // Needed by AppListView. AppListView* app_list_view_ = nullptr; // Owned by native widget. std::unique_ptr<AppListTestViewDelegate> delegate_; private: base::test::ScopedFeatureList feature_list_; std::unique_ptr<ui::ScopedAnimationDurationScaleMode> zero_duration_mode_; }; INSTANTIATE_TEST_SUITE_P(All, AppListMainViewTest, testing::Bool()); // Tests that the close button becomes invisible after close button is clicked. TEST_F(AppListMainViewTest, CloseButtonInvisibleAfterCloseButtonClicked) { PressKeyInSearchBox(ui::VKEY_A); ClickButton(search_box_view()->close_button()); EXPECT_FALSE(search_box_view()->close_button()->GetVisible()); } // Tests that the search box becomes empty after close button is clicked. TEST_F(AppListMainViewTest, SearchBoxEmptyAfterCloseButtonClicked) { PressKeyInSearchBox(ui::VKEY_A); ClickButton(search_box_view()->close_button()); EXPECT_TRUE(search_box_view()->search_box()->GetText().empty()); } // Tests that the search box is no longer active after close button is clicked. TEST_F(AppListMainViewTest, SearchBoxActiveAfterCloseButtonClicked) { PressKeyInSearchBox(ui::VKEY_A); ClickButton(search_box_view()->close_button()); EXPECT_FALSE(search_box_view()->is_search_box_active()); } // Tests changing the AppListModel when switching profiles. TEST_P(AppListMainViewTest, ModelChanged) { delegate_->GetTestModel()->PopulateApps(kInitialItems); EXPECT_EQ(kInitialItems, GetRootViewModel()->view_size()); // The model is owned by a profile keyed service, which is never destroyed // until after profile switching. std::unique_ptr<AppListModel> old_model(delegate_->ReleaseTestModel()); std::unique_ptr<SearchModel> old_search_model( delegate_->ReleaseTestSearchModel()); const int kReplacementItems = 5; delegate_->ReplaceTestModel(kReplacementItems); EXPECT_EQ(kReplacementItems, GetRootViewModel()->view_size()); } // Tests dragging an item out of a single item folder and dropping it onto the // page switcher. Regression test for http://crbug.com/415530/. TEST_P(AppListMainViewTest, DragReparentItemOntoPageSwitcher) { AppListItemView* folder_item_view = CreateAndOpenSingleItemFolder(); ASSERT_TRUE(folder_item_view); // Number of apps to populate. Should provide more than 1 page of apps (5*4 = // 20). const int kNumApps = 30; delegate_->GetTestModel()->PopulateApps(kNumApps); GetRootGridView()->Layout(); EXPECT_EQ(1, GetFolderViewModel()->view_size()); EXPECT_EQ(kNumApps + 1, GetRootViewModel()->view_size()); AppListItemView* dragged = StartDragForReparent(0); // Drag the reparent item to the page switcher. gfx::Point point = GetPageSwitcherView()->GetLocalBounds().CenterPoint(); views::View::ConvertPointToTarget(GetPageSwitcherView(), GetFolderGridView(), &point); SimulateUpdateDrag(GetFolderGridView(), AppsGridView::MOUSE, dragged, point); // Drop it. GetFolderGridView()->EndDrag(false); // The folder should not be destroyed. EXPECT_EQ(kNumApps + 1, GetRootViewModel()->view_size()); AppListFolderItem* const folder_item = delegate_->GetTestModel()->FindFolderItem("single_item_folder"); ASSERT_TRUE(folder_item); EXPECT_EQ(1u, folder_item->item_list()->item_count()); } // Test that an interrupted drag while reparenting an item from a folder, when // canceled via the root grid, correctly forwards the cancelation to the drag // ocurring from the folder. TEST_P(AppListMainViewTest, MouseDragItemOutOfFolderWithCancel) { CreateAndOpenSingleItemFolder(); AppListItemView* dragged = StartDragForReparent(0); // Now add an item to the model, not in any folder, e.g., as if by Sync. EXPECT_TRUE(GetRootGridView()->has_dragged_item()); EXPECT_TRUE(GetFolderGridView()->has_dragged_item()); delegate_->GetTestModel()->CreateAndAddItem("Extra"); // The drag operation should get canceled. EXPECT_FALSE(GetRootGridView()->has_dragged_item()); EXPECT_FALSE(GetFolderGridView()->has_dragged_item()); // Additional mouse move operations should be ignored. gfx::Point point(1, 1); SimulateUpdateDrag(GetFolderGridView(), AppsGridView::MOUSE, dragged, point); EXPECT_FALSE(GetRootGridView()->has_dragged_item()); EXPECT_FALSE(GetFolderGridView()->has_dragged_item()); } // Test that dragging an app out of a single item folder and reparenting it // back into its original folder results in a cancelled reparent. This is a // regression test for http://crbug.com/429083. TEST_P(AppListMainViewTest, ReparentSingleItemOntoSelf) { // TODO(anasalazar): Fix for cardified state if (IsPaginationPreviewActive()) return; // Add a folder with 1 item. AppListItemView* folder_item_view = CreateAndOpenSingleItemFolder(); std::string folder_id = folder_item_view->item()->id(); // Add another top level app. delegate_->GetTestModel()->PopulateApps(1); gfx::Point drag_point = folder_item_view->bounds().CenterPoint(); views::View::ConvertPointToTarget(GetRootGridView(), GetFolderGridView(), &drag_point); AppListItemView* dragged = StartDragForReparent(0); // Drag the reparent item back into its folder. SimulateUpdateDrag(GetFolderGridView(), AppsGridView::MOUSE, dragged, drag_point); GetFolderGridView()->EndDrag(false); // The app list model should remain unchanged. EXPECT_EQ(2, GetRootViewModel()->view_size()); EXPECT_EQ(folder_id, GetRootGridView()->GetItemViewAt(0)->item()->id()); AppListFolderItem* const folder_item = delegate_->GetTestModel()->FindFolderItem("single_item_folder"); ASSERT_TRUE(folder_item); EXPECT_EQ(1u, folder_item->item_list()->item_count()); } } // namespace test } // namespace ash
39.71134
79
0.71742
[ "model" ]
3380272227965eace4a83aa85cac04a80caee9ae
2,212
cc
C++
test.cc
KnairdA/CodepointIterator
31f8cbdd0b038c7196f630febd2bbe2f9183cde0
[ "MIT" ]
1
2019-07-18T03:36:52.000Z
2019-07-18T03:36:52.000Z
test.cc
KnairdA/CodepointIterator
31f8cbdd0b038c7196f630febd2bbe2f9183cde0
[ "MIT" ]
null
null
null
test.cc
KnairdA/CodepointIterator
31f8cbdd0b038c7196f630febd2bbe2f9183cde0
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "src/codepoint_iterator.h" #include <string> struct SampleText { std::string text; size_t length; std::u32string codepoints; }; class CodepointIteratorTest : public ::testing::Test { protected: virtual void SetUp() { SampleText tmp; tmp.text = u8"Hellø Uni¢od€!"; tmp.codepoints = U"Hellø Uni¢od€!"; this->sample_.push_back(tmp); tmp.text = u8"ᛖᚴ ᚷᛖᛏ ᛖᛏᛁ ᚧ ᚷᛚᛖᚱ ᛘᚾ ᚦᛖᛋᛋ ᚨᚧ ᚡᛖ ᚱᚧᚨ ᛋᚨᚱ"; tmp.codepoints = U"ᛖᚴ ᚷᛖᛏ ᛖᛏᛁ ᚧ ᚷᛚᛖᚱ ᛘᚾ ᚦᛖᛋᛋ ᚨᚧ ᚡᛖ ᚱᚧᚨ ᛋᚨᚱ"; this->sample_.push_back(tmp); tmp.text = u8"⠊⠀⠉⠁⠝⠀⠑⠁⠞⠀⠛⠇⠁⠎⠎⠀⠁⠝⠙⠀⠊⠞⠀⠙⠕⠑⠎⠝⠞⠀⠓⠥⠗⠞⠀⠍⠑"; tmp.codepoints = U"⠊⠀⠉⠁⠝⠀⠑⠁⠞⠀⠛⠇⠁⠎⠎⠀⠁⠝⠙⠀⠊⠞⠀⠙⠕⠑⠎⠝⠞⠀⠓⠥⠗⠞⠀⠍⠑"; this->sample_.push_back(tmp); tmp.text = u8"Ég get etið gler án þess að meiða mig"; tmp.codepoints = U"Ég get etið gler án þess að meiða mig"; this->sample_.push_back(tmp); tmp.text = u8"جام ييه بلورم بڭا ضررى طوقونمز"; tmp.codepoints = U"جام ييه بلورم بڭا ضررى طوقونمز"; this->sample_.push_back(tmp); tmp.text = u8"මට වීදුරු කෑමට හැකියි. එයින් මට කිසි හානියක් සිදු නොවේ"; tmp.codepoints = U"මට වීදුරු කෑමට හැකියි. එයින් මට කිසි හානියක් සිදු නොවේ"; this->sample_.push_back(tmp); } std::vector<SampleText> sample_; }; TEST_F(CodepointIteratorTest, ForwardIteration) { for ( auto&& tmp : this->sample_ ) { size_t length = 0; for ( UTF8::CodepointIterator iter(tmp.text.cbegin()); iter != tmp.text.cend(); ++iter ) { length++; } EXPECT_EQ(tmp.codepoints.size(), length); } } TEST_F(CodepointIteratorTest, ReverseIteration) { for ( auto&& tmp : this->sample_ ) { size_t length = 0; for ( UTF8::CodepointIterator iter(tmp.text.cend()); iter != tmp.text.cbegin(); --iter ) { length++; } EXPECT_EQ(tmp.codepoints.size(), length); } } TEST_F(CodepointIteratorTest, Dereferencing) { for ( auto&& tmp : this->sample_ ) { size_t index = 0; for ( UTF8::CodepointIterator iter(tmp.text.cbegin()); iter != tmp.text.cend(); ++iter ) { EXPECT_EQ(tmp.codepoints[index], *iter); ++index; } } } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
24.043478
79
0.602622
[ "vector" ]
3381e7c498cfece1ef2237d1ccf2929f302ba56d
3,024
cc
C++
third_party/blink/renderer/modules/webgl/webgl_query.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/modules/webgl/webgl_query.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/modules/webgl/webgl_query.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/webgl/webgl_query.h" #include "gpu/command_buffer/client/gles2_interface.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h" namespace blink { WebGLQuery* WebGLQuery::Create(WebGL2RenderingContextBase* ctx) { return new WebGLQuery(ctx); } WebGLQuery::WebGLQuery(WebGL2RenderingContextBase* ctx) : WebGLSharedPlatform3DObject(ctx), target_(0), can_update_availability_(false), query_result_available_(false), query_result_(0) { if (ctx->canvas()) { task_runner_ = ctx->canvas()->GetDocument().GetTaskRunner(TaskType::kInternalDefault); } else { // Fallback for OffscreenCanvas (no frame scheduler) task_runner_ = Platform::Current()->CurrentThread()->GetTaskRunner(); } GLuint query; ctx->ContextGL()->GenQueriesEXT(1, &query); SetObject(query); } WebGLQuery::~WebGLQuery() { RunDestructor(); } void WebGLQuery::SetTarget(GLenum target) { DCHECK(Object()); DCHECK(!target_); target_ = target; } void WebGLQuery::DeleteObjectImpl(gpu::gles2::GLES2Interface* gl) { gl->DeleteQueriesEXT(1, &object_); object_ = 0; } void WebGLQuery::ResetCachedResult() { can_update_availability_ = false; query_result_available_ = false; query_result_ = 0; // When this is called, the implication is that we should start // keeping track of whether we can update the cached availability // and result. ScheduleAllowAvailabilityUpdate(); } void WebGLQuery::UpdateCachedResult(gpu::gles2::GLES2Interface* gl) { if (query_result_available_) return; if (!can_update_availability_) return; if (!HasTarget()) return; // We can only update the cached result when control returns to the browser. can_update_availability_ = false; GLuint available = 0; gl->GetQueryObjectuivEXT(Object(), GL_QUERY_RESULT_AVAILABLE_EXT, &available); query_result_available_ = !!available; if (query_result_available_) { GLuint result = 0; gl->GetQueryObjectuivEXT(Object(), GL_QUERY_RESULT_EXT, &result); query_result_ = result; task_handle_.Cancel(); } else { ScheduleAllowAvailabilityUpdate(); } } bool WebGLQuery::IsQueryResultAvailable() { return query_result_available_; } GLuint WebGLQuery::GetQueryResult() { return query_result_; } void WebGLQuery::ScheduleAllowAvailabilityUpdate() { if (task_handle_.IsActive()) return; task_handle_ = PostCancellableTask(*task_runner_, FROM_HERE, WTF::Bind(&WebGLQuery::AllowAvailabilityUpdate, WrapWeakPersistent(this))); } void WebGLQuery::AllowAvailabilityUpdate() { can_update_availability_ = true; } } // namespace blink
28
83
0.72619
[ "object" ]
33824671bc91c6a8e3ca5f6ccf6fa78cb86a7ed8
2,312
cpp
C++
aws-cpp-sdk-transcribe/source/model/StartTranscriptionJobRequest.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2020-07-16T19:03:13.000Z
2020-07-16T19:03:13.000Z
aws-cpp-sdk-transcribe/source/model/StartTranscriptionJobRequest.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-transcribe/source/model/StartTranscriptionJobRequest.cpp
woohoou/aws-sdk-cpp
a42835a8aad2eac1e334d899a3fbfedcaa341d51
[ "Apache-2.0" ]
1
2019-10-31T11:19:50.000Z
2019-10-31T11:19:50.000Z
/* * 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/transcribe/model/StartTranscriptionJobRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::TranscribeService::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; StartTranscriptionJobRequest::StartTranscriptionJobRequest() : m_transcriptionJobNameHasBeenSet(false), m_languageCode(LanguageCode::NOT_SET), m_languageCodeHasBeenSet(false), m_mediaSampleRateHertz(0), m_mediaSampleRateHertzHasBeenSet(false), m_mediaFormat(MediaFormat::NOT_SET), m_mediaFormatHasBeenSet(false), m_mediaHasBeenSet(false), m_settingsHasBeenSet(false) { } Aws::String StartTranscriptionJobRequest::SerializePayload() const { JsonValue payload; if(m_transcriptionJobNameHasBeenSet) { payload.WithString("TranscriptionJobName", m_transcriptionJobName); } if(m_languageCodeHasBeenSet) { payload.WithString("LanguageCode", LanguageCodeMapper::GetNameForLanguageCode(m_languageCode)); } if(m_mediaSampleRateHertzHasBeenSet) { payload.WithInteger("MediaSampleRateHertz", m_mediaSampleRateHertz); } if(m_mediaFormatHasBeenSet) { payload.WithString("MediaFormat", MediaFormatMapper::GetNameForMediaFormat(m_mediaFormat)); } if(m_mediaHasBeenSet) { payload.WithObject("Media", m_media.Jsonize()); } if(m_settingsHasBeenSet) { payload.WithObject("Settings", m_settings.Jsonize()); } return payload.WriteReadable(); } Aws::Http::HeaderValueCollection StartTranscriptionJobRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "Transcribe.StartTranscriptionJob")); return headers; }
25.688889
98
0.766436
[ "model" ]
338694ac011fc0316e3a4dd4e29dc70d35dd855c
2,019
cc
C++
mindspore/lite/src/runtime/kernel/npu/cast_npu.cc
taroxd/mindspore
9bb620ff2caaac7f1c53c4b104935f22352cb88f
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/npu/cast_npu.cc
taroxd/mindspore
9bb620ff2caaac7f1c53c4b104935f22352cb88f
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/npu/cast_npu.cc
taroxd/mindspore
9bb620ff2caaac7f1c53c4b104935f22352cb88f
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/runtime/kernel/npu/cast_npu.h" #include "src/kernel_registry.h" #include "src/runtime/agent/npu/npu_converter_utils.h" using mindspore::kernel::KERNEL_ARCH::kNPU; using mindspore::lite::KernelRegistrar; using mindspore::schema::PrimitiveType_Cast; namespace mindspore::kernel { int CastNPUKernel::IsSupport(const std::vector<lite::Tensor *> &inputs, const std::vector<lite::Tensor *> &outputs, OpParameter *opParameter) { return RET_OK; } int CastNPUKernel::SetNPUInputs(const std::vector<lite::Tensor *> &inputs, const std::vector<lite::Tensor *> &outputs, const std::vector<ge::Operator *> &npu_inputs) { op_ = new (std::nothrow) hiai::op::CastT(name_); if (op_ == nullptr) { MS_LOG(ERROR) << name_ << " op is nullptr"; return RET_ERROR; } op_->set_input_x(*npu_inputs[0]); op_->set_attr_dst_dtype(lite::ConverterToNPUDataType(static_cast<TypeId>(cast_parameter_->dst_type_))); op_->set_attr_src_dtype(lite::ConverterToNPUDataType(static_cast<TypeId>(cast_parameter_->src_type_))); return RET_OK; } ge::Operator *mindspore::kernel::CastNPUKernel::GetNPUOp() { return this->op_; } CastNPUKernel::~CastNPUKernel() { if (op_ != nullptr) { delete op_; op_ = nullptr; } } REG_KERNEL(kNPU, kNumberTypeFloat32, PrimitiveType_Cast, NPUKernelCreator<CastNPUKernel>) } // namespace mindspore::kernel
37.388889
118
0.717682
[ "vector" ]