blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
dc6058a774e7325480cd30ee6278c906fe2fd0ca
2cdec7a46f62fa27757a57dfde3d6960222b1c72
/simple-pendulum.cpp
f08c1c33026922753d20a44d97d48d6832db6c4c
[]
no_license
soyaib11/Cpp-Codes
9e56dfe99bf2e0f2314d15cf141b431cfc521433
3be71a84729e034a8711076245fd09d6ed15c18c
refs/heads/main
2023-02-22T11:34:48.823866
2021-01-26T14:26:42
2021-01-26T14:26:42
333,107,276
0
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
#include <iostream> #include <cmath> #include <fstream> using namespace std; double f(double phi,double theta_M) { double a=pow(sin(theta_M/2.0),2.0); double b=pow(sin(phi),2); double c=4*sqrt(0.0253)*(1/sqrt(1-a*b)); return c; } double period(double theta_M) { double a=0,b=M_PI/2; int i,n=100; double I=0.0; double h=(b-a)/n; for(i=1;i<n;i++) { I+=f(a+i*h,theta_M); } return (h/2)*(f(a,theta_M)+2*I+f(b,theta_M)); } int main() { ofstream fout("pendulum.dat"); for(double theta_M=0;theta_M<=M_PI/2.0;theta_M+=M_PI/1000) { fout<<theta_M<<" "<<period(theta_M)<<endl; } return 0; }
[ "noreply@github.com" ]
soyaib11.noreply@github.com
087d76c6600268123a32e01b1eb3eb7b2fc558e3
14248aaedfa5f77c7fc5dd8c3741604fb987de5c
/luogu/P3723.cpp
007bad902f9b4a45c6eac2ba79468e96ebd7dc50
[]
no_license
atubo/online-judge
fc51012465a1bd07561b921f5c7d064e336a4cd2
8774f6c608bb209a1ebbb721d6bbfdb5c1d1ce9b
refs/heads/master
2021-11-22T19:48:14.279016
2021-08-29T23:16:16
2021-08-29T23:16:16
13,290,232
2
0
null
null
null
null
UTF-8
C++
false
false
3,486
cpp
// https://www.luogu.org/problemnew/show/P3723 // [AH2017/HNOI2017]礼物 #include <bits/stdc++.h> using namespace std; class Fft { public: constexpr const static double PI = 3.14159265359; static void four1(vector<double> &data, const int isign) { int nn = data.size() / 2; int n = nn << 1; int j = 1; for (int i = 1; i < n; i+=2) { if (j > i) { swap(data[j-1], data[i-1]); swap(data[j], data[i]); } int m = nn; while (m >= 2 && j > m) { j -= m; m >>= 1; } j += m; } int mmax = 2; while (n > mmax) { int istep = mmax << 1; double theta = isign * (2 * PI / mmax); double wtemp = sin(0.5 * theta); double wpr = - 2.0 * wtemp * wtemp; double wpi = sin(theta); double wr = 1.0; double wi = 0.0; for (int m = 1; m < mmax; m += 2) { for (int i = m; i <= n; i += istep) { j = i + mmax; double tempr = wr * data[j-1] - wi * data[j]; double tempi = wr * data[j] + wi * data[j-1]; data[j-1] = data[i-1] - tempr; data[j] = data[i] - tempi; data[i-1] += tempr; data[i] += tempi; } wr = (wtemp=wr)*wpr - wi*wpi + wr; wi = wi*wpr + wtemp*wpi + wi; } mmax = istep; } } static vector<double> innerProduct(const vector<double> &x, const vector<double> &y) { const int n = x.size() / 2; vector<double> ret(2*n); for (int i = 0; i < n; i++) { double a = x[2*i], b = x[2*i+1]; double c = y[2*i], d = y[2*i+1]; ret[2*i] = a*c - b*d; ret[2*i+1] = a*d + b*c; } return ret; } }; vector<int64_t> rotateProduct(const vector<int>& x, const vector<int> &y) { const int n = x.size(); int nn = log2(n) + 3; nn = (1 << nn); vector<double> a(2*nn), b(2*nn); for (int i = 0; i < 2*n; i += 2) { a[i] = x[i/2]; b[i] = b[i+2*n] = y[n-1-i/2]; } Fft::four1(a, 1); Fft::four1(b, 1); vector<double> c = Fft::innerProduct(a, b); Fft::four1(c, -1); vector<int64_t> ret(n); for (int i = 0; i < n; i++) { ret[i] = c[2*(i+n-1)]/nn + 0.1; } return ret; } int64_t ans = 1e12; int N, M; void solve(int c, const vector<int> &x, vector<int> y) { int64_t totsq = 0; for (int i = 0; i < N; i++) { y[i] += c; totsq += y[i]*y[i] + x[i]*x[i]; } vector<int64_t> z = rotateProduct(x, y); int64_t maxp = *max_element(z.begin(), z.end()); ans = min(ans, totsq - 2*maxp); } int main() { scanf("%d%d", &N, &M); vector<int> x(N), y(N); int totx = 0, toty = 0; for (int i = 0; i < N; i++) { scanf("%d", &x[i]); totx += x[i]; } for (int i = 0; i < N; i++) { scanf("%d", &y[i]); toty += y[i]; } if (totx < toty) { swap(totx, toty); swap(x, y); } vector<int> cz; cz.push_back((totx-toty)/N); if ((totx-toty) % N != 0) { cz.push_back(cz[0]+1); } for (int c: cz) { solve(c, x, y); } printf("%lld\n", ans); return 0; }
[ "err722@yahoo.com" ]
err722@yahoo.com
f0ef9e8cd70c91b929f3918a2623f5dda58148e8
c78a3b5c83435d2d6c6894bc1620ac14b3656283
/tango-gl-renderer/include/tango-gl-renderer/frustum.h
b3eedaf473cd1dfc5671ef96ef0be4c37414c58a
[ "MIT", "Apache-2.0" ]
permissive
atroccoli/tango-examples-c
fa4e1051a305164c473a89b9722f45529bb42d7d
e53123e5c6c11e883c3ff90c0f5d36f8e59d9a4e
refs/heads/master
2021-01-20T16:34:40.616395
2014-11-26T22:00:20
2014-11-26T22:00:20
27,202,251
1
0
null
null
null
null
UTF-8
C++
false
false
1,183
h
/* * Copyright 2014 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. */ #ifndef TANGO_GL_RENDERER_FRUSTUM_H #define TANGO_GL_RENDERER_FRUSTUM_H #include "tango-gl-renderer/drawable_object.h" #include "tango-gl-renderer/gl_util.h" class Frustum : public DrawableObject { public: Frustum(); Frustum(const Frustum& other) = delete; Frustum& operator=(const Frustum&) = delete; ~Frustum(); void Render(const glm::mat4& projection_mat, const glm::mat4& view_mat) const; private: GLuint vertex_buffer_; GLuint shader_program_; GLuint attrib_vertices_; GLuint uniform_mvp_mat_; }; #endif // TANGO_GL_RENDERER_FRUSTUM_H
[ "xuguo@google.com" ]
xuguo@google.com
2e4600e07b9c6113c413443f3d13a8f5af973543
fb2e13219f4ca0ea51ce4baa7abf12b229246abc
/leetcode/SymmetricTree/rec.cc
62ea46bce0ce81a8e4d4308224c517a79e39276f
[]
no_license
lewischeng-ms/online-judge
7ca1e91ff81e8713c85cbec0aa0509a929854af9
b09d985cfc1026ad2258c2507d7022d7774b01ef
refs/heads/master
2021-01-22T01:28:19.095275
2015-07-10T13:21:57
2015-07-10T13:21:57
15,488,315
0
0
null
null
null
null
UTF-8
C++
false
false
806
cc
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool helper(TreeNode *p, TreeNode *q) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!p && !q) return true; else if (!p && q) return false; else if (p && !q) return false; if (p->val != q->val) return false; return helper(p->left, q->right) && helper(p->right, q->left); } bool isSymmetric(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!root) return true; return helper(root->left, root->right); } };
[ "lewischeng@Lewis-Chengs-MacBook-Air.local" ]
lewischeng@Lewis-Chengs-MacBook-Air.local
3e4f977bae1a4f7e3deb80772c6fcec7a9216d95
167d57480690ab763ee6e31b6cc6b3a5028d2587
/check.cpp
11cbc75d991e8699dcdc5f705827e999c298c5c4
[]
no_license
shagunsodhani/assembler
8b35672e09a19d38799af9b8767f0383ce887c57
b87b9d26e476af2ab3379bd202d97a2b6f814186
refs/heads/master
2016-09-05T22:56:57.296034
2012-11-28T14:02:05
2012-11-28T14:02:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
cpp
/* This file contains the code to check which string is larger * */ #include <iostream> #include <string> using namespace std; bool chk(string a,string b) { int p,q,diff,d; p = a.length(); q = b.length(); if(p>q) diff = p-q; else diff = q-p; if((a[0]!='0')&&(p>q)) return 1; else if ((a[0]=='0')&&(p>q)) { for(int i=0;i<q;i++) { if(a[diff+i]>b[i]) return 1; else if (a[diff+i]<b[i]) return 0; } } else if(p==q) { for(int i=0;i<q;i++) { if(a[i]>b[i]) return 1; else if (a[i]<b[i]) return 0; } } else if(p<q) { for(int i = 0;i<diff;i++) { if(b[i]=='0') d = 1; else d = 0;break; } if(d==0) return 0; else { for(int i =0;i<p;i++) { if(a[i]>b[diff+i]) return 1; else if (a[i]<b[diff+i]) return 0; } } } }
[ "sshagun.sodhani@gmail.com" ]
sshagun.sodhani@gmail.com
a8c1009fcc0c85317c25feab2b93b1aeadc1eeae
f8e09dcd697b8d5576c69c76aeff399dae6c06bd
/src/MetaJoint.cpp
49cd9cf2dc92b820e5c4534f04c99f1daec319ae
[]
no_license
RyanYoung25/maestor
5baef1b79e616cb63650873c0e19047c798d59f3
0ddff92a6088bc571f900b4d59c63abe21acd968
refs/heads/master
2021-01-25T07:40:16.742070
2015-07-09T13:24:52
2015-07-09T13:24:52
17,982,335
4
3
null
null
null
null
UTF-8
C++
false
false
4,977
cpp
/* Copyright (c) 2013, Drexel University, iSchool, Applied Informatics Group 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 <organization> 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 AUTHORS 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. */ /** * A metajoint object. This is extended by ArmMetaJoint but for all * the other metajoints in MAESTOR they are objects of this class */ #include "MetaJoint.h" /** * Create a metajoint and tell it it's controller */ MetaJoint::MetaJoint(MetaJointController* controller){ this->controller = controller; this->position = 0; this->ready = false; } /** * Destructor */ MetaJoint::~MetaJoint() {} /** * Get the property of this metajoint. Store it in the pointer that is passed in. * * @param property The property that you want to ask about * @param value A pointer to store the result in * @return True on success */ bool MetaJoint::get(PROPERTY property, double &value){ switch (property){ case ENABLED: value = true; break; case GOAL: value = this->currGoal; break; case INTERPOLATION_STEP: if (!ready){ ready = true; controller->setInverse(); } else{ value = interpolate(); } break; case POSITION: controller->getForward(); value = position; break; case READY: value = ready; break; case VELOCITY: value = interVel; break; default: return false; } return true; } /** * Set the property of this metajoint to the value passed in * * @param property The property to set * @param value The value to set it to * @return True on success */ bool MetaJoint::set(PROPERTY property, double value){ double currVel; double newVia; switch (property){ case META_VALUE: position = value; break; case POSITION: case GOAL: controller->update(); if (value == interStep){ break; } currVel = (currStepCount != 0 && currParams.valid) ? (interpolateFourthOrder(currParams, currStepCount) - interpolateFourthOrder(currParams, currStepCount - 1)) : 0; if (!startParams.valid){ currStepCount = 0; totalStepCount = totalTime(interStep, value, currVel, interVel) * frequency; if (totalStepCount > 0) { startParams = initFourthOrder(interStep, currVel, (value + interStep)/2, (double)totalStepCount / 2, value, totalStepCount); currParams = startParams; } lastGoal = interStep; } else if (currStepCount != currParams.tv) { newVia = (startParams.ths + interpolateFourthOrder(currParams, currStepCount)); totalStepCount = currStepCount + (totalTime(newVia, value, currVel, interVel) * frequency); currParams = initFourthOrder( startParams.ths, currVel, newVia, currStepCount, value, totalStepCount ); } currGoal = value; break; case SPEED: case VELOCITY: if (value > 0) interVel = value; break; case READY: ready = (bool)value; break; case INTERPOLATION_STEP: currParams.valid = false; startParams.valid = false; totalStepCount = 0; currStepCount = 0; break; default: return false; } return true; } /** * Set the goal and everything to that position * @param pos The position to set it all to */ void MetaJoint::setGoal(double pos){ currGoal = pos; interStep = pos; lastGoal = pos; }
[ "Ryan@rdyoung.us" ]
Ryan@rdyoung.us
80c61d379df04817cf832ad58c9d81de7041c54a
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/core/chemical/automorphism.hh
cd466f64ca4700d3f196fa19fb5f11ab55d08828
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
5,288
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file core/chemical/automorphism.hh /// /// @brief /// @author Ian W. Davis #ifndef INCLUDED_core_chemical_automorphism_hh #define INCLUDED_core_chemical_automorphism_hh #include <core/chemical/ResidueType.hh> #include <utility/vector1.hh> namespace core { namespace chemical { class AutomorphismIterator; // fwd declaration typedef utility::pointer::shared_ptr< AutomorphismIterator > AutomorphismIteratorOP; typedef utility::pointer::shared_ptr< AutomorphismIterator const > AutomorphismIteratorCOP; /// @brief Enumerates the automorphisms of a residue, which are basically /// chemical symmetries that affect RMSD calculations. /// /// @details Common automorphisms include flipping a phenyl ring (think Phe chi2) /// or rotating a methyl group (or CF3, if you don't care about H). /// However, they can be much more complicated than that, /// and some cannot be imitated by rotation about a bond. /// Examples include labeling a -CF3 clockwise vs. counterclockwise, /// or swapping the -CF3 branches of -C(CF3)2R. /// See the ligand of PDB 1PQC for a reasonably complex example. /// /// Formally, a graph automorphism is an isomorphism of that graph with itself: /// given a graph G(V,E) and a mapping M that relabels the vertices /// according to M(v) -> v', then M is an automorphism iff /// (M(u),M(v)) is an edge if and only if (u,v) is an edge. /// If the vertices are "colored" (in our case, have atom types), it must also /// be true that M(v) and v have the same color, for all v in V. /// /// Thus you can re-label a phenyl ring /// /// 2 3 6 5 6 3 /// 1 4 or 1 4 but not 1 4 /// 6 5 2 3 2 5 /// /// because in the last case, there are new bonds 6-3 and 2-5, /// and missing bonds 6-5 and 2-3. /// /// See also: OpenEye's OEChem library and its OERMSD() function. /// class AutomorphismIterator : public utility::pointer::ReferenceCount { public: /// @brief Including H will lead to many, many more automorphisms! AutomorphismIterator(ResidueType const & restype, bool includeH = false): restype_(restype), restype2_(restype), empty_list_() { natoms_ = (includeH ? restype_.natoms() : restype_.nheavyatoms()); curr_.assign(natoms_, 1); // = [1, 1, 1, ..., 1] } /// @brief The mapping returned will be from restype to restype2 /// Including H will lead to many, many more automorphisms! AutomorphismIterator(ResidueType const & restype, ResidueType const & restype2, bool includeH = false): restype_(restype), restype2_(restype2), empty_list_() { natoms_ = (includeH ? restype_.natoms() : restype_.nheavyatoms()); core::Size natoms2 = (includeH ? restype2_.natoms() : restype2_.nheavyatoms()); runtime_assert( natoms_ == natoms2 ); curr_.assign(natoms_, 1); // = [1, 1, 1, ..., 1] } ~AutomorphismIterator() override = default; /// @brief Returns the next automorphism for this residue type /// as a vector that maps "old" atom indices to "new" atom indices. /// Returns an empty vector when no more automorphisms remain. utility::vector1<Size> next(); private: /// @brief Are atoms i and j potentially interchangeable? /// @details We want this check to be fast but also to eliminate /// as many potential pairings as possible. /// We currently check (1) atom types and (2) number of neighbors. /// We could potentially also check atom types of neighbors, /// but that costs a set comparison or two array sorts, so we don't right now. inline bool can_pair(Size i, Size j); /// @brief Does the current mapping preserve all edges? /// @details That is, if (i,j) is an edge, is (curr_[i],curr_[j]) also an edge? /// Checks all edges (i,j) where j < i, for the supplied i. /// (Edges with j > i can't be checked becaues curr_[j] isn't valid yet.) inline bool edges_match(Size i) { AtomIndices const & nbrs = restype_.nbrs(i); for ( Size idx = 1, end = nbrs.size(); idx <= end; ++idx ) { Size const j = nbrs[idx]; if ( j > i ) continue; if ( !bonded2( curr_[i], curr_[j] ) ) return false; } return true; } /* // Commented out for cppcheck /// @brief Are atoms i and j bonded to each other on Restype1? inline bool bonded(Size i, Size j) { return restype_.path_distance(i,j) == 1; } */ /// @brief Are atoms i and j bonded to each other on Restype2? inline bool bonded2(Size i, Size j) { return restype2_.path_distance(i,j) == 1; } private: ResidueType const & restype_; ResidueType const & restype2_; Size natoms_; /// curr_[i] = current partner for atom i utility::vector1<Size> curr_; utility::vector1<Size> const empty_list_; }; // AutomorphismIterator } // namespace chemical } // namespace core #endif // INCLUDED_core_chemical_automorphism_HH
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
002dd89368f55cfcb999fdaf4be9d26488f6f8ab
d567a9487e40ea3b7b7f7b86718ed52d8e335a6c
/TheStart/ptr/src/main2.cpp
06c01d670d6169309a7ba5bd1ac3d69d8bcef2b9
[]
no_license
kinten108101/big-man
01022cc9adb3c6c1a0c84a508b719069e11a084d
f3de11fdc893663cd8b1bf9cf4493d819b9d8092
refs/heads/master
2020-07-28T13:21:21.963723
2019-09-19T00:17:09
2019-09-19T00:17:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,660
cpp
#include "../h/Header.h" int SEPARATING(int x, int* L, int* R, int& lh, int& rh) { lh = x / 2; rh = lh + ((x - lh) % lh); L = new int[lh]; R = new int[rh]; return 0; } int BUBBLESORT(int total, int arr[]) { int pairamount = total - 1; for (int i = 0; i < pairamount; i++) { for (int i = 0; i < total; i++) { static int placeholder = 0; if (arr[i] < arr[i + 1]) // largest to smallest { placeholder = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = placeholder; } else continue; } } return 0; } int INSERTING(int n, int L[], int R[], int lh, int rh) { for (int i = 0; i < lh; i++) { std::cout << "LEFT" << i + 1 << "="; std::cin >> L[i]; } for (int i = 0; i < rh; i++) { std::cout << "RIGHT" << i + 1 << "="; std::cin >> R[i]; } return 0; } int main() { int a = NULL; int *LEFT = 0, *RIGHT = 0; int c = 0, cc = 0; int& p = c; int& px = cc; std::cout << "Limit of array:"; std::cin >> a; SEPARATING(a, LEFT, RIGHT, p, px); INSERTING(a, LEFT, RIGHT, p, px); BUBBLESORT(p, LEFT); BUBBLESORT(px, RIGHT); std::cin.get(); // //Problem: can't universally declare arrays LEFT and RIGHT //Solution: Declaring new variables that use the given variables (numbnuts). The original declaration should be in the main for //universal access. //INSERTING(a); /* for testing arraying length std::cout << LEFT[a/2] << std::endl; std::cout << RIGHT[a/2+1] << std::endl; */ /* for testing arraying declaring int *b = &Array[a - 1]; *b = 2; std::cout << b; */ std::cin.get(); }
[ "noreply@github.com" ]
kinten108101.noreply@github.com
91dc570a73bd2dcc5e54d1b07764051c68e8ad1f
0b2e6d1c1ae0ebc4fe0dfb3c5ff46720fad8b22a
/Kernel/VM/MemoryManager.h
3413e57945e4a047bef250bec4186f5e7fa64abb
[ "BSD-2-Clause" ]
permissive
vger92/serenity
b207e040eb1b735578c9d35276e5e5cd608212f5
e83afe228a424fa096586bf4528cf859ea5b9965
refs/heads/master
2020-05-30T15:55:49.704687
2019-06-02T10:40:45
2019-06-02T10:40:45
189,833,848
0
0
BSD-2-Clause
2019-06-02T10:39:26
2019-06-02T10:39:26
null
UTF-8
C++
false
false
6,999
h
#pragma once #include "i386.h" #include <AK/AKString.h> #include <AK/Badge.h> #include <AK/Bitmap.h> #include <AK/ByteBuffer.h> #include <AK/HashTable.h> #include <AK/RetainPtr.h> #include <AK/Retainable.h> #include <AK/Types.h> #include <AK/Vector.h> #include <AK/Weakable.h> #include <Kernel/FileSystem/InodeIdentifier.h> #include <Kernel/LinearAddress.h> #include <Kernel/VM/PhysicalPage.h> #include <Kernel/VM/Region.h> #include <Kernel/VM/VMObject.h> #define PAGE_ROUND_UP(x) ((((dword)(x)) + PAGE_SIZE - 1) & (~(PAGE_SIZE - 1))) class SynthFSInode; enum class PageFaultResponse { ShouldCrash, Continue, }; #define MM MemoryManager::the() class MemoryManager { AK_MAKE_ETERNAL friend class PageDirectory; friend class PhysicalPage; friend class Region; friend class VMObject; friend ByteBuffer procfs$mm(InodeIdentifier); friend ByteBuffer procfs$memstat(InodeIdentifier); public: [[gnu::pure]] static MemoryManager& the(); static void initialize(); PageFaultResponse handle_page_fault(const PageFault&); bool map_region(Process&, Region&); bool unmap_region(Region&); void populate_page_directory(PageDirectory&); void enter_process_paging_scope(Process&); bool validate_user_read(const Process&, LinearAddress) const; bool validate_user_write(const Process&, LinearAddress) const; enum class ShouldZeroFill { No, Yes }; RetainPtr<PhysicalPage> allocate_physical_page(ShouldZeroFill); RetainPtr<PhysicalPage> allocate_supervisor_physical_page(); void remap_region(PageDirectory&, Region&); size_t ram_size() const { return m_ram_size; } int user_physical_pages_in_existence() const { return s_user_physical_pages_in_existence; } int super_physical_pages_in_existence() const { return s_super_physical_pages_in_existence; } void map_for_kernel(LinearAddress, PhysicalAddress); RetainPtr<Region> allocate_kernel_region(size_t, String&& name); void map_region_at_address(PageDirectory&, Region&, LinearAddress, bool user_accessible); private: MemoryManager(); ~MemoryManager(); void register_vmo(VMObject&); void unregister_vmo(VMObject&); void register_region(Region&); void unregister_region(Region&); void remap_region_page(Region&, unsigned page_index_in_region, bool user_allowed); void initialize_paging(); void flush_entire_tlb(); void flush_tlb(LinearAddress); RetainPtr<PhysicalPage> allocate_page_table(PageDirectory&, unsigned index); void map_protected(LinearAddress, size_t length); void create_identity_mapping(PageDirectory&, LinearAddress, size_t length); void remove_identity_mapping(PageDirectory&, LinearAddress, size_t); static Region* region_from_laddr(Process&, LinearAddress); static const Region* region_from_laddr(const Process&, LinearAddress); bool copy_on_write(Region&, unsigned page_index_in_region); bool page_in_from_inode(Region&, unsigned page_index_in_region); bool zero_page(Region& region, unsigned page_index_in_region); byte* quickmap_page(PhysicalPage&); void unquickmap_page(); PageDirectory& kernel_page_directory() { return *m_kernel_page_directory; } struct PageDirectoryEntry { explicit PageDirectoryEntry(dword* pde) : m_pde(pde) { } dword* page_table_base() { return reinterpret_cast<dword*>(raw() & 0xfffff000u); } void set_page_table_base(dword value) { *m_pde &= 0xfff; *m_pde |= value & 0xfffff000; } dword raw() const { return *m_pde; } dword* ptr() { return m_pde; } enum Flags { Present = 1 << 0, ReadWrite = 1 << 1, UserSupervisor = 1 << 2, WriteThrough = 1 << 3, CacheDisabled = 1 << 4, }; bool is_present() const { return raw() & Present; } void set_present(bool b) { set_bit(Present, b); } bool is_user_allowed() const { return raw() & UserSupervisor; } void set_user_allowed(bool b) { set_bit(UserSupervisor, b); } bool is_writable() const { return raw() & ReadWrite; } void set_writable(bool b) { set_bit(ReadWrite, b); } bool is_write_through() const { return raw() & WriteThrough; } void set_write_through(bool b) { set_bit(WriteThrough, b); } bool is_cache_disabled() const { return raw() & CacheDisabled; } void set_cache_disabled(bool b) { set_bit(CacheDisabled, b); } void set_bit(byte bit, bool value) { if (value) *m_pde |= bit; else *m_pde &= ~bit; } dword* m_pde; }; struct PageTableEntry { explicit PageTableEntry(dword* pte) : m_pte(pte) { } dword* physical_page_base() { return reinterpret_cast<dword*>(raw() & 0xfffff000u); } void set_physical_page_base(dword value) { *m_pte &= 0xfffu; *m_pte |= value & 0xfffff000u; } dword raw() const { return *m_pte; } dword* ptr() { return m_pte; } enum Flags { Present = 1 << 0, ReadWrite = 1 << 1, UserSupervisor = 1 << 2, WriteThrough = 1 << 3, CacheDisabled = 1 << 4, }; bool is_present() const { return raw() & Present; } void set_present(bool b) { set_bit(Present, b); } bool is_user_allowed() const { return raw() & UserSupervisor; } void set_user_allowed(bool b) { set_bit(UserSupervisor, b); } bool is_writable() const { return raw() & ReadWrite; } void set_writable(bool b) { set_bit(ReadWrite, b); } bool is_write_through() const { return raw() & WriteThrough; } void set_write_through(bool b) { set_bit(WriteThrough, b); } bool is_cache_disabled() const { return raw() & CacheDisabled; } void set_cache_disabled(bool b) { set_bit(CacheDisabled, b); } void set_bit(byte bit, bool value) { if (value) *m_pte |= bit; else *m_pte &= ~bit; } dword* m_pte; }; static unsigned s_user_physical_pages_in_existence; static unsigned s_super_physical_pages_in_existence; PageTableEntry ensure_pte(PageDirectory&, LinearAddress); RetainPtr<PageDirectory> m_kernel_page_directory; dword* m_page_table_zero; LinearAddress m_quickmap_addr; Vector<Retained<PhysicalPage>> m_free_physical_pages; Vector<Retained<PhysicalPage>> m_free_supervisor_physical_pages; HashTable<VMObject*> m_vmos; HashTable<Region*> m_user_regions; HashTable<Region*> m_kernel_regions; size_t m_ram_size { 0 }; bool m_quickmap_in_use { false }; }; struct ProcessPagingScope { ProcessPagingScope(Process&); ~ProcessPagingScope(); };
[ "awesomekling@gmail.com" ]
awesomekling@gmail.com
40360636802f93b2ba1d0012663e40df42165a63
7233d7ee7502e6dc4638b8d2f283242db59d7557
/include/StringTable.h
b0a2c0b18dcdefbf2daaec4b7e200c95442bbe3f
[]
no_license
wllxyz/xyz
628c96f0e1fa903566257dfa37c74b2892d79952
70f90b400a03edf8c323310da7d6c5d858a11d6f
refs/heads/master
2021-08-15T17:13:47.853375
2021-01-13T10:18:43
2021-01-13T10:18:43
49,399,603
3
0
null
null
null
null
UTF-8
C++
false
false
807
h
//<FILENAME>StringTable.h</FILENAME> //<AUTHOR>WangLiLiang</AUTHOR> //<DATE>2012.04.04</DATE> //<TYPE>CPP PROGRAM CLASS</TYPE> #ifndef STRING_TABLE_H #define STRING_TABLE_H #include <string> #include <map> #include <vector> #include <iostream> //#include <hash_map> namespace Wll { class IndexOutOfBoundaryException { }; class StringTable { public: typedef std::map<std::string,int> MapType; public: //获取字符串注册的索引,如果字符串不存在,首先注册,然后返回新注册的索引值 int GetIndexByName(const std::string& name); //根据先前注册时分配的索引值获取字符串 const std::string& GetNameByIndex(int index); private: MapType name2index_table; std::vector<std::string> index2name_table; }; };//end of namespace Wll #endif //STRING_TABLE_H
[ "wangliliang@zizizizizi.com" ]
wangliliang@zizizizizi.com
16361661eaf232450caac25332739b238997a416
85d9243f5c18af76e5c56987ed7ec477f75d66d6
/src/Singleton/Singleton.hpp
efc243b34e107a23bb7dcbba873cee8627ba52f1
[]
no_license
Mdopenfy/HeroicWar
8b1a71c14cfeb49cd7915764a2410d06d88b62e2
0ef3f85b57234c56d7875bc62ad6a8c022132ca5
refs/heads/master
2021-01-01T17:05:37.611372
2013-03-04T20:06:50
2013-03-04T20:06:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,132
hpp
///////////////////////////////////////////////////////////////////////////// //// //// Singleton - modèle Singleton applicable à n'importe quelle classe. //// /////////////////////////////////////////////////////////////////////////////// #include <cstddef> template <typename T> class Singleton { protected: Singleton () { } ~Singleton () { } public: static T *getInstance () { if (NULL == _singleton) _singleton = new T; return (static_cast<T*> (_singleton)); } static void kill () { if (NULL != _singleton) { delete _singleton; _singleton = NULL; } } static bool exist() { return (_singleton != NULL); } private: static T *_singleton; }; template <typename T> T *Singleton<T>::_singleton = NULL;
[ "meven.mognol@gmail.com" ]
meven.mognol@gmail.com
63c9990ecf2b53d2251690027c0dd934039f51d0
c6da2e91c81b08f270bfc956f1258bc0ac19bdfc
/include/socket_t/proto_socket.h
7f988101f91d13ca605f5c9b4b9d2b3f9886c390
[ "MIT" ]
permissive
ognian-/socket_t
ef9b750e60f99bff77d2da531e0a397a625c7e89
75d2fec8be215341b6970839f00042dc979c0ffa
refs/heads/master
2021-09-21T01:03:50.081364
2018-08-17T12:31:29
2018-08-17T12:31:29
112,351,231
0
0
null
null
null
null
UTF-8
C++
false
false
2,928
h
#ifndef SOCKET_T_PROTO_SOCKET_H #define SOCKET_T_PROTO_SOCKET_H #include <chrono> #include <sys/socket.h> #include <sys/time.h> #include "socket_t/sockopt.h" SOCKT_NAMESPACE_BEGIN class timeout_t { public: template<typename Rep, typename Period> constexpr timeout_t(const std::chrono::duration<Rep, Period>& time); constexpr timeout_t(const ::timeval& time); constexpr operator ::timeval() const; constexpr operator const std::chrono::microseconds&() const; constexpr bool operator==(const timeout_t& other) const; constexpr bool operator!=(const timeout_t& other) const; private: const std::chrono::microseconds m_time; }; class linger_t { public: constexpr linger_t(int seconds); constexpr linger_t(const ::linger& in); constexpr operator ::linger() const; constexpr bool get_enabled() const; constexpr int get_seconds() const; private: const bool m_enabled; const int m_seconds; }; class proto_socket { ~proto_socket() = delete; public: using acceptconn = sockopt<SOL_SOCKET, SO_ACCEPTCONN, int, true, false, bool>; using reuseaddr = sockopt<SOL_SOCKET, SO_REUSEADDR, int, false, true, bool>; using rcvbuf = sockopt<SOL_SOCKET, SO_RCVBUF, int, true, true>; using sndbuf = sockopt<SOL_SOCKET, SO_SNDBUF, int, true, true>; using rcvtimeo = sockopt<SOL_SOCKET, SO_RCVTIMEO, ::timeval, true, true, timeout_t>; using sndtimeo = sockopt<SOL_SOCKET, SO_SNDTIMEO, ::timeval, true, true, timeout_t>; using linger = sockopt<SOL_SOCKET, SO_LINGER, ::linger, true, true, linger_t>; }; template<typename Rep, typename Period> constexpr timeout_t::timeout_t(const std::chrono::duration<Rep, Period>& time) : m_time{time} {} constexpr timeout_t::timeout_t(const ::timeval& time) : timeout_t{std::chrono::seconds(time.tv_sec) + std::chrono::microseconds(time.tv_usec)} {} constexpr timeout_t::operator ::timeval() const { ::timeval out{}; auto sec = std::chrono::duration_cast<std::chrono::seconds>(m_time); out.tv_sec = sec.count(); out.tv_usec = std::chrono::duration_cast<std::chrono::microseconds>(m_time - sec).count(); return out; } constexpr timeout_t::operator const std::chrono::microseconds&() const { return m_time; } constexpr bool timeout_t::operator==(const timeout_t& other) const { return m_time == other.m_time; } constexpr bool timeout_t::operator!=(const timeout_t& other) const { return m_time != other.m_time; } constexpr linger_t::linger_t(int seconds) : m_enabled{seconds >= 0}, m_seconds{seconds >= 0 ? seconds : 0} {} constexpr linger_t::linger_t(const ::linger& in) : m_enabled{in.l_linger != 0}, m_seconds{in.l_linger} {} constexpr linger_t::operator ::linger() const { ::linger out{}; out.l_onoff = m_enabled ? 1 : 0; out.l_linger = m_seconds; return out; } constexpr bool linger_t::get_enabled() const { return m_enabled; } constexpr int linger_t::get_seconds() const { return m_seconds; } SOCKT_NAMESPACE_END #endif // SOCKET_T_PROTO_SOCKET_H
[ "ognian@mokriya.com" ]
ognian@mokriya.com
02a85e138f7a8b8a5c8f0ef7b5145adbe1ae6cbe
c86269fcadcc2b8686199d32d168c84673709ba5
/src/controller/Controller.cpp
8027cd9deeff28de409d04c4fc27315dc194b156
[]
no_license
Szkodnik128/PokerGame
b007a10f955ff86202265b9d9f8266c006235fbb
93f98c1e4d4ebf4e7b40a0ad5b8fef4db3d4e445
refs/heads/master
2019-07-09T11:59:59.676386
2018-06-03T14:21:04
2018-06-03T14:21:04
34,904,229
0
0
null
null
null
null
UTF-8
C++
false
false
3,817
cpp
// // Created by kuba on 18.03.18. // #include "Controller.h" #include "event/EventRecvRequest.h" #include "event/EventConnectionClosed.h" Controller::Controller(BlockingQueue<Event *> *const blockingQueue, Model *const model) : blockingQueue(blockingQueue), model(model), workerFlag(false) { /* Fill event strategy map */ this->eventStrategyMap[typeid(EventRecvRequest).name()] = &Controller::eventRecvRequestHandler; this->eventStrategyMap[typeid(EventConnectionClosed).name()] = &Controller::eventConnectionClosedHandler; /* Fill message strategy map */ this->messageStrategyMap[Request::PayloadCase::kLogin] = &Controller::messageLoginHandler; this->messageStrategyMap[Request::PayloadCase::kCreateTable] = &Controller::messageCreateTableHandler; this->messageStrategyMap[Request::PayloadCase::kJoinTable] = &Controller::messageJoinTableHandler; this->messageStrategyMap[Request::PayloadCase::kLeaveTable] = &Controller::messageLeaveTableHandler; this->messageStrategyMap[Request::PayloadCase::kRaiseBet] = &Controller::messageRaiseHandler; this->messageStrategyMap[Request::PayloadCase::kFold] = &Controller::messageFoldHandler; this->messageStrategyMap[Request::PayloadCase::kCall] = &Controller::messageCallHandler; } void Controller::run() { Event *event; EventHandler handler; this->workerFlag = true; while (this->workerFlag) { event = this->blockingQueue->pop(); handler = this->eventStrategyMap[typeid(*event).name()]; assert(handler != nullptr); (this->*handler)(event); delete event; } } void Controller::setWorkerFlag(bool workerFlag) { this->workerFlag = workerFlag; } void Controller::eventRecvRequestHandler(Event *event) { MessageHandler handler; auto *eventRecvRequest = (EventRecvRequest *)event; const Request &request = eventRecvRequest->getRequest(); handler = this->messageStrategyMap[request.payload_case()]; assert(handler != nullptr); (this->*handler)(&request, (ClientHandler *const)eventRecvRequest->getClientHandler()); } void Controller::eventConnectionClosedHandler(Event *event) { auto *eventConnectionClosed = (EventConnectionClosed *)event; this->model->disconnect((ClientHandler *const)eventConnectionClosed->getClientHandler()); } void Controller::messageLoginHandler(const Request *const request, ClientHandler *const clientHandler) { const Login &login = request->login(); this->model->login(login, clientHandler); } void Controller::messageCreateTableHandler(const Request *const request, ClientHandler *const clientHandler) { const CreateTable &createTable = request->createtable(); this->model->createTable(createTable, clientHandler); } void Controller::messageJoinTableHandler(const Request *const request, ClientHandler *const clientHandler) { const JoinTable &joinTable = request->jointable(); this->model->joinTable(joinTable, clientHandler); } void Controller::messageLeaveTableHandler(const Request *const request, ClientHandler *const clientHandler) { const LeaveTable &leaveTable = request->leavetable(); this->model->leaveTable(leaveTable, clientHandler); } void Controller::messageRaiseHandler(const Request *const request, ClientHandler *const clientHandler) { const Raise &raise = request->raise_bet(); this->model->raise(raise, clientHandler); } void Controller::messageFoldHandler(const Request *const request, ClientHandler *const clientHandler) { const Fold &fold = request->fold(); this->model->fold(fold, clientHandler); } void Controller::messageCallHandler(const Request *const request, ClientHandler *const clientHandler) { const Call &call = request->call(); this->model->call(call, clientHandler); }
[ "ku3atonie@gmail.com" ]
ku3atonie@gmail.com
572ff8e20e427eb2faa8404cd6a75ed44f53d57e
c18fb2aa33610daf4f241e1bd8d62c288030f699
/MyProfessionalC++/c09_code/c09_code/WeatherPrediction/MyWeatherPrediction.cpp
43fef67981b13e0de1e15f10aae11116d1048aa1
[]
no_license
Chinkyu/CXXExercise
73f4166bfd9fa69ad4bc5786ddd74fa11398b58f
ca493a82c4e872f8c50da3f2b4027ef4e4ecf814
refs/heads/master
2023-08-31T12:04:49.295552
2023-08-31T01:02:25
2023-08-31T01:02:25
72,819,670
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,324
cpp
#include <iostream> #include "MyWeatherPrediction.h" using namespace std; void MyWeatherPrediction::setCurrentTempCelsius(int inTemp) { int fahrenheitTemp = convertCelsiusToFahrenheit(inTemp); setCurrentTempFahrenheit(fahrenheitTemp); } int MyWeatherPrediction::getTomorrowTempCelsius() const { int fahrenheitTemp = getTomorrowTempFahrenheit(); return convertFahrenheitToCelsius(fahrenheitTemp); } void MyWeatherPrediction::showResult() const { cout << "Tomorrow's temperature will be " << getTomorrowTempCelsius() << " degrees Celsius (" << getTomorrowTempFahrenheit() << " degrees Fahrenheit)" << endl; cout << "The chance of rain is " << (getChanceOfRain() * 100) << " percent" << endl; if (getChanceOfRain() > 0.5) { cout << "Bring an umbrella!" << endl; } } int MyWeatherPrediction::convertCelsiusToFahrenheit(int inCelsius) { return static_cast<int>((9.0 / 5.0) * inCelsius + 32); } int MyWeatherPrediction::convertFahrenheitToCelsius(int inFahrenheit) { return static_cast<int>((5.0 / 9.0) * (inFahrenheit - 32)); } string MyWeatherPrediction::getTemperature() const { return WeatherPrediction::getTemperature() + "°F"; } int main() { MyWeatherPrediction p; p.setCurrentTempCelsius(33); p.setPositionOfJupiter(80); p.showResult(); cout << p.getTemperature() << endl; return 0; }
[ "bamtori@hotmail.com" ]
bamtori@hotmail.com
455016ed0c6f20ce7a1c5e22ab8cbd33db0acdc1
66213c48da0b752dc6c350789935fe2b2b9ef5ca
/abc/272/e.cpp
abb861c0b414129376f3369169d65837d4dfbda6
[]
no_license
taketakeyyy/atcoder
28c58ae52606ba85852687f9e726581ab2539b91
a57067be27b27db3fee008cbcfe639f5309103cc
refs/heads/master
2023-09-04T16:53:55.172945
2023-09-04T07:25:59
2023-09-04T07:25:59
123,848,306
0
0
null
2019-04-21T07:39:45
2018-03-05T01:37:20
Python
UTF-8
C++
false
false
3,405
cpp
#define _USE_MATH_DEFINES // M_PI等のフラグ #include <bits/stdc++.h> #define MOD 1000000007 #define COUNTOF(array) (sizeof(array)/sizeof(array[0])) #define rep(i,n) for (int i = 0; i < (n); ++i) #define intceil(a,b) ((a+(b-1))/b) using namespace std; using ll = long long; using pii = pair<int,int>; using pll = pair<long,long>; const long long INF = LONG_LONG_MAX - 1001001001001001; void chmax(int& x, int y) { x = max(x,y); } void chmin(int& x, int y) { x = min(x,y); } string vs = "URDL"; // 上右下左 vector<ll> vy = { -1, 0, 1, 0 }; vector<ll> vx = { 0, 1, 0, -1 }; void solve() { ll N, M; cin >> N >> M; vector<vector<ll>> d(M); for(ll i=1; i<=N; i++) { ll a; cin >> a; a += i; // 0 <= a+i_x < N が成り立つiを列挙したい ll l = (0 <= a) ? 0 : intceil(-a, i); ll r = (N <= a) ? 0 : intceil(-(a-N), i); r = min(r, M); for(ll j=l; j<r; j++) { d[j].push_back(a+i*j); } } for(ll mi=0; mi<M; mi++) { auto &b = d[mi]; ll sz = b.size(); vector<bool> e(sz+1); // 存在するか for(ll i: b) e[i] = true; ll ans = 0; while(e[ans]) ans++; cout << ans << endl; } } /* 5 6 -2 -2 -5 -7 -15 */ void solve2() { ll N, M; cin >> N >> M; vector<set<ll>> opSet(M+1); // opSet[i] := i回目の操作後の存在する[0,N]までの整数 for(ll i=1; i<=N; i++) { ll a; cin >> a; a += i; // 0 <= a <= N となる範囲[li, ri]を探す ll li, ri; if (a>=0 && a<=N) { li = 1; ri = li + (N-a)/i; } else if (a < 0){ li = 1 + intceil(-a, i); ll s = a + (li-1) * i; ri = li + (N-s)/i; } else { continue; } ri = min(ri, M); for(ll j=li; j<=ri; j++) { opSet[j].insert(a+i*(j-1)); } } // 出力 O(NM)な感じだがopSet[mi]はスカスカ for(ll mi=1; mi<=M; mi++) { for(ll mex=0; mex<=N; mex++) { if (!opSet[mi].count(mex)) { cout << mex << endl; break; } } } } void solve3() { ll N, M; cin >> N >> M; vector<set<ll>> opSet(M+1); // opSet[i] := i回目の操作後の存在する[0,N]までの整数 for(ll i=1; i<=N; i++) { ll a; cin >> a; // はじめて 0 <= a <= N となる操作回数の開始地点を探す ll sj; if ((a+i)>=0 && (a+i)<=N) { sj = 1; } else if ((a+i) < 0){ sj = 1 + intceil(-(a+i), i); } else { continue; } // j回目の操作後の整数をopSetに入れていく a += sj*i; for(ll j=sj; j<=M; j++) { if (a > N) break; opSet[j].insert(a); a += i; } } // 出力 O(NM)な感じだがopSet[mi]はスカスカ for(ll mi=1; mi<=M; mi++) { for(ll mex=0; mex<=N; mex++) { if (!opSet[mi].count(mex)) { cout << mex << endl; break; } } } } int main() { // solve(); // solve2(); solve3(); return 0; }
[ "taketakeyyy@gmail.com" ]
taketakeyyy@gmail.com
aa5c733e86894e7a3865af0377f956f75bd6e7e8
4449426afd4842c90acfbad9b5ec4d027e2e9a8f
/src/Storage/Record.cc
84eadc618242caf3779b8c8206051e390441a5af
[]
no_license
yuanhang3260/DBMS
38a4d005676f56c3bb0a46266bc4d497a3025d93
c83e4ba75fbe9e1eff177d5474155628dbf2d466
refs/heads/master
2020-04-11T23:28:05.734606
2017-12-13T07:43:15
2017-12-13T07:43:15
47,942,052
0
0
null
null
null
null
UTF-8
C++
false
false
15,962
cc
#include <climits> #include <string.h> #include <iostream> #include <stdexcept> #include <algorithm> #include "Base/Utils.h" #include "Base/Log.h" #include "Strings/Split.h" #include "Strings/Utils.h" #include "Storage/Record.h" namespace Storage { std::string RecordTypeStr(RecordType record_type) { switch (record_type) { case INDEX_RECORD: return "INDEX_RECORD"; case DATA_RECORD: return "DATA_RECORD"; case TREENODE_RECORD: return "TREENODE_RECORD"; case UNKNOWN_RECORDTYPE: return "UNKNOWN_RECORD_TYPE"; } return "UNKNOWN_RECORDTYPE"; } // ****************************** RecordID ********************************** // int RecordID::DumpToMem(byte* buf) const { if (!buf) { return -1; } memcpy(buf, &page_id_, sizeof(page_id_)); memcpy(buf + sizeof(page_id_), &slot_id_, sizeof(slot_id_)); return sizeof(page_id_) + sizeof(slot_id_); } int RecordID::LoadFromMem(const byte* buf) { if (!buf) { return -1; } memcpy(&page_id_, buf, sizeof(page_id_)); memcpy(&slot_id_, buf + sizeof(page_id_), sizeof(slot_id_)); return sizeof(page_id_) + sizeof(slot_id_); } void RecordID::Print() const { std::cout << "rid = (" << page_id_ << ", " << slot_id_ << ")" << std::endl; } // ****************************** RecordBase ******************************** // uint32 RecordBase::size() const { uint32 size = 0; for (const auto& field: fields_) { size += field->length(); } return size; } void RecordBase::Print() const { PrintImpl(); std::cout << std::endl; } void RecordBase::PrintImpl() const { std::cout << "Record: | "; for (auto& field: fields_) { if (field->type() == Schema::FieldType::STRING || field->type() == Schema::FieldType::CHARARRAY) { std::cout << Schema::FieldTypeStr(field->type()) << ": " << "\"" << field->AsString() << "\" | "; } else { std::cout << Schema::FieldTypeStr(field->type()) << ": " << field->AsString() << " | "; } } } void RecordBase::AddField(Schema::Field* new_field) { fields_.push_back(std::shared_ptr<Schema::Field>(new_field)); } void RecordBase::AddField(std::shared_ptr<Schema::Field> new_field) { fields_.push_back(new_field); } bool RecordBase::operator<(const RecordBase& other) const { const auto& other_fields = other.fields(); int len = Utils::Min(fields_.size(), other_fields.size()); for (int i = 0; i < len; i++) { int re = RecordBase::CompareSchemaFields( fields_.at(i).get(), other_fields.at(i).get()); if (re < 0) { return true; } else if (re > 0){ return false; } } return fields_.size() < other_fields.size(); } bool RecordBase::operator>(const RecordBase& other) const { const auto& other_fields = other.fields(); int len = Utils::Min(fields_.size(), other_fields.size()); for (int i = 0; i < len; i++) { int re = RecordBase::CompareSchemaFields( fields_.at(i).get(), other_fields.at(i).get()); if (re > 0) { return true; } else if (re < 0){ return false; } } return fields_.size() > other_fields.size(); } bool RecordBase::operator<=(const RecordBase& other) const { return !(*this > other); } bool RecordBase::operator>=(const RecordBase& other) const { return !(*this < other); } bool RecordBase::operator==(const RecordBase& other) const { uint32 len = fields_.size(); if (len != other.fields_.size()) { return false; } const auto& other_fields = other.fields(); for (uint32 i = 0; i < len; i++) { int re = RecordBase::CompareSchemaFields( fields_.at(i).get(), other_fields.at(i).get()); if (re != 0) { return false; } } return true; } int RecordBase::CompareRecords(const RecordBase& r1, const RecordBase& r2) { CHECK(r1.NumFields() == r2.NumFields(), "records have different number of fields"); for (uint32 i = 0; i < r1.NumFields(); i++) { CHECK(r1.fields_.at(i)->type() == r2.fields_.at(i)->type(), "Comparing different types of schema fields!"); int re = RecordBase::CompareSchemaFields(r1.fields_.at(i).get(), r2.fields_.at(i).get()); if (re < 0) { return -1; } else if (re > 0) { return 1; } } return 0; } int RecordBase::CompareRecordsBasedOnIndex(const RecordBase& r1, const RecordBase& r2, const std::vector<uint32>& indexes) { CHECK(!indexes.empty(), "empty comparing indexes"); for (uint32 i = 0; i < indexes.size(); i++) { int re = RecordBase::CompareSchemaFields( r1.fields_.at(indexes[i]).get(), r2.fields_.at(indexes[i]).get() ); if (re < 0) { return -1; } else if (re > 0) { return 1; } } return 0; } bool RecordBase::RecordComparator(const RecordBase& r1, const RecordBase& r2, const std::vector<uint32>& indexes) { return CompareRecordsBasedOnIndex(r1, r2, indexes) < 0; } bool RecordBase::RecordComparatorGt(const RecordBase& r1, const RecordBase& r2, const std::vector<uint32>& indexes) { return CompareRecordsBasedOnIndex(r1, r2, indexes) > 0; } int RecordBase::CompareRecordWithKey(const RecordBase& record, const RecordBase& key, const std::vector<uint32>& indexes) { CHECK(!indexes.empty(), "empty comparing indexes"); CHECK(key.NumFields() == indexes.size(), "Number of key fields mismatch with indexes to compare"); for (uint i = 0; i < indexes.size(); i++) { int re = RecordBase::CompareSchemaFields( record.fields_.at(indexes[i]).get(), key.fields_.at(i).get() ); if (re < 0) { return -1; } else if (re > 0) { return 1; } } return 0; } bool RecordBase::operator!=(const RecordBase& other) const { return !(*this == other); } #define COMPARE_FIELDS_WITH_TYPE(TYPE, FIELD1, FIELD2) \ const TYPE& f1 = *dynamic_cast<const TYPE*>(FIELD1); \ const TYPE& f2 = *dynamic_cast<const TYPE*>(FIELD2); \ if (f1 < f2) { \ return -1; \ } \ if (f1 > f2) { \ return 1; \ } \ return 0; \ int RecordBase::CompareSchemaFields(const Schema::Field* field1, const Schema::Field* field2) { if (!field1 && !field2) { return 0; } if (!field1) { return -1; } if (!field2) { return 1; } auto type = field1->type(); CHECK(type == field2->type(), "Comparing different types of schema fields!"); if (type == Schema::FieldType::INT) { COMPARE_FIELDS_WITH_TYPE(Schema::IntField, field1, field2); } if (type == Schema::FieldType::LONGINT) { COMPARE_FIELDS_WITH_TYPE(Schema::LongIntField, field1, field2); } if (type == Schema::FieldType::DOUBLE) { COMPARE_FIELDS_WITH_TYPE(Schema::DoubleField, field1, field2); } if (type == Schema::FieldType::BOOL) { COMPARE_FIELDS_WITH_TYPE(Schema::BoolField, field1, field2); } if (type == Schema::FieldType::CHAR) { COMPARE_FIELDS_WITH_TYPE(Schema::CharField, field1, field2); } if (type == Schema::FieldType::STRING) { COMPARE_FIELDS_WITH_TYPE(Schema::StringField, field1, field2); } if (type == Schema::FieldType::CHARARRAY) { COMPARE_FIELDS_WITH_TYPE(Schema::CharArrayField, field1, field2); } throw std::runtime_error("Compare Schema Fields - Should NOT Reach Here."); return 0; } int RecordBase::DumpToMem(byte* buf) const { if (!buf) { return -1; } uint32 offset = 0; for (const auto& field: fields_) { offset += field->DumpToMem(buf + offset); } if (offset != RecordBase::size()) { LogFATAL("Record dump %d byte, record.size() = %d", offset, size()); } return offset; } int RecordBase::LoadFromMem(const byte* buf) { if (!buf) { return -1; } uint32 offset = 0; for (const auto& field: fields_) { offset += field->LoadFromMem(buf + offset); } if (offset != RecordBase::size()) { LogFATAL("Record load %d byte, record.size() = %d", offset, size()); } return offset; } int RecordBase::InsertToRecordPage(RecordPage* page) const { int slot_id = page->InsertRecord(size()); if (slot_id >= 0) { // Write the record content to page. DumpToMem(page->Record(slot_id)); return slot_id; } return -1; } RecordBase* RecordBase::Duplicate() const { RecordBase* new_record = new RecordBase(); new_record->fields_ = fields_; return new_record; } bool RecordBase::CopyFieldsFrom(const RecordBase& source) { fields_ = source.fields_; return true; } void RecordBase::reset() { for (auto& field: fields_) { field->reset(); } } void RecordBase::clear() { fields_.clear(); } void RecordBase::AddField(const DB::TableField& field_info) { auto field_type = field_info.type(); if (field_type == Schema::FieldType::INT) { AddField(new Schema::IntField()); } if (field_type == Schema::FieldType::LONGINT) { AddField(new Schema::LongIntField()); } if (field_type == Schema::FieldType::DOUBLE) { AddField(new Schema::DoubleField()); } if (field_type == Schema::FieldType::BOOL) { AddField(new Schema::BoolField()); } if (field_type == Schema::FieldType::CHAR) { AddField(new Schema::CharField()); } if (field_type == Schema::FieldType::STRING) { AddField(new Schema::StringField()); } if (field_type == Schema::FieldType::CHARARRAY) { AddField(new Schema::CharArrayField(field_info.size())); } } bool RecordBase::InitRecordFields(const DB::TableInfo& schema, const std::vector<uint32>& indexes) { clear(); for (int index: indexes) { AddField(schema.fields(index)); } return true; } // Check fields type match a schema. bool RecordBase::CheckFieldsType(const DB::TableInfo& schema, std::vector<uint32> key_indexes) const { if (fields_.size() != key_indexes.size()) { LogERROR("Index/TreeNode record has mismatchig number of fields - " "key has %d fields, record has %d fields", key_indexes.size(), fields_.size()); return false; } for (int i = 0; i < (int)key_indexes.size(); i++) { if (!fields_[i] || !fields_[i]->MatchesSchemaType( schema.fields(key_indexes[i]).type())) { LogERROR("Index/TreeNode record has mismatchig field type with schema " "field %d", key_indexes[i]); return false; } } return true; } bool RecordBase::CheckFieldsType(const DB::TableInfo& schema) const { if ((int)fields_.size() != schema.fields_size()) { LogERROR("Data record has mismatchig number of fields with schema - " "schema has %d indexes, record has %d", schema.fields_size(), fields_.size()); return false; } for (int i = 0; i < (int)schema.fields_size(); i++) { if (!fields_[i] || !fields_[i]->MatchesSchemaType( schema.fields(i).type())) { LogERROR("Data record has mismatchig field type with schema field %d", i); return false; } } return true; } bool RecordBase::ParseFromText(std::string str, int chararray_len_limit) { auto tokens = Strings::Split(str, '|'); for (auto& block: tokens) { block = Strings::Strip(block); if (block.length() == 0) { continue; } auto pieces = Strings::Split(block, ':'); if ((int)pieces.size() != 2) { continue; } for (int i = 0; i < (int)pieces.size(); i++) { pieces[i] = Strings::Strip(pieces[i]); pieces[i] = Strings::Strip(pieces[i], "\"\""); } if (pieces[0] == "Int") { AddField(new Schema::IntField(std::stoi(pieces[1]))); } else if (pieces[0] == "LongInt") { AddField(new Schema::LongIntField(std::stol(pieces[1]))); } else if (pieces[0] == "Double") { AddField(new Schema::DoubleField(std::stod(pieces[1]))); } else if (pieces[0] == "Bool") { AddField(new Schema::BoolField(std::stoi(pieces[1]))); } else if (pieces[0] == "String") { AddField(new Schema::StringField(pieces[1])); } else if (pieces[0] == "CharArray") { AddField(new Schema::CharArrayField(pieces[1], chararray_len_limit)); } } return (int)fields_.size() > 0; } // ****************************** DataRecord ******************************** // bool DataRecord::ExtractKey( RecordBase* key, const std::vector<uint32>& key_indexes) const { if (!key) { return false; } key->fields().clear(); for (uint32 index: key_indexes) { if (index > fields_.size()) { LogERROR("key_index %d > number of fields, won't fetch"); continue; } key->fields().push_back(fields_.at(index)); } return true; } RecordBase* DataRecord::Duplicate() const { DataRecord* new_record = new DataRecord(); new_record->fields_ = fields_; return new_record; } // ***************************** IndexRecord ******************************** // int IndexRecord::DumpToMem(byte* buf) const { if (!buf) { return -1; } uint32 offset = RecordBase::DumpToMem(buf); offset += rid_.DumpToMem(buf + offset); if (offset != size()) { LogFATAL("IndexRecord DumpToMem error - expect %d bytes, actual %d", size(), offset); } return offset; } int IndexRecord::LoadFromMem(const byte* buf) { if (!buf) { return -1; } uint32 offset = RecordBase::LoadFromMem(buf); offset += rid_.LoadFromMem(buf + offset); if (offset != size()) { LogFATAL("IndexRecord LoadFromMem error - expect %d bytes, actual %d", size(), offset); } return offset; } void IndexRecord::Print() const { RecordBase::PrintImpl(); rid_.Print(); } uint32 IndexRecord::size() const { return RecordBase::size() + rid_.size(); } RecordBase* IndexRecord::Duplicate() const { IndexRecord* new_record = new IndexRecord(); new_record->fields_ = fields_; new_record->rid_ = rid_; return new_record; } void IndexRecord::reset() { RecordBase::reset(); rid_.set_page_id(-1); rid_.set_slot_id(-1); } // **************************** TreeNodeRecord ****************************** // int TreeNodeRecord::DumpToMem(byte* buf) const { if (!buf) { return -1; } uint32 offset = RecordBase::DumpToMem(buf); memcpy(buf + offset, &page_id_, sizeof(page_id_)); offset += sizeof(page_id_); if (offset != size()) { LogFATAL("TreeNodeRecord DumpToMem error - expect %d bytes, actual %d", size(), offset); } return offset; } int TreeNodeRecord::LoadFromMem(const byte* buf) { if (!buf) { return -1; } uint32 offset = RecordBase::LoadFromMem(buf); memcpy(&page_id_, buf + offset, sizeof(page_id_)); offset += sizeof(page_id_); if (offset != size()) { LogFATAL("TreeNodeRecord LoadFromMem error - expect %d bytes, actual %d", size(), offset); } return offset; } void TreeNodeRecord::Print() const { RecordBase::PrintImpl(); std::cout << "page_id = " << page_id_ << std::endl; } uint32 TreeNodeRecord::size() const { return RecordBase::size() + sizeof(page_id_); } RecordBase* TreeNodeRecord::Duplicate() const { TreeNodeRecord* new_record = new TreeNodeRecord(); new_record->fields_ = fields_; new_record->page_id_ = page_id_; return new_record; } void TreeNodeRecord::reset() { RecordBase::reset(); page_id_ = -1; } } // namespace Storage
[ "yuanhang3260@gmail.com" ]
yuanhang3260@gmail.com
877cae8f9b0ff37c98ed5f8c69ccaa9094b3213f
260f53f6449249e20ccbddedbbe854a1ef169d08
/operators/multiply.cpp
f33b88f83085324db2c18be0cb2a3f02a1a661c5
[]
no_license
ArnavMohan/ACP_KANBAN
048712eaf4235ecab5e967a35f492b7e1db242cf
5fa5b2cd569737f4ba54c0563d2e04341754dcf6
refs/heads/master
2021-08-30T05:13:11.085828
2017-12-16T04:40:50
2017-12-16T04:40:50
112,633,309
0
0
null
2017-12-12T15:04:23
2017-11-30T16:21:31
C++
UTF-8
C++
false
false
682
cpp
//Author: Rishi //Operator: * //Purpose: return the product of two complex numbers #include "../complex.h" complex operator*(const complex &lhs, const complex &rhs){ //foil out the two sides into First, Outisde, Inside, Last. double first_foil = real(&lhs) * real(&rhs); double outisde_foil = real(&lhs) * imag(&rhs); double inside_foil = imag(&lhs) * real(&rhs); double last_foil = imag(&lhs) * imag(&rhs); //product refers to the product of the two params //it's the item to be returned double product_real = first_foil - last_foil; double product_imag = outside_foil + inside_foil; complex product = new complex(product_real, product_imag); return product; }
[ "rishi.chandnap6@stu.austinisd.org" ]
rishi.chandnap6@stu.austinisd.org
02d4e8feb321728110066055f580877ebf80f484
7cc47471cfd061d77409c4cbb9081f6de21e0fe7
/Notes/Stack/htmlValidator/finish/html_fragment_validate.cpp
e0666b555491e92ccf2fa6e27be580b0439c65af
[]
no_license
kevinkuriachan/CSCE121
29e59e515ec51228a97e5d8536f793a990fd8730
a6a988d6093e1225a50c12a893cde18e20cfe7cc
refs/heads/master
2020-03-12T10:52:37.031613
2018-12-07T05:29:57
2018-12-07T05:29:57
130,583,210
2
0
null
null
null
null
UTF-8
C++
false
false
4,434
cpp
/* Basic HTML validator. Ok, a really, really basic one. */ #include <iostream> #include <fstream> #include <string> #include <assert.h> #include "stack.h" int main(int argc, char *argv[]) { stack_t *tag_stack = NULL; if (argc != 2) { cerr << "Usage: " << argv[0] << " <input.html>" << endl; return 1; } tag_stack = create_stack(); ifstream infile; // Open the file infile.open(argv[1], ios_base::in); if (!infile) { cerr << "Couldn't open '" << argv[1] << "', for reading." << endl; //exit(1); return 1; } bool document_valid = true; string error_msg; int line_count = 0; string line; size_t pos; // Read in the file while (getline(infile, line)) { //cout << "Line #" << line_count << " '" << line << "'" << endl; // Process line: line_count++; bool finished_line = false; size_t pos, last_pos = 0; while (!finished_line) { pos = line.find('<', last_pos); if (pos != string::npos) { // found opening, now find closing size_t pos2 = line.find('>', pos); if (pos2 != string::npos) { string tag = line.substr(pos, pos2 - pos + 1); //cout << "Got tag '" << tag << "'" << endl; if (tag[1] != '/') { // Opening tag push_on_stack(tag_stack, tag); } else { // Closing tag if (is_empty_stack(tag_stack)) { error_msg = "Line #"+to_string(line_count)+": closing tag '" + tag + "' without opening one"; document_valid = false; // No closing! break; } else { string top = pop_off_stack(tag_stack); //cout << "Popped tag '" << top << "'" << endl; string l = top.substr(1,top.size()-2); //cout << "Popped trimmed to '" << l << "'" << endl; string r = tag.substr(2,tag.size()-3); //cout << "Compare with '" << r << "'" << endl; if (r != l) { error_msg = "Line #"+to_string(line_count)+": '" + top + "' doesn't make sense with '" + tag + "'"; document_valid = false; // No closing! break; } } } last_pos += pos2 + 1; // Move past this character } else { last_pos += line.size(); error_msg = "Line #"+to_string(line_count)+": no closing >"; document_valid = false; // No closing! break; } } else { // Check that there are no closing > without opening ones. pos = line.find('>', last_pos); if (pos != string::npos) { finished_line = true; error_msg = "Line #"+to_string(line_count)+": has closing > without opening <"; document_valid = false; // No closing! break; } else finished_line = true; } } if (!document_valid) break; // May as well quit now. } infile.close(); // Are there any reminants on the stack? if ((document_valid) && (!is_empty_stack(tag_stack))) { error_msg = "Unclosed tags"; while (!is_empty_stack(tag_stack)) error_msg += " '" + pop_off_stack(tag_stack) + "'"; error_msg += " remain on the stack"; document_valid = false; // No closing! } if (document_valid) { cout << "File '" << argv[1] << "' passed my basic santity checks for valid HTML." << endl; } else { cout << "File '" << argv[1] << "' is not valid HTML." << endl; cout << error_msg << endl; } destroy_stack(tag_stack); return 0; }
[ "kevinkuriachan@compute.cs.tamu.edu" ]
kevinkuriachan@compute.cs.tamu.edu
272adcb5ff68ac7642c544e9b073b84d7d65501e
1c24264c0884b709a7943f30dd157d92168581d0
/Programming_Principles_and_Practice_Using_C++/14_Graphics_Class_Design/Window.h
78d468d39c88e3f51b12a16900e4b304facdb505
[ "MIT" ]
permissive
KoaLaYT/Learn-Cpp
56dbece554503ca2e0d1bea35ae4ddda3c03f236
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
refs/heads/master
2020-12-22T13:08:02.582113
2020-10-26T02:33:24
2020-10-26T02:33:24
236,792,487
0
0
null
null
null
null
UTF-8
C++
false
false
1,353
h
#ifndef WINDOW_GUARD #define WINDOW_GUARD 1 #include "Point.h" #include "fltk.h" #include "std_lib_facilities.h" namespace Graph_lib { class Shape; // "forward declare" Shape class Widget; class Window : public Fl_Window { public: Window(int w, int h, const string& title); // let the system pick the location Window(Point xy, int w, int h, const string& title); // top left corner in xy virtual ~Window() {} int x_max() const { return w; } int y_max() const { return h; } void resize(int ww, int hh) { w = ww, h = hh; size(ww, hh); } void set_label(const string& s) { label(s.c_str()); } void attach(Shape& s); void attach(Widget& w); void detach(Shape& s); // remove s from shapes void detach(Widget& w); // remove w from window (deactivate callbacks) void put_on_top(Shape& p); // put p on top of other shapes protected: void draw(); private: vector<Shape*> shapes; // shapes attached to window int w, h; // window size void init(); }; int gui_main(); // invoke GUI library's main event loop inline int x_max() { return Fl::w(); } // width of screen in pixels inline int y_max() { return Fl::h(); } // height of screen in pixels } // namespace Graph_lib #endif
[ "hytohyeah@outlook.com" ]
hytohyeah@outlook.com
606dbe0ea9f6f05a99e2d6765c35038d176b66af
c237ea629b644b698476c6965eb6988df46f92a8
/alg6 - aula1.cpp
d602c81ec32be76d3dd6f6864017fac4541ac47a
[]
no_license
danielrsouza/algoritimos-C
858957360dd23d74b9185dc28223d55dc753036d
59ae45dae0448631e2af9854c1a10c3b3ceff57c
refs/heads/master
2020-04-25T19:16:08.408297
2019-02-28T00:39:31
2019-02-28T00:39:31
173,010,231
0
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
#include<stdio.h> main(){ float n1, n2, n3, media; printf("Digite a nota 1: \n"); scanf("%f",&n1); printf("Digite a nota 2: \n"); scanf("%f",&n2); printf("Digite a nota 3: \n"); scanf("%f",&n3); media = (n1+n2+n3)/3; printf("O resultado e: %f",media); if(media > 7){ printf("voce foi aprovado."); }else{ printf("voce foi reprovado."); } }
[ "daniel.ricardo@rede.ulbra.br" ]
daniel.ricardo@rede.ulbra.br
10737407f220c683515313bd229dda5455aa3905
d7db098f4b1d1cd7d32952ebde8106e1f297252e
/AtCoder/ARC/040/B.cpp
6dbc9f996121e4c8845183c2a113c01b8e1be77c
[]
no_license
monman53/online_judge
d1d3ce50f5a8a3364a259a78bb89980ce05b9419
dec972d2b2b3922227d9eecaad607f1d9cc94434
refs/heads/master
2021-01-16T18:36:27.455888
2019-05-26T14:03:14
2019-05-26T14:03:14
25,679,069
0
0
null
null
null
null
UTF-8
C++
false
false
420
cpp
#include <iostream> #include <algorithm> using namespace std; int main(){ int n, r; string s; int time=0; cin >> n >> r; cin >> s; int start; for(int i=n-1;i>=0;i--){ if(s[i] == '.'){ time+=max(0,i-r+1); break; } } for(int i=n-1;i>=0;){ if(s[i] == '.'){ i -= r; time++; }else if(s[i] == 'o'){ i--; } } cout << time << '\n'; return 0; }
[ "tetsuro53@gmail.com" ]
tetsuro53@gmail.com
f8a9e2b9769f1f6e35d08652f7c2bb950f2c209f
003f58454dd3cf9af1821b28e68f1f738d244d5e
/kernel/virtio/Network.cpp
84ebc7b9b986fd54fa81880628c9fe5c6564913d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
busybox11/skift
7b5fd54e57e03ad23ab08b8ee8a8edb81a348c2d
778ae3a0dc5ac29d7de02200c49d3533e47854c5
refs/heads/master
2023-01-04T21:38:24.421418
2020-08-09T15:02:17
2020-08-09T15:02:17
279,430,614
1
0
NOASSERTION
2020-07-13T23:10:19
2020-07-13T23:10:19
null
UTF-8
C++
false
false
304
cpp
#include <libsystem/Logger.h> #include "kernel/bus/PCI.h" #include "kernel/virtio/Virtio.h" bool virtio_network_match(DeviceInfo info) { return virtio_is_specific_virtio_device(info, VIRTIO_DEVICE_NETWORK); } void virtio_network_initialize(DeviceInfo info) { virtio_device_initialize(info); }
[ "nicolas.van.bossuyt@gmail.com" ]
nicolas.van.bossuyt@gmail.com
05fcfb6e43f4bfd920027d73e74388d65325418c
f9a0c4ac2e3c303670f0d277bedfaaf27cb2b120
/ee569/FMeasure.cpp
b088deeae6861132745fbd646e6c76846b1c0be7
[]
no_license
gbudiman/ee569
d0fdbd4e0e7b01a02ad966b5eb9615740ca6a6d5
fefe9770121ac2dfbfdcd6cb39193d20b5505f33
refs/heads/master
2021-05-01T06:56:29.068732
2016-11-04T23:50:41
2016-11-04T23:50:41
66,734,259
0
0
null
null
null
null
UTF-8
C++
false
false
1,453
cpp
// // FMeasure.cpp // ee569 // // Created by Gloria Budiman on 10/17/16. // Finalized on 10/31/16 // gbudiman@usc.edu 6528-1836-50 // Copyright © 2016 gbudiman. All rights reserved. // #include "FMeasure.hpp" FMeasure::FMeasure(Picture _base) { base = _base; dim_x = _base.get_dim_x(); dim_y = _base.get_dim_y(); result = Picture("", dim_x, dim_y, COLOR_RGB); } void FMeasure::compare_against(Picture _other) { int false_positive, false_negative, true_positive, true_negative; result.compare_f_measure(base, _other, true_positive, true_negative, false_negative, false_positive); printf("%5.1f%% %5.1f%% %5.1f%% %5.1f%%\n", f_float(true_positive), f_float(true_negative), f_float(false_positive), f_float(false_negative)); printf(" Precision: %5.2f | Recall: %5.2f\n", f_precision(true_positive, false_positive), f_recall(true_positive, false_negative)); printf(" F: %5.2f\n", f_compute(true_positive, true_negative, false_positive, false_negative)); } float FMeasure::f_float(int x) { return (float) x * 100 / (float) (dim_x * dim_y); } float FMeasure::f_compute(int tp, int tn, int fp, int fn) { float precision = f_precision(tp, fp); float recall = f_recall(tp, fn); return 2 * precision * recall / (precision + recall); } float FMeasure::f_precision(int tp, int fp) { return (float) tp / (float) (tp + fp); } float FMeasure::f_recall(int tp, int fn) { return (float) tp / (float) (tp + fn); }
[ "wahyu.g@gmail.com" ]
wahyu.g@gmail.com
c4f0254b63e398e8e20a841579f62fbfe37771d7
6b580bb5e7bbf83e0d9845818678fbb85ea14450
/aws-cpp-sdk-chime-sdk-media-pipelines/include/aws/chime-sdk-media-pipelines/model/ListTagsForResourceResult.h
5a05120ec7422740212b626619d536fc87536b50
[ "MIT", "Apache-2.0", "JSON" ]
permissive
dimatd/aws-sdk-cpp
870634473781731822e2636005bc215ad43a0339
3d3f3d0f98af842e06d3d74648a0fca383538bb3
refs/heads/master
2022-12-21T20:54:25.033076
2022-12-13T18:18:00
2022-12-13T18:18:00
219,980,346
0
0
Apache-2.0
2019-11-06T11:23:20
2019-11-06T11:23:20
null
UTF-8
C++
false
false
2,078
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/chime-sdk-media-pipelines/ChimeSDKMediaPipelines_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/chime-sdk-media-pipelines/model/Tag.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace ChimeSDKMediaPipelines { namespace Model { class AWS_CHIMESDKMEDIAPIPELINES_API ListTagsForResourceResult { public: ListTagsForResourceResult(); ListTagsForResourceResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); ListTagsForResourceResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The tag key-value pairs.</p> */ inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; } /** * <p>The tag key-value pairs.</p> */ inline void SetTags(const Aws::Vector<Tag>& value) { m_tags = value; } /** * <p>The tag key-value pairs.</p> */ inline void SetTags(Aws::Vector<Tag>&& value) { m_tags = std::move(value); } /** * <p>The tag key-value pairs.</p> */ inline ListTagsForResourceResult& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;} /** * <p>The tag key-value pairs.</p> */ inline ListTagsForResourceResult& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;} /** * <p>The tag key-value pairs.</p> */ inline ListTagsForResourceResult& AddTags(const Tag& value) { m_tags.push_back(value); return *this; } /** * <p>The tag key-value pairs.</p> */ inline ListTagsForResourceResult& AddTags(Tag&& value) { m_tags.push_back(std::move(value)); return *this; } private: Aws::Vector<Tag> m_tags; }; } // namespace Model } // namespace ChimeSDKMediaPipelines } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
0a040f07afc11a87345a30c7fd994772f0ed972b
a13a4dfcf577632bee9bfbc430ce469c1afe6652
/libraries/ros_lib/pano_ros/PanoCaptureFeedback.h
313e0be22d316aaecbf276c16cae6c87879aa4a4
[]
no_license
kirancps/ROS_Arduino
5cb8abeea6f87c2a8fa332ea9ebedc325ae5a0fb
537b45aa9c200e8f5be9a8f4625e045c6a7a8509
refs/heads/master
2021-01-10T18:52:58.914367
2016-04-17T11:23:07
2016-04-17T11:23:07
56,432,459
2
4
null
null
null
null
UTF-8
C++
false
false
1,687
h
#ifndef _ROS_pano_ros_PanoCaptureFeedback_h #define _ROS_pano_ros_PanoCaptureFeedback_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace pano_ros { class PanoCaptureFeedback : public ros::Msg { public: float n_captures; PanoCaptureFeedback(): n_captures(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { float real; uint32_t base; } u_n_captures; u_n_captures.real = this->n_captures; *(outbuffer + offset + 0) = (u_n_captures.base >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (u_n_captures.base >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (u_n_captures.base >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (u_n_captures.base >> (8 * 3)) & 0xFF; offset += sizeof(this->n_captures); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { float real; uint32_t base; } u_n_captures; u_n_captures.base = 0; u_n_captures.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0); u_n_captures.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); u_n_captures.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); u_n_captures.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); this->n_captures = u_n_captures.real; offset += sizeof(this->n_captures); return offset; } const char * getType(){ return "pano_ros/PanoCaptureFeedback"; }; const char * getMD5(){ return "22ff7abf8b5e4a280047b5a08afb8cf1"; }; }; } #endif
[ "scikiran@gmail.com" ]
scikiran@gmail.com
cc5739cf68c7cfc582d2335a8f45542eaf1c5bba
4e5fa5da1ffeb9d1a2e01c1145ab0bec9b424a2d
/Letters/Letters/Letters.cpp
b9a276a7662853ab6d1ac86cf600419790132645
[]
no_license
PLaG-In/MLITA
a441bf670f500abcaa94cd04b60ec6fb5a621196
2e50290e4bfbae2a2a0eb7c8a8cadaad3ab0d9ab
refs/heads/master
2021-05-30T09:40:57.852100
2016-01-21T17:38:11
2016-01-21T17:38:11
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,448
cpp
// Letters.cpp: определяет точку входа для консольного приложения. // #include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <map> #include <algorithm> using namespace std; void CheckWords(map <string, int> &dict, const string &mainWord) { int counter, score = 0; int pos; std::vector<std::pair<string, int>> items; string tempWord = mainWord; /*sort(dict.begin(), dict.end());*/ for (auto it = dict.begin(); it != dict.end(); ++it) { string elem = it->first; counter = 0; tempWord = mainWord; for (size_t i = 0; i < elem.length(); ++i) { pos = tempWord.find(elem[i]); if (pos != -1) { counter++; tempWord[pos] = '0'; } else { counter = 0; } } score += counter; dict[elem] += counter; } ofstream fout("output.txt"); fout << score << endl; for (auto it = dict.begin(); it != dict.end(); ++it) { if (it->second != 0){ items.push_back(pair<string, int>(it->first, it->second)); } } std::sort(items.begin(), items.end()); for (auto it = items.begin(); it != items.end(); ++it) { fout << it->first << endl; } } int main(int argc, char* argv[]) { ifstream fin("input.txt"); string mainWord, tempWord; fin >> mainWord; map <string, int> dict; while (!fin.eof()) { fin >> tempWord; dict.insert(pair<string, int>(tempWord, 0)); } CheckWords(dict, mainWord); return 0; }
[ "vladimir.alt@inbox.ru" ]
vladimir.alt@inbox.ru
2a5012ad07fc50dfc116c9465cca18119a211893
914b2437727654ef663c9c9795715598597b8eba
/AncillaryDataEvent/TaggerModule.h
dc4093c59a9d8fa03979ebebc5f5631ed78a3f18
[ "BSD-3-Clause" ]
permissive
fermi-lat/AncillaryDataEvent
362ae7384513be6ea90cba5b00ffb880ba05cc5c
4f8f9677971b36628b0949e3ccd8b708e4932c38
refs/heads/master
2022-02-17T03:07:33.552130
2019-08-27T17:26:54
2019-08-27T17:26:54
103,186,826
0
0
null
null
null
null
UTF-8
C++
false
false
911
h
#ifndef TAGGERMODULE_HH #define TAGGERMODULE_HH #include "TaggerLayer.h" class TaggerModule { public: TaggerModule(int moduleId); ~TaggerModule(); void processData(); void resetData(); int getId() const {return m_moduleId;} TaggerLayer *getLayer(int layerId) const {return m_layers[layerId];} TaggerChannel *getChannel(int layerId, int channelId) const {return getLayer(layerId)->getChannel(channelId);} double getXCrossingPosition() const {return m_xCrossingPosition;} double getXCrossingError() const {return m_xCrossingError;} double getYCrossingPosition() const {return m_yCrossingPosition;} double getYCrossingError() const {return m_yCrossingError;} private: int m_moduleId; TaggerLayer *m_layers[N_LAYERS_PER_MODULE]; double m_xCrossingPosition; double m_xCrossingError; double m_yCrossingPosition; double m_yCrossingError; }; #endif
[ "" ]
09eb4ede6f8b9421e02a382c8415e6b57e5b6e80
16137a5967061c2f1d7d1ac5465949d9a343c3dc
/cpp_code/iostreams/07-ofstreams-pos.cc
3d9931ad19e08a0f679010cc1ea2d5cbbff6b8f0
[]
no_license
MIPT-ILab/cpp-lects-rus
330f977b93f67771b118ad03ee7b38c3615deef3
ba8412dbf4c8f3bee7c6344a89e0780ee1dd38f2
refs/heads/master
2022-07-28T07:36:59.831016
2022-07-20T08:34:26
2022-07-20T08:34:26
104,261,623
27
4
null
2021-02-04T21:39:23
2017-09-20T19:56:44
TeX
UTF-8
C++
false
false
282
cc
#include <iostream> #include <fstream> int main (void) { std::ofstream outfile("sample.tmp"); outfile << "This is an apple"; // auto pos = outfile.tellp(); // outfile.seekp (pos - static_cast<decltype(pos)>(7)); outfile.seekp (-7, std::ios::cur); outfile << " sam"; }
[ "konstantin.vladimirov@gmail.com" ]
konstantin.vladimirov@gmail.com
27ea713204f216324c15f633a5c574aa95ebee3e
d535109f8406a7c4cf8238bd03f1c584ad6464aa
/aliyun-api-pts/2015-08-01/src/ali_pts_get_tasks.cc
3e43a981c66e1591b5a51edcff1f5f968d22f567
[ "Apache-2.0" ]
permissive
bailehang/aliyun
3cf08cb371e55fbff59fc3908e5c47c27b861af1
ca80fb97ce2b4d10bfb5fd8252c730a995354646
refs/heads/master
2020-05-23T11:17:00.183793
2015-11-16T01:41:03
2015-11-16T01:41:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,713
cc
#include <stdio.h> #include "ali_api_core.h" #include "ali_string_utils.h" #include "ali_pts.h" #include "json/value.h" #include "json/reader.h" using namespace aliyun; namespace { void Json2Type(const Json::Value& value, std::string* item); void Json2Type(const Json::Value& value, PTSGetTasksResponseType* item); template<typename T> class Json2Array { public: Json2Array(const Json::Value& value, std::vector<T>* vec) { if(!value.isArray()) { return; } for(int i = 0; i < value.size(); i++) { T val; Json2Type(value[i], &val); vec->push_back(val); } } }; void Json2Type(const Json::Value& value, std::string* item) { *item = value.asString(); } void Json2Type(const Json::Value& value, PTSGetTasksResponseType* item) { if(value.isMember("Tasks")) { item->tasks = value["Tasks"].asString(); } } } int PTS::GetTasks(const PTSGetTasksRequestType& req, PTSGetTasksResponseType* response, PTSErrorInfo* error_info) { std::string str_response; int status_code; int ret = 0; bool parse_success = false; std::string secheme = this->use_tls_ ? "https" : "http"; AliRpcRequest* req_rpc = new AliRpcRequest(version_, appid_, secret_, secheme + "://" + host_); Json::Value val; Json::Reader reader; req_rpc->AddRequestQuery("Action","GetTasks"); if(!req.status.empty()) { req_rpc->AddRequestQuery("Status", req.status); } if(!this->region_id_.empty()) { req_rpc->AddRequestQuery("RegionId", this->region_id_); } if(req_rpc->CommitRequest() != 0) { if(error_info) { error_info->code = "connect to host failed"; } ret = -1; goto out; } status_code = req_rpc->WaitResponseHeaderComplete(); req_rpc->ReadResponseBody(str_response); if(status_code > 0 && !str_response.empty()){ parse_success = reader.parse(str_response, val); } if(!parse_success) { if(error_info) { error_info->code = "parse response failed"; } ret = -1; goto out; } if(status_code!= 200 && error_info && parse_success) { error_info->request_id = val.isMember("RequestId") ? val["RequestId"].asString(): ""; error_info->code = val.isMember("Code") ? val["Code"].asString(): ""; error_info->host_id = val.isMember("HostId") ? val["HostId"].asString(): ""; error_info->message = val.isMember("Message") ? val["Message"].asString(): ""; } if(status_code== 200 && response) { Json2Type(val, response); } ret = status_code; out: delete req_rpc; return ret; }
[ "zcy421593@126.com" ]
zcy421593@126.com
f71934402f18d768ba32d6db90931fdb24ef1b03
668c7477acc16c366196d8655dd554496c396a1b
/test/InstanceTests.cpp
606959d27e571d446077c4c2341c971073d0c569
[ "Unlicense" ]
permissive
lucasmpavelski/fsp-eval
1eb9de961b168e761891c6f205972695b00db35b
4a26be3af341324e9de106318f28c06027e3abd8
refs/heads/master
2023-02-09T14:53:33.208783
2021-01-01T14:00:12
2021-01-01T14:00:12
319,150,871
0
0
null
null
null
null
UTF-8
C++
false
false
1,340
cpp
#include <catch2/catch.hpp> #include <vector> #include <vector> #include "../src/Instance.hpp" using namespace fsp; TEST_CASE("FSP data load from vector", "[fsp]") { const std::vector<unsigned> procTimes = { 1, 2, 3, 4, 5, 6 }; const int no_jobs = 2; Instance instance(procTimes, no_jobs); SECTION("number of machines is determined") { REQUIRE(instance.noMachines() == 3); } SECTION("vector is read by row") { REQUIRE(instance.pt(0, 1) == 2); } } TEST_CASE("FSP data load from vector by jobs", "[fsp]") { const std::vector<unsigned> procTimes = { 1, 2, 3, 4, 5, 6 }; const int no_jobs = 2; const bool jobsByMachines = true; Instance instance(procTimes, no_jobs, jobsByMachines); SECTION("vector is read by row") { REQUIRE(instance.pt(0, 1) == 4); } } TEST_CASE("FSP data load from file", "[fsp]") { Instance instance("test/instance.txt"); SECTION("dimensions are correct") { REQUIRE(instance.noJobs() == 4); REQUIRE(instance.noMachines() == 5); } SECTION("processing times are loaded") { REQUIRE(instance.pt(0, 0) == 5); REQUIRE(instance.pt(0, 1) == 9); } } TEST_CASE("FSP data can be compared with equals operator", "[fsp]") { Instance instance1("test/instance.txt"); Instance instance2("test/instance.txt"); REQUIRE(instance1 == instance2); }
[ "lmpavelski@yahoo.com.br" ]
lmpavelski@yahoo.com.br
f08648ecaf1e93558fe5f662754ab8e10fda4363
28ccd518e0c516f5e6dfce5b8373ba4a028d22ca
/14.10/marini/random.h
85e1528b0c7077dc376af7b688ea79b0bb0907db
[]
no_license
eugnsp/CUJ
a3fd72f81ac18460febc090bb8be0c21164750b4
922ecf8f730a193dab63ec790c0b655477732dcf
refs/heads/master
2023-08-19T07:48:19.948674
2021-09-19T08:55:58
2021-09-19T09:00:49
357,140,243
3
1
null
null
null
null
UTF-8
C++
false
false
3,856
h
/* * random.h * Header file for the implementation of a random number * generator class. This class is based on the algorithm defined * by Z(i) = AZ(i-1)modM. Where M is the prime number 2^31-1 = * 2,147,483,647 and A is the value 62089911. */ #include <values.h> #include <math.h> // Unform Random Generator Class Definition (PMMLCG) class RandomGenerator { // Generate U(0,1) public: RandomGenerator(void); // virtual ~RandomGenerator(void); virtual double Rand(void); void Reset(void); static void ResetStreamCount(); static void SelectSeed(long int seed); protected: long int current_seed; private: static int stream_count; static long int base_seed; long int my_start_seed; }; // RandomGenerator Inline Functions inline void RandomGenerator::ResetStreamCount(void) { stream_count = 0; } inline void RandomGenerator::SelectSeed(long int seed) { base_seed = seed; } inline void RandomGenerator::Reset(void) { current_seed = my_start_seed; } // End of RandomGenerator // Uniform Random Generator Class Definition -- Generate U(a,b) class UniformRandomGenerator : public RandomGenerator { public: UniformRandomGenerator(double high_limit = 1.0, double low_limit = 0.0); // virtual ~UniformRandomGenerator(void); double Rand(void); private: double A; double B; }; // UniformRandomGenerator Inline Functions inline UniformRandomGenerator::UniformRandomGenerator(double high_limit, double low_limit) : RandomGenerator(), A(low_limit), B(high_limit) { // Constructor does nothing special } inline double UniformRandomGenerator::Rand(void) { // return Z = A + (B-A)*U(0,1) return A + ((B - A) * RandomGenerator::Rand()); } // End of UniformRandomGenerator // Exponential Random Generator Class Def. -- Gen. Exp(a) class ExponentialRandomGenerator : public RandomGenerator { public: ExponentialRandomGenerator(double m = 1.0); // virtual ~ExponentialRandomGenerator(void); double Rand(void); private: double mean; }; // ExponentialRandomGenerator Inline Functions inline ExponentialRandomGenerator::ExponentialRandomGenerator(double m) : RandomGenerator(), mean(m) { // Constructor does nothing special } inline double ExponentialRandomGenerator::Rand(void) { // return Z = -1*mean*ln(U(0,1)) return -1.0 * mean * log(RandomGenerator::Rand()); } // End of ExponentialRandomGenerator // Triangle Random Generator Class Def. -- Generate Triang(a,b,c) class TriangleRandomGenerator : public RandomGenerator { public: TriangleRandomGenerator(double high_limit = 1.0, double low_limit = 0.0, double cut_value = 0.5); // virtual ~TriangleRandomGenerator(void); double Rand(void); private: double A; double B; double C; }; // TriangleRandomGenerator Inline Function inline TriangleRandomGenerator::TriangleRandomGenerator( double high_limit,double low_limit, double cut_value) : RandomGenerator(), A(low_limit), B(high_limit) { // Calculate bend value C = (cut_value - A) / (B - A); } inline double TriangleRandomGenerator::Rand(void) { /* * If U(0,1) <= C, then return A + (B-A)*sqrt(C*U(0,1)) * otherwise * return A + (B-A)*(1 - sqrt((1-C) * (1 - U(0,1)))) */ double x = RandomGenerator::Rand(); if (x <= C) return A + (B - A) * sqrt(C * x); else return A + (B - A) * (1.0 - sqrt((1.0 - C)*(1.0 - x))); } // End of ExponentialRandomGenerator
[ "evgeny.sg@gmail.com" ]
evgeny.sg@gmail.com
d85c02212a408a89e2bcccae450d8cbacfc94d17
9cd87733a1958baa0e5c9fdee5e78f05f0ef7d36
/kdtree2.cpp
391296a65eb24b7ddc31f5a9366035c39cbbe923
[]
no_license
brantr/shock-tracking
4f754b2f3554486e9748f5a3278128b2d210ab32
60dab0327f07da2787b59809544b8cbb79c8ace1
refs/heads/master
2021-01-19T16:43:08.587659
2017-04-14T16:35:49
2017-04-14T16:35:49
88,284,529
0
0
null
null
null
null
UTF-8
C++
false
false
25,212
cpp
// // (c) Matthew B. Kennel, Institute for Nonlinear Science, UCSD (2004) // // Licensed under the Academic Free License version 1.1 found in file LICENSE // with additional provisions in that same file. // NB:license included in comments at the end of this file #include "kdtree2.hpp" #include <algorithm> #include <iostream> #include <stdio.h> // utility inline float squared(const float x) { return(x*x); } inline void swap(int& a, int&b) { int tmp; tmp = a; a = b; b = tmp; } inline void swap(float& a, float&b) { float tmp; tmp = a; a = b; b = tmp; } // // KDTREE2_RESULT implementation // inline bool operator<(const kdtree2_result& e1, const kdtree2_result& e2) { return (e1.dis < e2.dis); } // // KDTREE2_RESULT_VECTOR implementation // float kdtree2_result_vector::max_value() { return( (*begin()).dis ); // very first element } vector<kdtree2_result>::iterator kdtree2_result_vector::lower_bound (const kdtree2_result& value) { vector<kdtree2_result>::iterator it; vector<kdtree2_result>::iterator first = begin(); vector<kdtree2_result>::iterator last = end(); int count, step; count = distance(first,last); while(count>0) { it = first; step = count/2; advance(it,step); //printf("*it %e value %e\n",(*it).dis,value.dis); //if(*it<value) if((*it).dis<value.dis) { first=++it; count-=step+1; } else count=step; } return first; } void kdtree2_result_vector::push_element_and_heapify(kdtree2_result& e) { push_back(e); // what a vector does. push_heap( begin(), end() ); // and now heapify it, with the new elt. } float kdtree2_result_vector::replace_maxpri_elt_return_new_maxpri(kdtree2_result& e) { // remove the maximum priority element on the queue and replace it // with 'e', and return its priority. // // here, it means replacing the first element [0] with e, and re heapifying. pop_heap( begin(), end() ); pop_back(); push_back(e); // insert new push_heap(begin(), end() ); // and heapify. return( (*this)[0].dis ); } // // KDTREE2 implementation // // constructor kdtree2::kdtree2(kdtree2_array& data_in,bool rearrange_in,int dim_in) : the_data(data_in), N ( data_in.shape()[0] ), dim( data_in.shape()[1] ), sort_results(true), rearrange(rearrange_in), root(NULL), data(NULL), ind(N) { // // initialize the constant references using this unusual C++ // feature. // if (dim_in > 0) dim = dim_in; build_tree(); //cout<<"Tree built.\n"; if (rearrange) { // if we have a rearranged tree. // allocate the memory for it. //printf("rearranging\n"); rearranged_data.resize( extents[N][dim] ); // permute the data for it. for (int i=0; i<N; i++) { for (int j=0; j<dim; j++) { rearranged_data[i][j] = the_data[ind[i]][j]; // wouldn't F90 be nice here? } } data = &rearranged_data; } else { data = &the_data; } } // destructor kdtree2::~kdtree2() { delete root; } // building routines void kdtree2::build_tree() { for (int i=0; i<N; i++) ind[i] = i; root = build_tree_for_range(0,N-1,NULL); } kdtree2_node* kdtree2::build_tree_for_range(int l, int u, kdtree2_node* parent) { // recursive function to build kdtree2_node* node = new kdtree2_node(dim); // the newly created node. if (u<l) { return(NULL); // no data in this node. } if ((u-l) <= bucketsize) { // create a terminal node. // always compute true bounding box for terminal node. for (int i=0;i<dim;i++) { spread_in_coordinate(i,l,u,node->box[i]); } node->cut_dim = 0; node->cut_val = 0.0; node->l = l; node->u = u; node->left = node->right = NULL; } else { // // Compute an APPROXIMATE bounding box for this node. // if parent == NULL, then this is the root node, and // we compute for all dimensions. // Otherwise, we copy the bounding box from the parent for // all coordinates except for the parent's cut dimension. // That, we recompute ourself. // int c = -1; float maxspread = 0.0; int m; for (int i=0;i<dim;i++) { if ((parent == NULL) || (parent->cut_dim == i)) { spread_in_coordinate(i,l,u,node->box[i]); } else { node->box[i] = parent->box[i]; } float spread = node->box[i].upper - node->box[i].lower; if (spread>maxspread) { maxspread = spread; c=i; } } // // now, c is the identity of which coordinate has the greatest spread // if (false) { m = (l+u)/2; select_on_coordinate(c,m,l,u); } else { float sum; float average; if (true) { sum = 0.0; for (int k=l; k <= u; k++) { sum += the_data[ind[k]][c]; } average = sum / static_cast<float> (u-l+1); } else { // average of top and bottom nodes. average = (node->box[c].upper + node->box[c].lower)*0.5; } m = select_on_coordinate_value(c,average,l,u); } // move the indices around to cut on dim 'c'. node->cut_dim=c; node->l = l; node->u = u; node->left = build_tree_for_range(l,m,node); node->right = build_tree_for_range(m+1,u,node); if (node->right == NULL) { for (int i=0; i<dim; i++) node->box[i] = node->left->box[i]; node->cut_val = node->left->box[c].upper; node->cut_val_left = node->cut_val_right = node->cut_val; } else if (node->left == NULL) { for (int i=0; i<dim; i++) node->box[i] = node->right->box[i]; node->cut_val = node->right->box[c].upper; node->cut_val_left = node->cut_val_right = node->cut_val; } else { node->cut_val_right = node->right->box[c].lower; node->cut_val_left = node->left->box[c].upper; node->cut_val = (node->cut_val_left + node->cut_val_right) / 2.0; // // now recompute true bounding box as union of subtree boxes. // This is now faster having built the tree, being logarithmic in // N, not linear as would be from naive method. // for (int i=0; i<dim; i++) { node->box[i].upper = max(node->left->box[i].upper, node->right->box[i].upper); node->box[i].lower = min(node->left->box[i].lower, node->right->box[i].lower); } } } return(node); } void kdtree2:: spread_in_coordinate(int c, int l, int u, interval& interv) { // return the minimum and maximum of the indexed data between l and u in // smin_out and smax_out. float smin, smax; float lmin, lmax; int i; smin = the_data[ind[l]][c]; smax = smin; // process two at a time. for (i=l+2; i<= u; i+=2) { lmin = the_data[ind[i-1]] [c]; lmax = the_data[ind[i] ] [c]; if (lmin > lmax) { swap(lmin,lmax); // float t = lmin; // lmin = lmax; // lmax = t; } if (smin > lmin) smin = lmin; if (smax <lmax) smax = lmax; } // is there one more element? if (i == u+1) { float last = the_data[ind[u]] [c]; if (smin>last) smin = last; if (smax<last) smax = last; } interv.lower = smin; interv.upper = smax; // printf("Spread in coordinate %d=[%f,%f]\n",c,smin,smax); } void kdtree2::select_on_coordinate(int c, int k, int l, int u) { // // Move indices in ind[l..u] so that the elements in [l .. k] // are less than the [k+1..u] elmeents, viewed across dimension 'c'. // while (l < u) { int t = ind[l]; int m = l; for (int i=l+1; i<=u; i++) { if ( the_data[ ind[i] ] [c] < the_data[t][c]) { m++; swap(ind[i],ind[m]); } } // for i swap(ind[l],ind[m]); if (m <= k) l = m+1; if (m >= k) u = m-1; } // while loop } int kdtree2::select_on_coordinate_value(int c, float alpha, int l, int u) { // // Move indices in ind[l..u] so that the elements in [l .. return] // are <= alpha, and hence are less than the [return+1..u] // elmeents, viewed across dimension 'c'. // int lb = l, ub = u; while (lb < ub) { if (the_data[ind[lb]][c] <= alpha) { lb++; // good where it is. } else { swap(ind[lb],ind[ub]); ub--; } } // here ub=lb if (the_data[ind[lb]][c] <= alpha) return(lb); else return(lb-1); } // void kdtree2::dump_data() { // int upper1, upper2; // upper1 = N; // upper2 = dim; // printf("Rearrange=%d\n",rearrange); // printf("N=%d, dim=%d\n", upper1, upper2); // for (int i=0; i<upper1; i++) { // printf("the_data[%d][*]=",i); // for (int j=0; j<upper2; j++) // printf("%f,",the_data[i][j]); // printf("\n"); // } // for (int i=0; i<upper1; i++) // printf("Indexes[%d]=%d\n",i,ind[i]); // for (int i=0; i<upper1; i++) { // printf("data[%d][*]=",i); // for (int j=0; j<upper2; j++) // printf("%f,",(*data)[i][j]); // printf("\n"); // } // } // // search record substructure // // one of these is created for each search. // this holds useful information to be used // during the search static const float infinity = 1.0e38; class searchrecord { private: friend class kdtree2; friend class kdtree2_node; vector<float>& qv; int dim; bool rearrange; unsigned int nn; // , nfound; float ballsize; int centeridx, correltime; kdtree2_result_vector& result; // results const kdtree2_array* data; const vector<int>& ind; // constructor public: searchrecord(vector<float>& qv_in, kdtree2& tree_in, kdtree2_result_vector& result_in) : qv(qv_in), result(result_in), data(tree_in.data), ind(tree_in.ind) { dim = tree_in.dim; rearrange = tree_in.rearrange; ballsize = infinity; nn = 0; }; }; void kdtree2::n_nearest_brute_force(vector<float>& qv, int nn, kdtree2_result_vector& result) { result.clear(); for (int i=0; i<N; i++) { float dis = 0.0; kdtree2_result e; for (int j=0; j<dim; j++) { dis += squared( the_data[i][j] - qv[j]); } e.dis = dis; e.idx = i; result.push_back(e); } sort(result.begin(), result.end() ); } void kdtree2::n_nearest(vector<float>& qv, int nn, kdtree2_result_vector& result) { searchrecord sr(qv,*this,result); vector<float> vdiff(dim,0.0); result.clear(); sr.centeridx = -1; sr.correltime = 0; sr.nn = nn; root->search(sr); if (sort_results) sort(result.begin(), result.end()); } // search for n nearest to a given query vector 'qv'. void kdtree2::n_nearest_around_point(int idxin, int correltime, int nn, kdtree2_result_vector& result) { vector<float> qv(dim); // query vector result.clear(); for (int i=0; i<dim; i++) { qv[i] = the_data[idxin][i]; } // copy the query vector. { searchrecord sr(qv, *this, result); // construct the search record. sr.centeridx = idxin; sr.correltime = correltime; sr.nn = nn; root->search(sr); } if (sort_results) sort(result.begin(), result.end()); } void kdtree2::r_nearest(vector<float>& qv, float r2, kdtree2_result_vector& result) { // search for all within a ball of a certain radius searchrecord sr(qv,*this,result); vector<float> vdiff(dim,0.0); result.clear(); sr.centeridx = -1; sr.correltime = 0; sr.nn = 0; sr.ballsize = r2; root->search(sr); if (sort_results) sort(result.begin(), result.end()); } int kdtree2::r_count(vector<float>& qv, float r2) { // search for all within a ball of a certain radius { kdtree2_result_vector result; searchrecord sr(qv,*this,result); sr.centeridx = -1; sr.correltime = 0; sr.nn = 0; sr.ballsize = r2; root->search(sr); return(result.size()); } } void kdtree2::r_nearest_around_point(int idxin, int correltime, float r2, kdtree2_result_vector& result) { vector<float> qv(dim); // query vector result.clear(); for (int i=0; i<dim; i++) { qv[i] = the_data[idxin][i]; } // copy the query vector. { searchrecord sr(qv, *this, result); // construct the search record. sr.centeridx = idxin; sr.correltime = correltime; sr.ballsize = r2; sr.nn = 0; root->search(sr); } if (sort_results) sort(result.begin(), result.end()); } int kdtree2::r_count_around_point(int idxin, int correltime, float r2) { vector<float> qv(dim); // query vector for (int i=0; i<dim; i++) { qv[i] = the_data[idxin][i]; } // copy the query vector. { kdtree2_result_vector result; searchrecord sr(qv, *this, result); // construct the search record. sr.centeridx = idxin; sr.correltime = correltime; sr.ballsize = r2; sr.nn = 0; root->search(sr); return(result.size()); } } // // KDTREE2_NODE implementation // // constructor kdtree2_node::kdtree2_node(int dim) : box(dim) { left = right = NULL; // // all other construction is handled for real in the // kdtree2 building operations. // } // destructor kdtree2_node::~kdtree2_node() { if (left != NULL) delete left; if (right != NULL) delete right; // maxbox and minbox // will be automatically deleted in their own destructors. } void kdtree2_node::search(searchrecord& sr) { // the core search routine. // This uses true distance to bounding box as the // criterion to search the secondary node. // // This results in somewhat fewer searches of the secondary nodes // than 'search', which uses the vdiff vector, but as this // takes more computational time, the overall performance may not // be improved in actual run time. // if ( (left == NULL) && (right == NULL)) { // we are on a terminal node if (sr.nn == 0) { process_terminal_node_fixedball(sr); } else { process_terminal_node(sr); } } else { kdtree2_node *ncloser, *nfarther; float extra; float qval = sr.qv[cut_dim]; // value of the wall boundary on the cut dimension. if (qval < cut_val) { ncloser = left; nfarther = right; extra = cut_val_right-qval; } else { ncloser = right; nfarther = left; extra = qval-cut_val_left; }; if (ncloser != NULL) ncloser->search(sr); if ((nfarther != NULL) && (squared(extra) < sr.ballsize)) { // first cut if (nfarther->box_in_search_range(sr)) { nfarther->search(sr); } } } } inline float dis_from_bnd(float x, float amin, float amax) { if (x > amax) { return(x-amax); } else if (x < amin) return (amin-x); else return 0.0; } inline bool kdtree2_node::box_in_search_range(searchrecord& sr) { // // does the bounding box, represented by minbox[*],maxbox[*] // have any point which is within 'sr.ballsize' to 'sr.qv'?? // int dim = sr.dim; float dis2 =0.0; float ballsize = sr.ballsize; for (int i=0; i<dim;i++) { dis2 += squared(dis_from_bnd(sr.qv[i],box[i].lower,box[i].upper)); if (dis2 > ballsize) return(false); } return(true); } void kdtree2_node::process_terminal_node(searchrecord& sr) { int centeridx = sr.centeridx; int correltime = sr.correltime; unsigned int nn = sr.nn; int dim = sr.dim; float ballsize = sr.ballsize; // bool rearrange = sr.rearrange; const kdtree2_array& data = *sr.data; const bool debug = false; if (debug) { printf("Processing terminal node %d, %d\n",l,u); cout << "Query vector = ["; for (int i=0; i<dim; i++) cout << sr.qv[i] << ','; cout << "]\n"; cout << "nn = " << nn << '\n'; check_query_in_bound(sr); } for (int i=l; i<=u;i++) { int indexofi; // sr.ind[i]; float dis; bool early_exit; if (rearrange) { early_exit = false; dis = 0.0; for (int k=0; k<dim; k++) { dis += squared(data[i][k] - sr.qv[k]); if (dis > ballsize) { early_exit=true; break; } } if(early_exit) continue; // next iteration of mainloop // why do we do things like this? because if we take an early // exit (due to distance being too large) which is common, then // we need not read in the actual point index, thus saving main // memory bandwidth. If the distance to point is less than the // ballsize, though, then we need the index. // indexofi = sr.ind[i]; } else { // // but if we are not using the rearranged data, then // we must always indexofi = sr.ind[i]; early_exit = false; dis = 0.0; for (int k=0; k<dim; k++) { dis += squared(data[indexofi][k] - sr.qv[k]); if (dis > ballsize) { early_exit= true; break; } } if(early_exit) continue; // next iteration of mainloop } // end if rearrange. if (centeridx > 0) { // we are doing decorrelation interval if (abs(indexofi-centeridx) < correltime) continue; // skip this point. } // here the point must be added to the list. // // two choices for any point. The list so far is either // undersized, or it is not. // if (sr.result.size() < nn) { kdtree2_result e; e.idx = indexofi; e.dis = dis; sr.result.push_element_and_heapify(e); if (debug) cout << "unilaterally pushed dis=" << dis; if (sr.result.size() == nn) ballsize = sr.result.max_value(); // Set the ball radius to the largest on the list (maximum priority). if (debug) { cout << " ballsize = " << ballsize << "\n"; cout << "sr.result.size() = " << sr.result.size() << '\n'; } } else { // // if we get here then the current node, has a squared // distance smaller // than the last on the list, and belongs on the list. // kdtree2_result e; e.idx = indexofi; e.dis = dis; ballsize = sr.result.replace_maxpri_elt_return_new_maxpri(e); if (debug) { cout << "Replaced maximum dis with dis=" << dis << " new ballsize =" << ballsize << '\n'; } } } // main loop sr.ballsize = ballsize; } void kdtree2_node::process_terminal_node_fixedball(searchrecord& sr) { int centeridx = sr.centeridx; int correltime = sr.correltime; int dim = sr.dim; float ballsize = sr.ballsize; // bool rearrange = sr.rearrange; const kdtree2_array& data = *sr.data; for (int i=l; i<=u;i++) { int indexofi = sr.ind[i]; float dis; bool early_exit; if (rearrange) { early_exit = false; dis = 0.0; for (int k=0; k<dim; k++) { dis += squared(data[i][k] - sr.qv[k]); if (dis > ballsize) { early_exit=true; break; } } if(early_exit) continue; // next iteration of mainloop // why do we do things like this? because if we take an early // exit (due to distance being too large) which is common, then // we need not read in the actual point index, thus saving main // memory bandwidth. If the distance to point is less than the // ballsize, though, then we need the index. // indexofi = sr.ind[i]; } else { // // but if we are not using the rearranged data, then // we must always indexofi = sr.ind[i]; early_exit = false; dis = 0.0; for (int k=0; k<dim; k++) { dis += squared(data[indexofi][k] - sr.qv[k]); if (dis > ballsize) { early_exit= true; break; } } if(early_exit) continue; // next iteration of mainloop } // end if rearrange. if (centeridx > 0) { // we are doing decorrelation interval if (abs(indexofi-centeridx) < correltime) continue; // skip this point. } { kdtree2_result e; e.idx = indexofi; e.dis = dis; sr.result.push_back(e); } } } /* The KDTREE2 software is licensed under the terms of the Academic Free Software License, listed herein. In addition, users of this software must give appropriate citation in relevant technical documentation or journal paper to the author, Matthew B. Kennel, Institute For Nonlinear Science, preferably via a reference to the www.arxiv.org repository of this document, {\tt www.arxiv.org e-print: physics/0408067}. This requirement will be deemed to be advisory and not mandatory as is necessary to permit the free inclusion of the present software with any software licensed under the terms of any version of the GNU General Public License, or GNU Library General Public License. Academic Free License Version 1.1 This Academic Free License applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work: "Licensed under the Academic Free License version 1.1." Grant of License. Licensor hereby grants to any person obtaining a copy of the Original Work ("You") a world-wide, royalty-free, non-exclusive, perpetual, non-sublicenseable license (1) to use, copy, modify, merge, publish, perform, distribute and/or sell copies of the Original Work and derivative works thereof, and (2) under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and derivative works thereof, subject to the following conditions. Right of Attribution. Redistributions of the Original Work must reproduce all copyright notices in the Original Work as furnished by the Licensor, both in the Original Work itself and in any documentation and/or other materials provided with the distribution of the Original Work in executable form. Exclusions from License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. WARRANTY AND DISCLAIMERS. LICENSOR WARRANTS THAT THE COPYRIGHT IN AND TO THE ORIGINAL WORK IS OWNED BY THE LICENSOR OR THAT THE ORIGINAL WORK IS DISTRIBUTED BY LICENSOR UNDER A VALID CURRENT LICENSE FROM THE COPYRIGHT OWNER. EXCEPT AS EXPRESSLY STATED IN THE IMMEDIATELY PRECEEDING SENTENCE, THE ORIGINAL WORK IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, THE WARRANTY OF NON-INFRINGEMENT AND WARRANTIES THAT THE ORIGINAL WORK IS MERCHANTABLE OR FIT FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO LICENSE TO ORIGINAL WORK IS GRANTED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE LICENSOR BE LIABLE TO ANY PERSON FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OF THIS LICENSE OR THE USE OF THE ORIGINAL WORK INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PERSON SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. License to Source Code. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to access and modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work. Mutual Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License if You file a lawsuit in any court alleging that any OSI Certified open source software that is licensed under any license containing this "Mutual Termination for Patent Action" clause infringes any patent claims that are essential to use that software. This license is Copyright (C) 2002 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner. */
[ "brant@ucsc.edu" ]
brant@ucsc.edu
f712e1d970bc0a35adea0baa23dc2a867e1b0d0c
942b7b337019aa52862bce84a782eab7111010b1
/3rd party/imgui/imconfig.h
769713a30a15d89c762a0a9576a9060213782d14
[ "MIT", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
galek/xray15
338ad7ac5b297e9e497e223e0fc4d050a4a78da8
015c654f721e0fbed1ba771d3c398c8fa46448d9
refs/heads/master
2021-11-23T12:01:32.800810
2020-01-10T15:52:45
2020-01-10T15:52:45
168,657,320
0
0
null
2019-02-01T07:11:02
2019-02-01T07:11:01
null
UTF-8
C++
false
false
3,752
h
//----------------------------------------------------------------------------- // COMPILE-TIME OPTIONS FOR DEAR IMGUI // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure. // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions. //----------------------------------------------------------------------------- // A) You may edit imconfig.h (and not overwrite it when updating imgui, or maintain a patch/branch with your modifications to imconfig.h) // B) or add configuration directives in your own file and compile with #define IMGUI_USER_CONFIG "myfilename.h" // Note that options such as IMGUI_API, IM_VEC2_CLASS_EXTRA or ImDrawIdx needs to be defined consistently everywhere you include imgui.h, not only for the imgui*.cpp compilation units. //----------------------------------------------------------------------------- #pragma once //---- Define assertion handler. Defaults to calling assert(). //#define IM_ASSERT(_EXPR) MyAssert(_EXPR) //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows. //#define IMGUI_API __declspec( dllexport ) //#define IMGUI_API __declspec( dllimport ) #ifdef IMGUI_EXPORTS #define IMGUI_API __declspec(dllexport) #else #define IMGUI_API __declspec(dllimport) #endif //---- Don't define obsolete functions/enums names. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS //---- Don't implement default handlers for Windows (so as not to link with certain functions) //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // Don't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // Don't use and link with ImmGetContext/ImmSetCompositionWindow. //---- Don't implement demo windows functionality (ShowDemoWindow()/ShowStyleEditor()/ShowUserGuide() methods will be empty) //---- It is very strongly recommended to NOT disable the demo windows during development. Please read the comments in imgui_demo.cpp. //#define IMGUI_DISABLE_DEMO_WINDOWS //---- Don't implement ImFormatString(), ImFormatStringV() so you can reimplement them yourself. //#define IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS //---- Include imgui_user.h at the end of imgui.h as a convenience //#define IMGUI_INCLUDE_IMGUI_USER_H //---- Pack colors to BGRA8 instead of RGBA8 (if you needed to convert from one to another anyway) //#define IMGUI_USE_BGRA_PACKED_COLOR //---- Implement STB libraries in a namespace to avoid linkage conflicts (defaults to global namespace) //#define IMGUI_STB_NAMESPACE ImGuiStb //---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. // This will be inlined as part of ImVec2 and ImVec4 class declarations. /* #define IM_VEC2_CLASS_EXTRA \ ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ operator MyVec2() const { return MyVec2(x,y); } #define IM_VEC4_CLASS_EXTRA \ ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ operator MyVec4() const { return MyVec4(x,y,z,w); } */ //---- Use 32-bit vertex indices (default is 16-bit) to allow meshes with more than 64K vertices. Render function needs to support it. //#define ImDrawIdx unsigned int //---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. /* namespace ImGui { void MyFunction(const char* name, const MyMatrix44& v); } */
[ "abramcumner@yandex.ru" ]
abramcumner@yandex.ru
c9a7e693427d6b057fc891dd1ef488d3c11faed6
181968b591aa12c3081dbb78806717cce0fad98e
/src/modules/mesh_converter/MeshConverter.cpp
9b2c7b4374df3f082785d06885a22ea6e7199d20
[ "MIT" ]
permissive
Liudeke/CAE
d6d4c2dfbabe276a1e2acaa79038d8efcbe9d454
7eaa096e45fd32f55bd6de94c30dcf706c6f2093
refs/heads/master
2023-03-15T08:55:37.797303
2020-10-03T17:31:22
2020-10-03T17:36:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,660
cpp
#include "MeshConverter.h" #include "MeshCriteria.h" #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/make_mesh_3.h> #include <CGAL/Mesh_3/config.h> #include <CGAL/Mesh_complex_3_in_triangulation_3.h> #include <CGAL/Mesh_criteria_3.h> #include <CGAL/Mesh_triangulation_3.h> #include <CGAL/Mesh_polyhedron_3.h> #include <CGAL/Polyhedral_mesh_domain_3.h> #include <CGAL/Polyhedral_mesh_domain_with_features_3.h> #include <CGAL/Polyhedron_3.h> #include <CGAL/refine_mesh_3.h> #include <CGAL/utility.h> // IO #include <iostream> #include <fstream> // Boost #include <boost/algorithm/string/predicate.hpp> #include <boost/lexical_cast.hpp> // Eigen #include <Eigen/Dense> // std #include <set> #include <vector> // CGAL feature detection #include <CGAL/Polygon_mesh_processing/detect_features.h> // concurrency tags #ifdef CGAL_CONCURRENT_MESH_3 typedef CGAL::Parallel_tag Concurrency_tag; #else typedef CGAL::Sequential_tag Concurrency_tag; #endif // Polyhedron typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef CGAL::Mesh_polyhedron_3<K>::type Polyhedron; // Domain typedef CGAL::Polyhedral_mesh_domain_with_features_3<K> Mesh_domain_features; typedef CGAL::Polyhedral_mesh_domain_3<Polyhedron, K> Mesh_domain; // Triangulation typedef CGAL::Mesh_triangulation_3<Mesh_domain, CGAL::Default, Concurrency_tag>::type Tr; typedef CGAL::Mesh_triangulation_3<Mesh_domain_features, CGAL::Default, Concurrency_tag>::type Tr_features; typedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3; typedef CGAL::Mesh_complex_3_in_triangulation_3<Tr> C3t3_features; // Criteria typedef CGAL::Mesh_criteria_3<Tr> Mesh_criteria; typedef Polyhedron::HalfedgeDS HalfedgeDS; MeshConverter* MeshConverter::m_instance = new MeshConverter(); MeshConverter::MeshConverter() { } // Helper function template<typename T, unsigned int n> void add_if_not_contains(std::vector<std::array<T, n>>& v, std::array<T, n> e) { for (unsigned int i = 0; i < v.size(); ++i) { bool equal = true; for (unsigned int j = 0; j < n; ++j) { if (std::abs(v[i][j] - e[j]) > 0.0001) equal = false; } if (equal) return; } v.push_back(e); } template<typename Polyhedron> void reset_sharp_edges(Polyhedron* pMesh) { typename boost::property_map<Polyhedron, CGAL::edge_is_feature_t>::type if_pm = get(CGAL::edge_is_feature, *pMesh); for(typename boost::graph_traits<Polyhedron>::edge_descriptor ed : edges(*pMesh)) { put(if_pm,ed,false); } } template<typename Polyhedron> void detect_sharp_edges(Polyhedron* pMesh, const double angle) { reset_sharp_edges(pMesh); // Detect edges in current polyhedron typename boost::property_map<Polyhedron, CGAL::edge_is_feature_t>::type eif = get(CGAL::edge_is_feature, *pMesh); CGAL::Polygon_mesh_processing::detect_sharp_edges(*pMesh, angle, eif); } // Creates a CGAL Polyhedron from the given vertices and triangles. Polyhedron createPolyhedron( const Vectors& vertices, const Faces& facets) { Polyhedron p; CGAL::Polyhedron_incremental_builder_3<HalfedgeDS> builder( p.hds(), true); typedef typename HalfedgeDS::Vertex Vertex; typedef typename Vertex::Point Point; builder.begin_surface(vertices.size(), facets.size(), 0); for (const Eigen::Vector3d& v : vertices) { builder.add_vertex(Point(v(0), v(1), v(2))); } for (const std::array<unsigned int, 3>& f : facets) { builder.begin_facet(); builder.add_vertex_to_facet(f[0]); builder.add_vertex_to_facet(f[1]); builder.add_vertex_to_facet(f[2]); builder.end_facet(); } builder.end_surface(); return p; } template <typename Mesh_domain> bool generateMeshFromCGALPolyhedron( Mesh_domain& domain, Vectors& vertices_out, Faces& outer_facets_out, Faces& facets_out, Cells& cells_out, const MeshCriteria& meshCriteria) { // Triangulation typedef typename CGAL::Mesh_triangulation_3<Mesh_domain, CGAL::Default, Concurrency_tag>::type MeshTr; typedef CGAL::Mesh_complex_3_in_triangulation_3<MeshTr> C3t3; typedef CGAL::Mesh_criteria_3<MeshTr> Mesh_criteria; Mesh_criteria criteria( CGAL::parameters::cell_radius_edge_ratio=meshCriteria.getCellRadiusEdgeRatio(), CGAL::parameters::cell_size=meshCriteria.getCellSize(), CGAL::parameters::facet_angle=meshCriteria.getFacetAngle(), CGAL::parameters::facet_size=meshCriteria.getFacetSize(), CGAL::parameters::facet_distance=meshCriteria.getFaceDistance()); // Mesh_criteria criteria; // Mesh generation C3t3 c3t3 = CGAL::make_mesh_3<C3t3>( domain, criteria, CGAL::parameters::no_perturb(), CGAL::parameters::no_exude()); // CONVERT FROM CGAL TO vectors typedef typename C3t3::Triangulation Tr; typedef typename C3t3::Facets_in_complex_iterator Facet_iterator; typedef typename C3t3::Cells_in_complex_iterator Cell_iterator; typedef typename Tr::Finite_vertices_iterator Finite_vertices_iterator; typedef typename Tr::Vertex_handle Vertex_handle; typedef typename Tr::Point Point_3; const Tr& tr = c3t3.triangulation(); std::cout << "\nAfter Triangulation: \n" << "Vertices: " << tr.number_of_vertices() << "\n" << "Facets/Triangles: " << tr.number_of_facets() << "\n" << "Cells/Tetrahedra: " << tr.number_of_cells() << "\n"; //------------------------------------------------------- // Vertices //------------------------------------------------------- boost::unordered_map<Vertex_handle, int> V; int inum = 0; for (Finite_vertices_iterator vit = tr.finite_vertices_begin(); vit != tr.finite_vertices_end(); ++vit) { V[vit] = inum++; Point_3 p = vit->point(); vertices_out.push_back(Eigen::Vector3d((float)CGAL::to_double(p.x()), (float)CGAL::to_double(p.y()), (float)CGAL::to_double(p.z()))); } //------------------------------------------------------- // Facets //------------------------------------------------------- typename C3t3::size_type number_of_triangles = c3t3.number_of_facets_in_complex(); for (Facet_iterator fit = c3t3.facets_in_complex_begin(); fit != c3t3.facets_in_complex_end(); ++fit) { typename C3t3::Subdomain_index cell_sd=c3t3.subdomain_index(fit->first); typename C3t3::Subdomain_index opp_sd=c3t3.subdomain_index(fit->first->neighbor(fit->second)); int j = -1; std::array<unsigned int, 3> vertex; for (int i = 0; i < 4; i++) { if (i != fit->second) { const Vertex_handle& vh = (*fit).first->vertex(i); vertex[++j] = V[vh]; } } //facets.push_back(vertex); // Only for outer Facets true (that one that lie on the boundary) if (!(cell_sd != 0 && opp_sd != 0)) outer_facets_out.push_back(vertex); } //------------------------------------------------------- // Tetrahedra //------------------------------------------------------- auto sortedFace = [](std::array<unsigned int, 3> f) { std::sort(f.begin(), f.end()); return f; }; std::set<std::array<unsigned int, 3>> addedSortedFacets; auto addFaceIfNotContains = [&sortedFace, &facets_out, &addedSortedFacets]( std::array<unsigned int, 3> f) { std::array<unsigned int, 3> sortedF = sortedFace(f); if (addedSortedFacets.find(sortedF) == addedSortedFacets.end()) { addedSortedFacets.insert(sortedF); facets_out.push_back(f); } }; for (Cell_iterator cit = c3t3.cells_in_complex_begin(); cit != c3t3.cells_in_complex_end(); ++cit) { std::array<unsigned int, 4> f; for (unsigned int i = 0; i < 4; i++) f[i] = static_cast<unsigned int>(V[cit->vertex(static_cast<int>(i))]); cells_out.push_back(f); addFaceIfNotContains({f[0], f[1], f[2]}); addFaceIfNotContains({f[0], f[1], f[3]}); addFaceIfNotContains({f[0], f[2], f[3]}); addFaceIfNotContains({f[1], f[2], f[3]}); } // correct the triangle indices // The 3 vertex indices of a triangles must be ordered in a way // that the cross product of the first two vertices: // v1.cross(v2) points on the outside. for (size_t i = 0; i < outer_facets_out.size(); ++i) { std::array<unsigned int, 3>& facet = outer_facets_out[i]; // ===================================================================== // Disclaimer: // This code part is responsible for fixing the vertex index order of // each outer triangle so that the normal that points outside the // polygon can be calculated in a consistent way. The same is already // done in the constructor of Polygon3D so this part may be removed. // It is left here for the case that one doesn't want to create a // Polygon3D afterwards. It could be removed for the future to slightly // improve the performance. // find the outer facet (tetrahedron) that contains this triangle // note, that since this is an outer triangle, there is only a single tetrahedron // that containts it. bool found = false; unsigned int other_vertex_id = 0; for (size_t j = 0; j < cells_out.size(); ++j) { Cell& c = cells_out[j]; if (std::find(c.begin(), c.end(), facet[0]) != c.end() && std::find(c.begin(), c.end(), facet[1]) != c.end()&& std::find(c.begin(), c.end(), facet[2]) != c.end()) { found = true; // find the other vertex of the cell that is not part of the triangle for (size_t k = 0; k < 4; ++k) { if (std::find(facet.begin(), facet.end(), c[k]) == facet.end()) { other_vertex_id = c[k]; break; } } break; } } bool reverted = false; if (!found) { std::cout << "Did not find cell for outer triangle.\n"; } else { Eigen::Vector3d r_1 = vertices_out[facet[1]] - vertices_out[facet[0]]; Eigen::Vector3d r_2 = vertices_out[facet[2]] - vertices_out[facet[0]]; Eigen::Vector3d r_3 = vertices_out[other_vertex_id] - vertices_out[facet[0]]; // std::cout << "other_vertex_id = " << other_vertex_id << "\n"; if (r_1.cross(r_2).normalized().dot(r_3) > 0) { unsigned int temp = facet[1]; facet[1] = facet[2]; facet[2] = temp; reverted = true; } } // ===================================================================== // Check if this face is part of all faces. If so, revert the // corresponding global facet if the outer facet was also reverted. // Polygon3D doesn't necessarily require this to be done because // it does it on its own as well, see // Polygon3D::synchronizeTriangleIndexOrder()). bool found2 = false; for (size_t j = 0; j < facets_out.size(); ++j) { if (sortedFace(facets_out[j]) == sortedFace(facet)) { found2 = true; // revert the same face in facets_out as it was done in // outer_facets_out if (reverted) { std::array<unsigned int, 3>& facet = facets_out[j]; unsigned int temp = facet[1]; facet[1] = facet[2]; facet[2] = temp; } break; } } if (!found2) { std::cout << "Outer face is not part of all faces.\n"; } } std::cout << "\nIn Output File: \n" << "Vertices: " << vertices_out.size() << "\n" << "Facets/Triangles: " << facets_out.size() << "\n" << "Outer Facets/Triangles: " << outer_facets_out.size() << "\n" << "Cells/Tethraedra: " << cells_out.size() << "\n"; return true; } // The same as the other generateMesh() but uses a CGAL Polyhedron. // Calling createPolyhedron() and this method is equal to the other // generateMesh(). bool generateMeshFromCGALPolyhedron( Polyhedron& p, Vectors& vertices_out, Faces& outer_facets_out, Faces& facets_out, Cells& cells_out, const MeshCriteria& meshCriteria) { if (meshCriteria.isEdgesAsFeatures()) { typedef CGAL::Polyhedral_mesh_domain_with_features_3<K> Mesh_domain; // Create domain Mesh_domain domain(p, p); domain.detect_features(meshCriteria.getMinFeatureEdgeAngleDeg()); return generateMeshFromCGALPolyhedron( domain, vertices_out, outer_facets_out, facets_out, cells_out, meshCriteria); } else { typedef CGAL::Polyhedral_mesh_domain_3<Polyhedron, K> Mesh_domain; // Create domain Mesh_domain domain(p); return generateMeshFromCGALPolyhedron( domain, vertices_out, outer_facets_out, facets_out, cells_out, meshCriteria); } } bool MeshConverter::generateMesh( const Vectors& vertices, const Faces& facets, Vectors& vertices_out, Faces& outer_facets_out, Faces& facets_out, Cells& cells_out, const MeshCriteria& meshCriteria) { std::cout << "Input: \n " << "Vertices: " << vertices.size() << "\n" << "Facets/Triangles: " << facets.size() << "\n"; vertices_out.clear(); outer_facets_out.clear(); facets_out.clear(); cells_out.clear(); Polyhedron p = createPolyhedron(vertices, facets); std::cout << "\nAfter Conversion to Polyhedron: \n" << "Vertices: " << p.size_of_vertices() << "\n" << "Facets/Triangles: " << p.size_of_facets() << "\n"; return generateMeshFromCGALPolyhedron( p, vertices_out, outer_facets_out, facets_out, cells_out, meshCriteria); }
[ "daniel.roth@mailbase.info" ]
daniel.roth@mailbase.info
4b9a66fb0e6e128ac1d178dcd15109aa3cb1d177
a6201151b9956af651570c1286bbf078556cf1c6
/RectifierControlFView.cpp
e9199f89d2562b73013d27a9d39dd55e287f64d4
[]
no_license
vladislav-007/RectifierControl
d73ea8dabf0c667823384406762dd6ab373f18f7
3b1281f6d0ec3f82a850c35554c06a9b0e1773a0
refs/heads/master
2020-03-12T13:01:01.062623
2019-06-10T03:19:53
2019-06-10T03:19:53
130,632,131
0
0
null
2018-11-28T02:18:10
2018-04-23T02:57:23
C++
UTF-8
C++
false
false
855
cpp
// RectifierControlFView.cpp : implementation file // #include "stdafx.h" #include "RectifierControl.h" #include "RectifierControlFView.h" // CRectifierControlFView IMPLEMENT_DYNCREATE(CRectifierControlFView, CFormView) CRectifierControlFView::CRectifierControlFView() : CFormView(IDD_RECTIFIERCONTROLFVIEW) { } CRectifierControlFView::~CRectifierControlFView() { } void CRectifierControlFView::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CRectifierControlFView, CFormView) END_MESSAGE_MAP() // CRectifierControlFView diagnostics #ifdef _DEBUG void CRectifierControlFView::AssertValid() const { CFormView::AssertValid(); } #ifndef _WIN32_WCE void CRectifierControlFView::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif #endif //_DEBUG // CRectifierControlFView message handlers
[ "vladisl@ngs.ru" ]
vladisl@ngs.ru
d8f771b217cf3c0e6a054f1c92b4c7383be52cc2
e3e012664e3b4c016b7ed240cd9b81af1289149e
/thirdparty/linux/miracl/miracl_osmt/source/ecsign.cpp
7c2b4410c85dc9f5298ab2988396d943c915dbd2
[ "Unlicense" ]
permissive
osu-crypto/MultipartyPSI
b48ce23163fed8eb458a05e3af6e4432963f08c7
44e965607b0d27416420d32cd09e6fcc34782c3a
refs/heads/implement
2023-07-20T10:16:55.866284
2021-05-12T22:01:12
2021-05-12T22:01:12
100,207,769
73
29
Unlicense
2023-07-11T04:42:04
2017-08-13T22:15:27
C++
UTF-8
C++
false
false
2,812
cpp
/* * Elliptic Curve Digital Signature Algorithm (ECDSA) * * * This program asks for the name of a <file>, computes its message digest, * signs it, and outputs the signature to a file <file>.ecs. It is assumed * that curve parameters are available from a file common.ecs, as well as * the private key of the signer previously generated by the ecsgen program * * The curve is y^2=x^3+Ax+B mod p * * The file common.ecs is presumed to exist, and to contain the domain * information {p,A,B,q,x,y}, where A and B are curve parameters, (x,y) are * a point of order q, p is the prime modulus, and q is the order of the * point (x,y). In fact normally q is the prime number of points counted * on the curve. * * Requires: big.cpp ecn.cpp */ #include <iostream> #include <cstring> #include <fstream> #include "ecn.h" using namespace std; #ifndef MR_NOFULLWIDTH Miracl precision(200,256); #else Miracl precision(50,MAXBASE); #endif void strip(char *name) { /* strip off filename extension */ int i; for (i=0;name[i]!='\0';i++) { if (name[i]!='.') continue; name[i]='\0'; break; } } static Big Hash(ifstream &fp) { /* compute hash function */ char ch,s[20]; Big h; sha sh; shs_init(&sh); forever { /* read in bytes from message file */ fp.get(ch); if (fp.eof()) break; shs_process(&sh,ch); } shs_hash(&sh,s); h=from_binary(20,s); return h; } int main() { ifstream common("common.ecs"); /* construct file I/O streams */ ifstream private_key("private.ecs"); ifstream message; ofstream signature; char ifname[50],ofname[50]; ECn G; Big a,b,p,q,x,y,h,r,s,d,k; long seed; int bits; miracl *mip=&precision; /* randomise */ cout << "Enter 9 digit random number seed = "; cin >> seed; irand(seed); /* get common data */ common >> bits; mip->IOBASE=16; common >> p >> a >> b >> q >> x >> y; mip->IOBASE=10; /* calculate r - this can be done off-line, and hence amortized to almost nothing */ ecurve(a,b,p,MR_PROJECTIVE); G=ECn(x,y); k=rand(q); G*=k; /* see ebrick.cpp for technique to speed this up */ G.get(r); r%=q; /* get private key of recipient */ private_key >> d; /* get message */ cout << "file to be signed = " ; cin >> ifname; strcpy(ofname,ifname); strip(ofname); strcat(ofname,".ecs"); message.open(ifname,ios::binary|ios::in); if (!message) { cout << "Unable to open file " << ifname << "\n"; return 0; } h=Hash(message); /* calculate s */ k=inverse(k,q); s=((h+d*r)*k)%q; signature.open(ofname); signature << r << endl; signature << s << endl; return 0; }
[ "trieun@oregonstate.edu" ]
trieun@oregonstate.edu
b067a2f67add7305f9459539960b4d598c70b022
67cf5d1d7ea62ca9e7b35c42c042efcf1c77ff36
/mosixFastProjections/include/Projector/ProjectionLib/VanDerGrintenProjection.h
5e318d9edca9500f865c50a70ddb6d01cdea4792
[]
no_license
bpass/cegis
d3c84d2d29a084105b4c207391ddc6ace0cdf398
6c849e41974b8ff844f78e260de26d644c956afb
refs/heads/master
2020-04-03T18:57:58.102939
2013-04-24T22:07:54
2013-04-24T22:07:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,869
h
// $Id: VanDerGrintenProjection.h,v 1.1 2005/03/11 23:59:10 mschisler Exp $ // Last modified by $Author: mschisler $ on $Date: 2005/03/11 23:59:10 $ #ifndef _VanDerGrintenPROJECTION_H_ #define _VanDerGrintenPROJECTION_H_ #include "PseudocylindricalProjection.h" namespace ProjLib { class VanDerGrintenProjection : public PseudocylindricalProjection { public: VanDerGrintenProjection( double originLat, double sphereRadius, double centralMeridian, double falseEasting, double falseNorthing, DATUM d, UNIT u, DATUM geoDatum = DEFAULT_DATUM, UNIT geoUnit = ARC_DEGREES ); VanDerGrintenProjection( const VanDerGrintenProjection& p ); // Accessors PROJSYS getProjectionSystem() const throw(); double getOriginLatitude() const throw(); // Modifiers void setOriginLatitude( double originLat ) throw(); /* Sets the origin latitude. The latitude must be in packed DMS (DDDMMMSSS.SSS) format. */ // Operator overloads bool operator==( const Projection& rhs ) const throw(); // Cloning Projection* clone() const throw(std::bad_alloc); // String override std::string toString() const throw(); }; // *************************************************************************** inline PROJSYS VanDerGrintenProjection::getProjectionSystem() const throw() { return VGRINT; } // *************************************************************************** inline double VanDerGrintenProjection::getOriginLatitude() const throw() { return d_projParams[5]; } // *************************************************************************** inline void VanDerGrintenProjection::setOriginLatitude( double originLat ) throw() { d_projParams[5] = originLat; } } // namespace ProjLib #endif
[ "mschisler" ]
mschisler
3c41587310bd90eedfbebafd5e1188c20ce06a1a
da38e03e53832f864058e7d1517a8ba3ac17f15d
/CLI/Validators/InputValidators/LabelValidator.cpp
cf5fb87904a4d17457e3f03319323e8b8693aca2
[]
no_license
IliaIlyin/ToDoList
916c076726d64cffa8d09f5d82608cd28568fa8d
04a7101a2057972e5f869407da95208bf0bf4485
refs/heads/master
2023-01-02T04:34:01.033413
2020-09-27T22:59:05
2020-09-27T22:59:05
281,182,314
0
0
null
2020-08-18T07:57:34
2020-07-20T17:25:21
C++
UTF-8
C++
false
false
213
cpp
// // Created by illia.ilin on 8/25/2020. // #include "LabelValidator.h" GeneralInputValidator::InputToken LabelValidator::validate(const std::string &str) { return GeneralInputValidator::validateLabel(str); }
[ "fate98765@gmail.com" ]
fate98765@gmail.com
d753c11cf26f5d85d557b8074c859a9de565b06a
a864b84c706a4432a3a3cf9dd11e3c940bb53860
/Activation.h
64afa56355d2c309377ac3a87a17bac242610e12
[]
no_license
NehoraM/ML-identifying-numbers
b3669cfaf3a711ee50ec362fa348060f54f49d35
1e76cc02d92bd47ea7ded34773481bb466d2d408
refs/heads/master
2022-12-22T03:01:12.314833
2020-09-17T12:22:51
2020-09-17T12:22:51
296,318,116
0
0
null
null
null
null
UTF-8
C++
false
false
853
h
#ifndef ACTIVATION_H #define ACTIVATION_H #include "Matrix.h" /** * @enum ActivationType * @brief Indicator of activation function. */ enum ActivationType { Relu, Softmax }; /** * Activates softmax or relu */ class Activation { private: ActivationType _type; /** * * @param m tha matrix * @return relu matrix */ Matrix &_relu(Matrix &m); /** * * @param m matrix * @return softmax matrix */ Matrix &_softmax(Matrix &m); public: /** * * @param t the type */ Activation(ActivationType t); /** * * @return the activation type */ ActivationType getActivationType() const; /** * * @param m the matrix * @return matrix after activation function */ Matrix &operator()(Matrix &m); }; #endif //ACTIVATION_H
[ "you@example.com" ]
you@example.com
6e55e2dc3ea65bb6db5ecbb007c678469ba972a3
2e5c33f159adf150b67ef1b19f14607d2d11f1fe
/engine/renderers/opengl/OpenGLFrameBuffer.cpp
5fffdb39c9aa8bad3d774b7a93eba6827553acba
[ "Apache-2.0" ]
permissive
AeonGames/AeonEngine
29fedf6dcba2548e594ec067f99c834d8f975f27
2cdbf540227c1c4bbf4d893145627564dbb2a8a3
refs/heads/master
2023-07-22T01:35:42.972067
2023-07-19T01:47:20
2023-07-19T01:47:20
54,066,866
17
4
null
null
null
null
UTF-8
C++
false
false
4,434
cpp
/* Copyright (C) 2019,2021 Rodrigo Jose Hernandez Cordoba 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 "aeongames/ProtoBufClasses.h" #include "OpenGLFrameBuffer.h" namespace AeonGames { OpenGLFrameBuffer::OpenGLFrameBuffer() = default; OpenGLFrameBuffer::~OpenGLFrameBuffer() { Finalize(); } void OpenGLFrameBuffer::Initialize() { // Frame Buffer glGenFramebuffers ( 1, &mFBO ); OPENGL_CHECK_ERROR_THROW; glBindFramebuffer ( GL_FRAMEBUFFER, mFBO ); OPENGL_CHECK_ERROR_THROW; // Color Buffer glGenTextures ( 1, &mColorBuffer ); OPENGL_CHECK_ERROR_THROW; glBindTexture ( GL_TEXTURE_2D, mColorBuffer ); OPENGL_CHECK_ERROR_THROW; glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, 800, 600, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr ); OPENGL_CHECK_ERROR_THROW; glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); OPENGL_CHECK_ERROR_THROW; glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); OPENGL_CHECK_ERROR_THROW; glBindTexture ( GL_TEXTURE_2D, 0 ); OPENGL_CHECK_ERROR_THROW; glFramebufferTexture2D ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mColorBuffer, 0 ); OPENGL_CHECK_ERROR_THROW; // Render Buffer glGenRenderbuffers ( 1, &mRBO ); OPENGL_CHECK_ERROR_THROW; glBindRenderbuffer ( GL_RENDERBUFFER, mRBO ); OPENGL_CHECK_ERROR_THROW; glRenderbufferStorage ( GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 800, 600 ); OPENGL_CHECK_ERROR_THROW; glBindRenderbuffer ( GL_RENDERBUFFER, 0 ); OPENGL_CHECK_ERROR_THROW; glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mRBO ); OPENGL_CHECK_ERROR_THROW; if ( glCheckFramebufferStatus ( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE ) { throw std::runtime_error ( "Incomplete Framebuffer." ); } OPENGL_CHECK_ERROR_THROW; glBindFramebuffer ( GL_FRAMEBUFFER, 0 ); OPENGL_CHECK_ERROR_THROW; } void OpenGLFrameBuffer::Finalize() { if ( glIsRenderbuffer ( mRBO ) ) { OPENGL_CHECK_ERROR_NO_THROW; glDeleteRenderbuffers ( 1, &mRBO ); OPENGL_CHECK_ERROR_NO_THROW; mRBO = 0; } if ( glIsTexture ( mColorBuffer ) ) { OPENGL_CHECK_ERROR_NO_THROW; glDeleteTextures ( 1, &mColorBuffer ); OPENGL_CHECK_ERROR_NO_THROW; mColorBuffer = 0; } if ( glIsFramebuffer ( mFBO ) ) { OPENGL_CHECK_ERROR_NO_THROW; glDeleteFramebuffers ( 1, &mFBO ); OPENGL_CHECK_ERROR_NO_THROW; mFBO = 0; } OPENGL_CHECK_ERROR_NO_THROW; } void OpenGLFrameBuffer::Resize ( uint32_t aWidth, uint32_t aHeight ) { glBindTexture ( GL_TEXTURE_2D, mColorBuffer ); glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB, aWidth, aHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr ); glBindRenderbuffer ( GL_RENDERBUFFER, mRBO ); glRenderbufferStorage ( GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, aWidth, aHeight ); glBindRenderbuffer ( GL_RENDERBUFFER, 0 ); } void OpenGLFrameBuffer::Bind() { glBindFramebuffer ( GL_FRAMEBUFFER, mFBO ); OPENGL_CHECK_ERROR_NO_THROW; } void OpenGLFrameBuffer::Unbind() { glBindFramebuffer ( GL_FRAMEBUFFER, 0 ); OPENGL_CHECK_ERROR_NO_THROW; } GLuint OpenGLFrameBuffer::GetFBO() const { return mFBO; } OpenGLFrameBuffer::OpenGLFrameBuffer ( OpenGLFrameBuffer&& aOpenGLFrameBuffer ) { std::swap ( mFBO, aOpenGLFrameBuffer.mFBO ); std::swap ( mColorBuffer, aOpenGLFrameBuffer.mColorBuffer ); std::swap ( mRBO, aOpenGLFrameBuffer.mRBO ); } }
[ "kwizatz@aeongames.com" ]
kwizatz@aeongames.com
1d4f38f6ad0257238b48570740e3afcd64f1a6b0
f54a025958cdd048de41728272bd95b1b0177cb7
/src/modules/fancyzones/FancyZonesLib/JsonHelpers.h
56df116032ecce50fe061b3b8f5fe8651c94a537
[ "MIT", "BSL-1.0", "Unlicense", "LicenseRef-scancode-generic-cla" ]
permissive
jaimecbernardo/PowerToys
d600318849dbb977214aa98fc9159be8b48333b4
01ab8d5f75dcda8ddd5c8461a57d2f1fc1409735
refs/heads/master
2023-09-04T05:21:59.227306
2022-10-11T11:36:26
2022-10-11T11:36:26
254,362,160
7
0
MIT
2022-12-05T04:12:41
2020-04-09T12:14:22
C#
UTF-8
C++
false
false
4,263
h
#pragma once #include "FancyZonesDataTypes.h" #include <common/utils/json.h> #include <string> #include <vector> #include <unordered_map> namespace BackwardsCompatibility { struct DeviceIdData { std::wstring deviceName = L"FallbackDevice"; int width; int height; GUID virtualDesktopId; std::wstring monitorId; static std::optional<DeviceIdData> ParseDeviceId(const std::wstring& str); static bool IsValidDeviceId(const std::wstring& str); }; inline bool operator==(const BackwardsCompatibility::DeviceIdData& lhs, const BackwardsCompatibility::DeviceIdData& rhs) { return lhs.deviceName.compare(rhs.deviceName) == 0 && lhs.width == rhs.width && lhs.height == rhs.height && (lhs.virtualDesktopId == rhs.virtualDesktopId || lhs.virtualDesktopId == GUID_NULL || rhs.virtualDesktopId == GUID_NULL) && lhs.monitorId.compare(rhs.monitorId) == 0; } inline bool operator!=(const BackwardsCompatibility::DeviceIdData& lhs, const BackwardsCompatibility::DeviceIdData& rhs) { return !(lhs == rhs); } inline bool operator<(const BackwardsCompatibility::DeviceIdData& lhs, const BackwardsCompatibility::DeviceIdData& rhs) { return lhs.deviceName.compare(rhs.deviceName) < 0 || lhs.width < rhs.width || lhs.height < rhs.height || lhs.monitorId.compare(rhs.monitorId) < 0; } } namespace JSONHelpers { namespace CanvasLayoutInfoJSON { json::JsonObject ToJson(const FancyZonesDataTypes::CanvasLayoutInfo& canvasInfo); std::optional<FancyZonesDataTypes::CanvasLayoutInfo> FromJson(const json::JsonObject& infoJson); } namespace GridLayoutInfoJSON { json::JsonObject ToJson(const FancyZonesDataTypes::GridLayoutInfo& gridInfo); std::optional<FancyZonesDataTypes::GridLayoutInfo> FromJson(const json::JsonObject& infoJson); } struct CustomZoneSetJSON { std::wstring uuid; FancyZonesDataTypes::CustomLayoutData data; static json::JsonObject ToJson(const CustomZoneSetJSON& device); static std::optional<CustomZoneSetJSON> FromJson(const json::JsonObject& customZoneSet); }; namespace ZoneSetDataJSON { std::optional<FancyZonesDataTypes::ZoneSetData> FromJson(const json::JsonObject& zoneSet); }; struct DeviceInfoJSON { BackwardsCompatibility::DeviceIdData deviceId; FancyZonesDataTypes::DeviceInfoData data; static std::optional<DeviceInfoJSON> FromJson(const json::JsonObject& device); }; struct LayoutQuickKeyJSON { std::wstring layoutUuid; int key; static std::optional<LayoutQuickKeyJSON> FromJson(const json::JsonObject& device); }; using TDeviceInfoMap = std::unordered_map<BackwardsCompatibility::DeviceIdData, FancyZonesDataTypes::DeviceInfoData>; using TCustomZoneSetsMap = std::unordered_map<std::wstring, FancyZonesDataTypes::CustomLayoutData>; using TLayoutQuickKeysMap = std::unordered_map<std::wstring, int>; json::JsonObject GetPersistFancyZonesJSON(const std::wstring& zonesSettingsFileName, const std::wstring& appZoneHistoryFileName); // replace zones-settings: applied layouts std::optional<TDeviceInfoMap> ParseDeviceInfos(const json::JsonObject& fancyZonesDataJSON); void SaveAppliedLayouts(const TDeviceInfoMap& deviceInfoMap); // replace zones-settings: layout hotkeys std::optional<TLayoutQuickKeysMap> ParseQuickKeys(const json::JsonObject& fancyZonesDataJSON); void SaveLayoutHotkeys(const TLayoutQuickKeysMap& quickKeysMap); // replace zones-settings: layout templates std::optional<json::JsonArray> ParseLayoutTemplates(const json::JsonObject& fancyZonesDataJSON); void SaveLayoutTemplates(const json::JsonArray& templates); // replace zones-settings: custom layouts std::optional<TCustomZoneSetsMap> ParseCustomZoneSets(const json::JsonObject& fancyZonesDataJSON); void SaveCustomLayouts(const TCustomZoneSetsMap& map); } namespace std { template<> struct hash<BackwardsCompatibility::DeviceIdData> { size_t operator()(const BackwardsCompatibility::DeviceIdData& Value) const { return 0; } }; }
[ "noreply@github.com" ]
jaimecbernardo.noreply@github.com
4965a320997643f9190a8df49fc01217216091c5
a0423109d0dd871a0e5ae7be64c57afd062c3375
/Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/OpenGL.GLTextureParameterValue.h
dcf65e94720302d8a6a3d130be7b98dba9a429bc
[ "Apache-2.0" ]
permissive
marferfer/SpinOff-LoL
1c8a823302dac86133aa579d26ff90698bfc1ad6
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
refs/heads/master
2020-03-29T20:09:20.322768
2018-10-09T10:19:33
2018-10-09T10:19:33
150,298,258
0
0
null
null
null
null
UTF-8
C++
false
false
376
h
// This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/UnoCore/1.9.0/Source/OpenGL/GLEnums.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Int.h> namespace g{ namespace OpenGL{ // public extern enum GLTextureParameterValue :89 uEnumType* GLTextureParameterValue_typeof(); }} // ::g::OpenGL
[ "mariofdezfdez@hotmail.com" ]
mariofdezfdez@hotmail.com
d6213b59a235112190f0926c0599939d71591456
edbc89690747c7f5ca36c2e9cc0de17953daf76f
/RepositoryFile.h
3d5c9733fa380b7725e43c70a894df09b31d7da2
[]
no_license
LauraDiosan-CS/lab8-11-polimorfism-davidvrabioru
6f7da3234a4b52144873453c4f1b99e57277e65b
8c370cb12b05d27a9a146c65240c5ea4ca6a5433
refs/heads/master
2022-05-26T02:43:39.234637
2020-05-04T06:25:06
2020-05-04T06:25:06
255,149,426
0
0
null
null
null
null
UTF-8
C++
false
false
3,605
h
#pragma once #include <list> #include <iostream> #include<fstream> #include "Mancare.h" #include "Comanda.h" #include "Shopping.h" #include "Repository.h" using namespace std; template<class T> class RepositoryFile :public RepositoryTemplate<T> { private: const char* fileName; const char* outputFile; public: RepositoryFile(); RepositoryFile(const char*, const char*); int addElem(const T&); int deleteElem(const T&); void updateElem(const T&, const T); void loadFromFile(const char*); void saveToFile(); ~RepositoryFile(); }; template<class T> RepositoryFile<T>::RepositoryFile() :RepositoryTemplate<T>() { fileName = ""; outputFile = ""; } template<class T> RepositoryFile<T>::RepositoryFile(const char* fileName, const char* outputFile) { this->fileName = fileName; this->outputFile = outputFile; loadFromFile(fileName); //RepositoryTemplate::clearElem(); //fis = fileName; //ifstream f(fileName); //string linie; //char* name = new char[10]; //char* numar = new char[10]; //char* status = new char[10]; //while (!f.eof()) { // f >> name >> numar >> status; // if (name != "") { // Entity e(name, numar, status); // //elem.push_back(e); // RepositoryTemplate::addElem(e); // } //} //delete[] name; //delete[] numar; //delete[] status; //f.close(); } template<class T> void RepositoryFile<T>::loadFromFile(const char* fileName) { ////elem.clear(); //RepositoryTemplate::clearElem(); //fis = fileName; //ifstream f(fileName); //char* name = new char[10]; //char* numar = new char[10]; //char* status = new char[10]; //while (!f.eof()) //{ // f >> name >> numar >> status; // if (strcmp(name, "") != 0) // { // T t; // //Entity e(name, numar, status); // //elem.push_back(e); // RepositoryTemplate::addElem(t); // } //} //delete[] name; //delete[] numar; //delete[] status; //f.close(); if (fileName == NULL) return; try { this->fileName = fileName; std::ifstream inf(this->fileName); RepositoryTemplate<T>::clearElem(); string line; if (inf.is_open()) { while (getline(inf, line)) { //T t; //std::string inStr; //t.fromString(inStr); this->addElem(T(line)); //cout << line << endl; } inf.close(); } } catch (int e) { std::cout << "Failed loading from file.\n"; }; } template<class T> void RepositoryFile<T>::saveToFile() { /*ofstream f(fis); typename list<T>::iterator it; list<T> elem = RepositoryTemplate::getAll(); for (it = elem.begin(); it != elem.end(); ++it) { f << *it; } f.close();*/ if (this->fileName == NULL) return; std::ofstream out(this->fileName); //out << this->dim() << '\n'; for (T t : this->getAll()) { out << t;// << '\n'; } out.close(); if (this->outputFile == NULL) return; std::ofstream ou(this->outputFile); //out << this->dim() << '\n'; for (T t : this->getAll()) { ou << t;// << '\n'; } ou.close(); } template<class T> RepositoryFile<T>::~RepositoryFile() { } template<class T> int RepositoryFile<T>::addElem(const T& e) { int r = RepositoryTemplate<T>::addElem(e); if (r != -1) { saveToFile(); return 0; } return -1; } template<class T> int RepositoryFile<T>::deleteElem(const T& e) { int r = RepositoryTemplate<T>::deleteElem(e); if (r != 0) { saveToFile(); return 0; } else return -1; } template<class T> void RepositoryFile<T>::updateElem(const T& e, const T n) { RepositoryTemplate<T>::updateElem(e, n); saveToFile(); }
[ "noreply@github.com" ]
LauraDiosan-CS.noreply@github.com
a289d5ed4da0d671eb266e09f622397185456236
9826489e216479f8b3c7b8d600208076b15028af
/libsolintent/ir/ExpressionInterface.h
d5b2242a0fbed2d2bbffe0b111e25dc1cc593c13
[]
no_license
ScottWe/solintent
117a1e3e157bbd42a21ae256c063480fdd90d5d7
85f8c4d9a2a8acd044a833b24a01dfcfffb465c7
refs/heads/master
2020-11-23T20:55:32.384223
2019-12-20T20:18:53
2019-12-20T20:18:53
227,817,149
0
0
null
null
null
null
UTF-8
C++
false
false
6,784
h
/** * Analyzing Solidity expressions directly is not always practical. The AST is * designed to be (1) readable and (2) JavaScript like. It can instead be * helpful to have some intermediate form. Furthermore, it can be helpful if * such an intermediate form is "adaptive". That is, it adjusts to the current * needs of analysis (taint versus bounds versus etc.). This module provides a * set of primitives to capture different views of the Solidity AST. */ /** * @author Arthur Scott Wesley <aswesley@uwaterloo.ca> * @date 2019 * Surface-level interfaces for the full ExpressionSummary hierarchy. */ #pragma once #include <libsolidity/ast/ASTVisitor.h> #include <libsolidity/ast/Types.h> #include <libsolintent/ir/IRSummary.h> #include <algorithm> #include <list> #include <optional> #include <set> namespace dev { namespace solintent { // -------------------------------------------------------------------------- // /** * A generalized summary of any expression. This is a shared base-type. */ class ExpressionSummary: public detail::SpecializedIR<solidity::Expression> { public: /** * Possible sources of data. Examples are given below. * - [Length] `array.length` * - [Balance] `address(contract).balance` * - [Input] `x` in `function f(int x) public` * - [Output] `x` in `function f() returns (int x) public` * - [Miner] `block.num` * - [Sender] `msg.value` */ enum class Source { Length, Balance, Input, Output, Miner, Sender, State }; virtual ~ExpressionSummary() = 0; /** * If this expression is tainted by mutable variables, this will return all * applicable tags. */ virtual std::optional<std::set<Source>> tags() const = 0; /** * Returns a list of the free variables upon which this operation is * dependant. */ virtual std::set<std::reference_wrapper<ExpressionSummary const>> free() const = 0; protected: /** * Declares that this summary wraps the given expression. * * _expr: the wrapped expression. */ explicit ExpressionSummary(solidity::Expression const& _expr); }; // -------------------------------------------------------------------------- // /** * Represents a numeric expression in Solidity as either a literal, or an AST of * operations. */ class NumericSummary: public ExpressionSummary { public: virtual ~NumericSummary() = 0; /** * Produces the exact value of this expression, if possible. */ virtual std::optional<solidity::rational> exact() const = 0; protected: /** * Declares that this summary wraps the given expression. * * _expr: the wrapped expression. */ explicit NumericSummary(solidity::Expression const& _expr); }; // -------------------------------------------------------------------------- // /** * Represents a boolean expression in Solidity as either a literal, or an AST of * operations. */ class BooleanSummary: public ExpressionSummary { public: virtual ~BooleanSummary() = 0; /** * Produces the exact value of the expression, if possible. */ virtual std::optional<bool> exact() const = 0; protected: /** * Declares that this summary wraps the given expression. * * _expr: the wrapped expression. */ explicit BooleanSummary(solidity::Expression const& _expr); }; // -------------------------------------------------------------------------- // /** * A secondary base-class which endows variable-related summaries the ability to * analyze their declarations. */ class SymbolicVariable { public: virtual ~SymbolicVariable() = 0; /** * Allows the symbol to be tied to a unique name. */ std::string symb() const; protected: /** * Resolves the identifier to its variable declaration. All labels and names * will be populated in the process. * * _id: the identifier to resolve */ explicit SymbolicVariable(solidity::Identifier const& _id); /** * Resolves the member access to the appropriate initialization site. The * path to reach this variable is expanded. * * _access: the member access to resolve */ explicit SymbolicVariable(solidity::MemberAccess const& _access); /** * Allows symbolic metadata to be forwarded to a new instantiation. * * _otr: the previously annotated symbolic variable. */ explicit SymbolicVariable(SymbolicVariable const& _otr); /** * Returns all tags resolved during itialization. */ std::set<ExpressionSummary::Source> symbolTags() const; private: /** * Utility class to map scopable variables to path. */ class PathAnalyzer: private solidity::ASTConstVisitor { public: /** * _id: identifier to analyze, wrt its reference declaration. */ explicit PathAnalyzer(solidity::Identifier const& _id); /** * _mem: identifier to analyze, wrt its reference declaration. */ explicit PathAnalyzer(solidity::MemberAccess const& _mem); /** * Produces the full name of this variable */ std::string symb() const; /** * Returns the source of this variable. If there are no applicable * source annotations then notion is returned. */ std::optional<ExpressionSummary::Source> source() const; protected: bool visit(solidity::VariableDeclaration const& _node) override; bool visit(solidity::FunctionCall const& _node) override; bool visit(solidity::MemberAccess const& _node) override; void endVisit(solidity::Identifier const& _node) override; private: // Maintains a chain of all declarations, starting from top level. std::string m_symb; // If a variable source is resolved, it is stored here. std::optional<ExpressionSummary::Source> m_source; /** * Pushes _str to the front of m_path. The '#' separator notation is * obeyed. */ void prependToPath(std::string _str); }; // Stores all tags extracted for this symbol during analysis. std::set<ExpressionSummary::Source> m_tags; // A unique identifier for this variable. std::string m_symb; /** * Integrates the PathAnalysis results with the SymbolicVariable. This * factors out some of the initialization logic. * * TODO: the initialization parameter object pattern (does this have a * name?) would be more practical. Less error-prone... */ void applyPathAnalysis(PathAnalyzer const& _analysis); }; // -------------------------------------------------------------------------- // } }
[ "scott.wesley@ns.sympatico.ca" ]
scott.wesley@ns.sympatico.ca
da4cfc2bd5206067402ebf416915dbe29392fd73
35db93efa1c425ce1073c15474729b46a3cc173f
/src/server/modules/parser.h
e15d502c61b4ae18c0d6cb8936b1a0bca668a1d4
[]
no_license
Plasmarobo/SkyfullOfMetal
e0a0c6ca8ee30a9c9e220724ef85b22ded974420
6ef2d3ae44fb6e643f727f6bef7d7d2dc0d50be1
refs/heads/master
2021-01-22T06:23:02.435407
2017-06-02T16:04:37
2017-06-02T16:04:37
92,546,688
0
0
null
null
null
null
UTF-8
C++
false
false
201
h
#ifndef MODULE_PARSER_H #define MODULE_PARSER_H #include <flatbuffers/idl.h> #include <flatbuffers/util.h> #include <flatbuffers/flatbuffers.h> class ModuleParser { }; #endif /* MODULE_PARSER_H */
[ "austen@thelevelup.com" ]
austen@thelevelup.com
aa479687ab9f0098112b9af148ce1b659518bcfc
ac316dc53e018ee84008fe2cdacc75c73cb4a12a
/data_structure&algorithms/DataStructure&Algorithms/02_list/include/list/list_deduplicate.h
0ce48e08b2c10d212f775b3fc11165b1ccb1db94
[]
no_license
shixu312349410/vscode_cplusplus
7701913254aa1754dc0853716338d4cf8536e31d
a961759431054d58a0eb9edc27f5957f55b2d83a
refs/heads/master
2023-03-18T02:07:38.104946
2021-03-09T12:45:44
2021-03-09T12:45:44
339,215,392
0
0
null
null
null
null
GB18030
C++
false
false
824
h
/****************************************************************************************** * Data Structures in C++ * ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3 * Junhui DENG, deng@tsinghua.edu.cn * Computer Science & Technology, Tsinghua University * Copyright (c) 2003-2019. All rights reserved. ******************************************************************************************/ #pragma once template <typename T> int List<T>::deduplicate() { int oldSize = _size; ListNodePosi(T) p = first(); for ( Rank r = 0; p != trailer; p = p->succ ) //O(n) if ( ListNodePosi(T) q = find(p->data, r, p) ) remove(q); //此时q与p雷同,但删除前者更为简明 else r++; //r为无重前缀的长度 return oldSize - _size; //删除元素总数 }
[ "312349410@qq.com" ]
312349410@qq.com
e44b3505659ac4e0be1bf709a843ef8202ead677
492976adfdf031252c85de91a185bfd625738a0c
/src/Game/AI/AI/aiPriestBossBowEquiped.cpp
d6c684f5b55bfdcf8e240e054eb9373660cc205f
[]
no_license
zeldaret/botw
50ccb72c6d3969c0b067168f6f9124665a7f7590
fd527f92164b8efdb746cffcf23c4f033fbffa76
refs/heads/master
2023-07-21T13:12:24.107437
2023-07-01T20:29:40
2023-07-01T20:29:40
288,736,599
1,350
117
null
2023-09-03T14:45:38
2020-08-19T13:16:30
C++
UTF-8
C++
false
false
555
cpp
#include "Game/AI/AI/aiPriestBossBowEquiped.h" namespace uking::ai { PriestBossBowEquiped::PriestBossBowEquiped(const InitArg& arg) : BowEquiped(arg) {} PriestBossBowEquiped::~PriestBossBowEquiped() = default; bool PriestBossBowEquiped::init_(sead::Heap* heap) { return BowEquiped::init_(heap); } void PriestBossBowEquiped::enter_(ksys::act::ai::InlineParamPack* params) { BowEquiped::enter_(params); } void PriestBossBowEquiped::leave_() { BowEquiped::leave_(); } void PriestBossBowEquiped::loadParams_() {} } // namespace uking::ai
[ "leo@leolam.fr" ]
leo@leolam.fr
af106a4437b0503ca98e3ee3babff660cbbb71e1
47a4b9901faf9742273b02ba14444d8d555b65a4
/Codeforces/579A.cpp
2ac8e859b116623eb176a3534afcaab6887d7ac0
[]
no_license
Aulene/Competitive-Programming-Solutions
a028b7b96e024d8547e2ff66801e5377d7fb76cd
81d2705263313755399f2e3b6e01e029d40f61a6
refs/heads/master
2021-06-27T20:03:53.657351
2019-04-25T19:48:29
2019-04-25T19:48:29
101,798,734
3
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
#include <bits/stdc++.h> using namespace std; #define int long long int #define mod 1000000007 #define p push #define pb push_back #define mp make_pair #define f first #define s second #define vi vector <int> #define vvi vector < vector <int> > signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n, m, i, j, u, v, ans = 0; cin >> n; while(n) { ans++; n = n & (n - 1); } cout << ans << endl; return 0; }
[ "aussylegendflame@gmail.com" ]
aussylegendflame@gmail.com
7673470c67788a4ebf842044ef7897045e7d43ea
1f752f8b0131d45ef869cc2e78618494ee1df8f4
/src/gasnet_handlers.cpp
10dd400d7d988214b77f86a15939ff49fe7c8795
[]
no_license
vainamon/DSTM_P1
e51682aba7ddaa0c37b73873533f340f14bd376f
5dea9122dbcae336f5bbd5dca4dd7eed6730028e
refs/heads/master
2020-04-04T10:28:21.974659
2018-11-02T11:35:17
2018-11-02T11:35:17
155,856,244
0
0
null
null
null
null
UTF-8
C++
false
false
6,734
cpp
/* * gasnet_handlers.cpp * * Created on: 12.09.2011 * Author: igor */ #include "gasnet_handlers.h" #include "dstm_gasnet_appl_wrapper.h" #include "profiling.h" #include "glue.h" #include "dstm_malloc/dstm_malloc.h" #include <gasnet_handler.h> namespace dstm_pthread { #include "dstm_pthread/dstm_pthread.h" } Application* GLOBAL_APPLICATION; int GLOBAL_END_EXECUTION = 0; #ifdef TRANSACTIONS_STATS #include "dstm_stats.h" volatile int GLOBAL_RETRIVE_STATS = 0; #endif DEFINE_HANDLER_TIME_PROFILING(spawnthread, 1) int gasnet_handlers_init(Application* __application) { GLOBAL_APPLICATION = __application; } typedef void(*handler_func)(); gasnet_handlerentry_t htable[] = { { hidx_endexec_shrthandler, (handler_func)endexec_shrthandler }, { hidx_endexec_succ_shrthandler, (handler_func)endexec_succ_shrthandler }, { hidx_spawnthread_medhandler, (handler_func)spawnthread_medhandler }, { hidx_spawnthread_succ_medhandler, (handler_func)spawnthread_succ_medhandler }, { hidx_threadexited_shrthandler, (handler_func)threadexited_shrthandler }, { hidx_threadexited_succ_shrthandler, (handler_func)threadexited_succ_shrthandler }, { hidx_requestlocks_medhandler, (handler_func)requestlocks_medhandler }, { hidx_requestlocks_succ_medhandler, (handler_func)requestlocks_succ_medhandler }, { hidx_dstmfree_medhandler, (handler_func)dstmfree_medhandler }, { hidx_dstmfree_succ_medhandler, (handler_func)dstmfree_succ_medhandler }, { hidx_dstmmalloc_shrthandler, (handler_func)dstmmalloc_shrthandler }, { hidx_dstmmalloc_succ_shrthandler, (handler_func)dstmmalloc_succ_shrthandler }, { hidx_dstmstats_medhandler, (handler_func)dstmstats_medhandler }, { hidx_dstmstats_succ_medhandler, (handler_func)dstmstats_succ_medhandler }, }; void spawnthread_medhandler (gasnet_token_t token, void *buf, size_t nbytes, harg_t gtid) { BEGIN_TIME_PROFILING(); gasnet_node_t node; gasnet_AMGetMsgSource(token, &node); int ltid = 0; if(GLOBAL_APPLICATION != 0){ ltid = GLOBAL_APPLICATION->runChildThread(buf, node, gtid); } GASNET_Safe(gasnet_AMReplyMedium1 (token, hidx_spawnthread_succ_medhandler, buf, nbytes, ltid)); END_TIME_PROFILING(""); } void spawnthread_succ_medhandler (gasnet_token_t token, void *buf, size_t nbytes, harg_t ltid) { BEGIN_TIME_PROFILING(); gasnet_node_t node; gasnet_AMGetMsgSource(token, &node); #ifdef LOGGING VLOG(3)<<"Inside function "<<__PRETTY_FUNCTION__<<" from node = "<<node<<" ltid = "<<ltid; #endif int gtid = *dstm_pthread::newthread_ptr_t(buf)->__new_thread; DSTMGASNetApplWrapper* applWrp = (DSTMGASNetApplWrapper*)(GLOBAL_APPLICATION); Application::application_thread_ptr_t thread_ptr; if(applWrp->inLocalThreads(gtid)) thread_ptr = applWrp->getLocalThread(gtid); else if(applWrp->inRemoteThreads(gtid)) thread_ptr = applWrp->getRemoteThread(gtid); thread_ptr->ltid = ltid; if(thread_ptr->state == Application::RUNNABLE) thread_ptr->state = Application::RUNNING; END_HANDLER_TIME_PROFILING(spawnthread, gtid); END_TIME_PROFILING(""); } void threadexited_shrthandler (gasnet_token_t token, harg_t gtid, harg_t state) { #ifdef LOGGING VLOG(3)<<"Inside function "<<__PRETTY_FUNCTION__<<" GTID = "<<gtid<<" state = "<<state; #endif BEGIN_TIME_PROFILING(); gasnet_node_t node; gasnet_AMGetMsgSource(token, &node); DSTMGASNetApplWrapper* applWrp = (DSTMGASNetApplWrapper*)(GLOBAL_APPLICATION); if(applWrp->inLocalThreads(gtid)){ applWrp->getLocalThread(gtid)->state = state; }else{ applWrp->getRemoteThread(gtid)->state = state; } GASNET_Safe(gasnet_AMReplyShort2 (token, hidx_threadexited_succ_shrthandler, gtid, state)); END_TIME_PROFILING(""); } void threadexited_succ_shrthandler (gasnet_token_t token, harg_t gtid, harg_t state) { } void requestlocks_medhandler(gasnet_token_t token, void* buf, size_t nbytes) { uint64_t* objects_versions = (uint64_t*)buf; uint64_t* result = glue::processLocksRequest(objects_versions, nbytes); if(result == NULL) GASNET_Safe(gasnet_AMReplyMedium1 (token, hidx_requestlocks_succ_medhandler, buf, sizeof(uintptr_t), 0)); else { /// first element - tx descriptor result[0] = *((uint64_t*)buf); GASNET_Safe(gasnet_AMReplyMedium1 (token, hidx_requestlocks_succ_medhandler, result, (result[1]+2)*sizeof(uint64_t), result[1])); free(result); } } void requestlocks_succ_medhandler(gasnet_token_t, void* buf, size_t, harg_t nobjs) { uint64_t *tx = (uint64_t*)buf; uint64_t *changedObjects = (uint64_t*)buf+2; glue::locksRequestProcessed((uintptr_t)*tx, changedObjects, nobjs); } void dstmfree_medhandler(gasnet_token_t token, void* buf, size_t nbytes) { glue::dstm_mallocFree(*((uint64_t*)buf)); GASNET_Safe(gasnet_AMReplyMedium0(token,hidx_dstmfree_succ_medhandler,NULL,0)); } void dstmfree_succ_medhandler(gasnet_token_t token, void* buf, size_t nbytes) { } void dstmmalloc_shrthandler(gasnet_token_t token, harg_t size, harg_t remote_ptr_h, harg_t remote_ptr_l, harg_t remote_mutex_h, harg_t remote_mutex_l) { uintptr_t ptr; ptr = glue::dstm_mallocMalloc(size); /* fprintf(stderr, "%s size %d _ptr %p mutex %p ptr %p\n", __PRETTY_FUNCTION__, size, UNPACK2(remote_ptr_h, remote_ptr_l), UNPACK2(remote_mutex_h, remote_mutex_l), ptr); */ GASNET_Safe(gasnet_AMReplyShort6(token,hidx_dstmmalloc_succ_shrthandler, remote_ptr_h,remote_ptr_l,remote_mutex_h,remote_mutex_l, GASNETI_HIWORD(ptr),GASNETI_LOWORD(ptr))); } void dstmmalloc_succ_shrthandler(gasnet_token_t, harg_t ptr_h, harg_t ptr_l, harg_t mutex_h, harg_t mutex_l, harg_t returned_ptr_h, harg_t returned_ptr_l) { uintptr_t* ptr = (uintptr_t*)UNPACK2(ptr_h,ptr_l); *ptr = (uintptr_t)UNPACK2(returned_ptr_h,returned_ptr_l); /* fprintf(stderr, "%s _ptr %p mutex %p ptr %p\n", __PRETTY_FUNCTION__, UNPACK2(ptr_h, ptr_l), UNPACK2(mutex_h, mutex_l), *ptr); */ uintptr_t *mtx = (uintptr_t*)UNPACK2(mutex_h,mutex_l); *mtx = 1; //gasnett_mutex_unlock((gasnett_mutex_t*) UNPACK2(mutex_h,mutex_l)); } void endexec_shrthandler(gasnet_token_t token) { GLOBAL_END_EXECUTION = 1; GASNET_Safe(gasnet_AMReplyShort0(token,hidx_endexec_succ_shrthandler)); } void endexec_succ_shrthandler(gasnet_token_t token) { } void dstmstats_medhandler(gasnet_token_t token, void* buf, size_t nbytes) { #ifdef TRANSACTIONS_STATS gasnet_node_t node; gasnet_AMGetMsgSource(token, &node); add_node_to_stat(node,*(node_stats_t*)buf); GLOBAL_RETRIVE_STATS++; #endif } void dstmstats_succ_medhandler(gasnet_token_t token, void* buf, size_t nbytes) { }
[ "vainamon@gmail.com" ]
vainamon@gmail.com
5718606275e2839bab174ded6cdd024eaccb9dc6
a3ca1f53459ef5bc3653f900d7381c2615c51ad9
/Bhalim1.cpp
dc7cc3ef9374273e56cfe963fcd7c1acb173473e
[]
no_license
giongto35/CompetitveProgramming
cf7b02dfaecb46c4c949d903675817cd9c2e141b
29b7cdf7796d4054f5e74d2bce7e0247a21968e8
refs/heads/master
2021-01-20T23:32:38.627994
2015-01-30T17:07:56
2015-01-30T17:07:56
30,082,220
1
0
null
null
null
null
UTF-8
C++
false
false
1,460
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <sstream> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <queue> using namespace std ; #define FOREACH(it,c) for( __typeof((c).begin()) it=(c).begin();it!=(c).end();it++) #define FOR(i,a,b) for( int i=(a),_b=(b);i<=_b;i++) #define DOW(i,b,a) for( int i=(b),_a=(a);i>=_a;i--) #define REP(i,n) FOR(i,0,(n)-1) #define DEP(i,n) DOW(i,(n)-1,0) #define all(a) (a).begin() , (a).end() #define push(a,b) (a).push_back((b)) typedef vector<int> VI ; typedef vector<string> VS ; template<class T> inline int size(const T&c) { return c.size(); } using namespace std; const int maxn=300000+10; int a[maxn],s[maxn],n,cs,j,T; int res; int main() { freopen("Bhalim1.inp","r",stdin); //freopen("Bhalim1.out","w",stdout); while (scanf("%d%d", &n,&cs) ==2) { FOR(i,1,n) { cin>>a[i]; s[i]=s[i-1]+a[i]; } j=1; res=n+1; FOR(i,1,n) { while (s[i]-s[j]>=cs) j++; if (s[i]-s[j-1]>=cs) res=min(res,i-j+1); } if (res==n+1) cout<<0; else cout<<res; cout<<endl; T--; } fclose(stdin); fclose(stdout); return 0; }
[ "giongto35@yahoo.com" ]
giongto35@yahoo.com
fa9b7417f2021108ace1368a3680d6a79aa8ffee
511a4a9bebd1f35731c6269a121961b9aa18d7b1
/shaderSketch1/src/ofApp.h
efe139cfc6c2931d87f9df292525c32973c586c0
[]
no_license
ofZach/ecalWorkshop
0b98a6adb7a04aab6259700fcd78b366ce0594e6
4fb4c1a21bc24482fee5e43f65fb7367a0a85dd7
refs/heads/main
2023-05-01T17:43:50.543423
2021-05-05T18:39:27
2021-05-05T18:39:27
363,986,626
9
1
null
null
null
null
UTF-8
C++
false
false
569
h
#pragma once #include "ofMain.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofShader shader; };
[ "zach@sfpc.io" ]
zach@sfpc.io
433088595ef4fd484ecbf91c0a53563860fb3d28
391b88509968575dfa92db8220a7d0ed1a222f0d
/MFC3.23(1)/MFC3.23(1)/stdafx.cpp
760c22e5e036d37b4c682e7998b7553a46eff0ba
[]
no_license
ZouXinyi-a/ZXY
f6b6d65f3431b20f046ed3bb46117376c3795c8d
03772e5569e21bac14d097192f648bce026bd2be
refs/heads/master
2022-11-07T22:38:15.876992
2020-07-02T14:54:47
2020-07-02T14:54:47
265,002,732
0
0
null
null
null
null
GB18030
C++
false
false
169
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // MFC3.23(1).pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "1749883446.qq.com@example.com" ]
1749883446.qq.com@example.com
2abb55959d4883b2ac0071a775dd0405a481eada
eda7f1e5c79682bf55cfa09582a82ce071ee6cee
/aspects/fluid/source/test/UtGunnsGasDisplacementPump.hh
3b3455b116b293c625b6480045af302cd2c3e26c
[ "LicenseRef-scancode-us-govt-public-domain", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nasa/gunns
923f4f7218e2ecd0a18213fe5494c2d79a566bb3
d5455e3eaa8b50599bdb16e4867a880705298f62
refs/heads/master
2023-08-30T06:39:08.984844
2023-07-27T12:18:42
2023-07-27T12:18:42
235,422,976
34
11
NOASSERTION
2023-08-30T15:11:41
2020-01-21T19:21:16
C++
UTF-8
C++
false
false
7,786
hh
#ifndef UtGunnsGasDisplacementPump_EXISTS #define UtGunnsGasDisplacementPump_EXISTS //////////////////////////////////////////////////////////////////////////////////////////////////// /// @defgroup UT_TSM_GUNNS_FLUID_SOURCE_GAS_DISPLACEMENT_PUMP Gas Displacement Pump Unit Tests /// @ingroup UT_TSM_GUNNS_FLUID_SOURCE /// /// @copyright Copyright 2019 United States Government as represented by the Administrator of the /// National Aeronautics and Space Administration. All Rights Reserved. /// /// @details Unit Tests for the GUNNS Gas Displacement Pump link model. /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////// #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestFixture.h> #include "aspects/fluid/source/GunnsGasDisplacementPump.hh" //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Inherit from GunnsGasDisplacementPump and befriend UtGunnsGasDisplacementPump. /// /// @details Class derived from the unit under test. It just has a constructor with the same /// arguments as the parent and a default destructor, but it befriends the unit test case /// driver class to allow it access to protected data members. //////////////////////////////////////////////////////////////////////////////////////////////////// class FriendlyGunnsGasDisplacementPump : public GunnsGasDisplacementPump { public: FriendlyGunnsGasDisplacementPump(); virtual ~FriendlyGunnsGasDisplacementPump(); friend class UtGunnsGasDisplacementPump; }; inline FriendlyGunnsGasDisplacementPump::FriendlyGunnsGasDisplacementPump() : GunnsGasDisplacementPump() {}; inline FriendlyGunnsGasDisplacementPump::~FriendlyGunnsGasDisplacementPump() {} //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Gas Displacement Pump unit tests. /// /// @details This class provides the unit tests for the GUNNS Gas Displacement Pump link model /// within the CPPUnit framework. //////////////////////////////////////////////////////////////////////////////////////////////////// class UtGunnsGasDisplacementPump: public CppUnit::TestFixture { public: /// @brief Default constructs this Gas Displacement Pump unit test. UtGunnsGasDisplacementPump(); /// @brief Default destructs this Gas Displacement Pump unit test. virtual ~UtGunnsGasDisplacementPump(); /// @brief Executes before each test. void setUp(); /// @brief Executes after each test. void tearDown(); /// @brief Tests config data. void testConfig(); /// @brief Tests input data. void testInput(); /// @brief Tests default construction. void testDefaultConstruction(); /// @brief Tests initialize method. void testNominalInitialization(); /// @brief Tests initialize method exceptions. void testInitializationExceptions(); /// @brief Tests accessor methods. void testAccessors(); /// @brief Tests modifier methods. void testModifiers(); /// @brief Tests update state method. void testUpdateState(); /// @brief Tests update fluid method. void testUpdateFluid(); /// @brief Tests compute flows method. void testComputeFlows(); private: CPPUNIT_TEST_SUITE(UtGunnsGasDisplacementPump); CPPUNIT_TEST(testConfig); CPPUNIT_TEST(testInput); CPPUNIT_TEST(testDefaultConstruction); CPPUNIT_TEST(testNominalInitialization); CPPUNIT_TEST(testInitializationExceptions); CPPUNIT_TEST(testAccessors); CPPUNIT_TEST(testModifiers); CPPUNIT_TEST(testUpdateState); CPPUNIT_TEST(testUpdateFluid); CPPUNIT_TEST(testComputeFlows); CPPUNIT_TEST_SUITE_END(); /// @brief Enumeration for the number of nodes and fluid constituents. enum {N_NODES = 2, N_FLUIDS = 2}; FluidProperties::FluidType tTypes[N_FLUIDS]; /**< (--) Constituent fluid types array */ double tFractions[N_FLUIDS]; /**< (--) Constituent fluid mass fractions array */ DefinedFluidProperties* tFluidProperties; /**< (--) Predefined fluid properties */ PolyFluidConfigData* tFluidConfig; /**< (--) Fluid config data */ PolyFluidInputData* tFluidInput0; /**< (--) Fluid input data for node 0 */ PolyFluidInputData* tFluidInput1; /**< (--) Fluid input data for node 1 */ std::vector<GunnsBasicLink*> tLinks; /**< (--) Link vector */ std::string tName; /**< (--) Nominal name */ GunnsFluidNode tNodes[N_NODES]; /**< (--) Nominal connected nodes */ GunnsNodeList tNodeList; /**< (--) Network node structure */ int tPort0; /**< (--) Nominal inlet port index */ int tPort1; /**< (--) Nominal outlet port index */ double tCycleVolume; /**< (m3) Volume of fluid displaced per cycle */ double tDriveRatio; /**< (--) Gear ratio of motor to impeller speed */ double tThermalLength; /**< (m) Impeller length for thermal convection */ double tThermalDiameter; /**< (m) Impeller inner diameter for thermal convection */ double tSurfaceRoughness; /**< (m) Impeller wall surface roughness for thermal convection */ bool tCheckValveActive; /**< (--) Check valve active flag */ GunnsGasDisplacementPumpConfigData* tConfigData; /**< (--) Pointer to nominal config data */ bool tBlockageFlag; /**< (--) Blockage malf flag */ double tBlockage; /**< (--) Blockage malf value */ double tFlowDemand; /**< (kg/s) Initial flow demand */ double tMotorSpeed; /**< (rev/min) Initial motor speed */ double tWallTemperature; /**< (K) Initial wall temperature */ GunnsGasDisplacementPumpInputData* tInputData; /**< (--) Pointer to nominal input data */ FriendlyGunnsGasDisplacementPump* tArticle; /**< (--) Pointer to test article */ double tTimeStep; /**< (--) Nominal time step */ static const double PI; /**< (--) Units conversion constant */ static int TEST_ID; /**< (--) Test identification number. */ //////////////////////////////////////////////////////////////////////////////////////////// /// @details Copy constructor unavailable since declared private and not implemented. //////////////////////////////////////////////////////////////////////////////////////////// UtGunnsGasDisplacementPump(const UtGunnsGasDisplacementPump&); //////////////////////////////////////////////////////////////////////////////////////////// /// @details Assignment operator unavailable since declared private and not implemented. //////////////////////////////////////////////////////////////////////////////////////////// UtGunnsGasDisplacementPump& operator =(const UtGunnsGasDisplacementPump&); }; ///@} #endif
[ "jason.l.harvey@nasa.gov" ]
jason.l.harvey@nasa.gov
08612dabf1379c9bbe35b150ef5885723d6ce725
d0d5fac9b0635f75dc211ceb68d16e9b4399bb11
/src/hiphop-php/hphp/third_party/folly/folly/experimental/File.cpp
a0f05f6bb76913bfa18442833bde2749f2a990f0
[ "Apache-2.0", "PHP-3.01", "Zend-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
NeoTim/hiphop-php-docker
2ebf60db2c08bb93aef94ec9fab4d548f8f09bf4
51ae1a35e387c05f936cf59ed9d23965554d4b87
refs/heads/master
2020-04-16T09:17:51.394473
2017-12-03T18:45:36
2017-12-03T18:45:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
cpp
/* * Copyright 2012 Facebook, 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 "folly/experimental/File.h" #include <system_error> #include <glog/logging.h> namespace folly { File::File(const char* name, int flags, mode_t mode) : fd_(::open(name, flags, mode)), ownsFd_(false) { if (fd_ == -1) { throw std::system_error(errno, std::system_category(), "open() failed"); } ownsFd_ = true; } void File::close() { if (!closeNoThrow()) { throw std::system_error(errno, std::system_category(), "close() failed"); } } bool File::closeNoThrow() { int r = ownsFd_ ? ::close(fd_) : 0; release(); return r == 0; } } // namespace folly
[ "mikesjett@gmail.com" ]
mikesjett@gmail.com
6cfb044fe7c8836b3bba8677a5d83e069aa0f7ac
05b72d3eb9bc9b836aea86045cef02f17b3de3ea
/src/graf/grafDrawer.cpp
5d5c334c47097be35346e0bd0b4017af88542360
[]
no_license
jjzhang166/GA_Interactive
9b234c3611c041b9cc5e09a8e931678068af6b7a
c0fbb5f61d62727e56c70d0869c8af7bc9e9b010
refs/heads/master
2021-12-02T04:53:53.309527
2010-06-29T22:05:57
2010-06-29T22:05:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,478
cpp
#include "grafDrawer.h" grafDrawer::grafDrawer() { alpha = 1.f; minLen = .005; lineWidth = 2.0; lineAlpha = .92; lineScale = .05; bSetupDrawer = false; pctTransLine = .001; flatTime = 0; } grafDrawer::~grafDrawer() { for( int i = 0; i < lines.size(); i++) delete lines[i]; } void grafDrawer::setup(grafTagMulti * myTag, float maxLen ) { alpha = 1.f; if( myTag->myStrokes.size() == 0 ) return; if( lines.size() > 0 ) { for( int i = 0; i < lines.size(); i++) delete lines[i]; } lines.clear(); for( int i = 0; i < myTag->myStrokes.size(); i++) { lines.push_back( new grafLineDrawer() ); } for( int i = 0; i < myTag->myStrokes.size(); i++) { lines[i]->globalAlpha = lineAlpha; lines[i]->lineScale = lineScale; lines[i]->setup( myTag->myStrokes[i].pts, minLen, maxLen, .5f); } bSetupDrawer = false; pctTransLine = .001; } void grafDrawer::setAlpha(float a) { lineAlpha = a; for( int i = 0; i < lines.size(); i++) { lines[i]->globalAlpha = lineAlpha; } } void grafDrawer::setLineScale(float val) { if( lineScale != val ) { lineScale = val; for( int i = 0; i < lines.size(); i++) { lines[i]->lineScale = val; } bSetupDrawer = true; } } void grafDrawer::transition( float dt, float pct ) { average(pct); //alpha -= .35*dt; } void grafDrawer::transitionDeform( float dt, float pct, float * amps, int numAmps ) { float pctMe = 1-pctTransLine; float pctLn = pctTransLine; for( int i = 0; i < lines.size(); i++) { for( int j = 0; j < lines[i]->pts_l.size(); j++) { int ps = 1+(j % (numAmps-1)); float bandH = pct*(amps[ps]); lines[i]->pts_l[j].y = pctMe*lines[i]->pts_l[j].y+pctLn*(lines[i]->pts_lo[j].y+bandH);//.9*lines[i]->pts_l[j].y+.1*bandH; lines[i]->pts_r[j].y = pctMe*lines[i]->pts_r[j].y+pctLn*(lines[i]->pts_ro[j].y+bandH);//.9*lines[i]->pts_r[j].y+.1*bandH; lines[i]->pts_lout[j].y = pctMe*lines[i]->pts_lout[j].y+pctLn*(lines[i]->pts_lo[j].y+bandH);//.9*lines[i]->pts_l[j].y+.1*bandH; lines[i]->pts_rout[j].y = pctMe*lines[i]->pts_rout[j].y+pctLn*(lines[i]->pts_ro[j].y+bandH);//.9*lines[i]->pts_r[j].y+.1*bandH; } } //if( pctTransLine < .1 ) pctTransLine += .001; } void grafDrawer::transitionLineWidth( float dt, float avg ) { float pctMe = 1-pctTransLine; float pctLn = pctTransLine; for( int i = 0; i < lines.size(); i++) { for( int j = 0; j < lines[i]->pts_l.size(); j++) { lines[i]->pts_l[j].x = pctMe*lines[i]->pts_l[j].x+pctLn*(lines[i]->pts_lo[j].x+avg*-lines[i]->vecs[j].x); lines[i]->pts_l[j].y = pctMe*lines[i]->pts_l[j].y+pctLn*(lines[i]->pts_lo[j].y+avg*-lines[i]->vecs[j].y); lines[i]->pts_r[j].x = pctMe*lines[i]->pts_r[j].x+pctLn*(lines[i]->pts_ro[j].x+avg*lines[i]->vecs[j].x); lines[i]->pts_r[j].y = pctMe*lines[i]->pts_r[j].y+pctLn*(lines[i]->pts_ro[j].y+avg*lines[i]->vecs[j].y); lines[i]->pts_lout[j].x = pctMe*lines[i]->pts_lout[j].x+pctLn*(lines[i]->pts_lo[j].x+avg*-lines[i]->vecs[j].x); lines[i]->pts_lout[j].y = pctMe*lines[i]->pts_lout[j].y+pctLn*(lines[i]->pts_lo[j].y+avg*-lines[i]->vecs[j].y); lines[i]->pts_rout[j].x = pctMe*lines[i]->pts_rout[j].x+pctLn*(lines[i]->pts_ro[j].x+avg*lines[i]->vecs[j].x); lines[i]->pts_rout[j].y = pctMe*lines[i]->pts_rout[j].y+pctLn*(lines[i]->pts_ro[j].y+avg*lines[i]->vecs[j].y); } } //if( pctTransLine < .1 ) pctTransLine += .001; //alpha -= .35*dt; } void grafDrawer::transitionBounce( float dt, float avg ) { float pctMe = 1-pctTransLine; float pctLn = pctTransLine; for( int i = 0; i < lines.size(); i++) { for( int j = 0; j < lines[i]->pts_l.size(); j++) { lines[i]->pts_l[j].y = pctMe*lines[i]->pts_l[j].y+pctLn*(lines[i]->pts_lo[j].y+avg); lines[i]->pts_r[j].y = pctMe*lines[i]->pts_r[j].y+pctLn*(lines[i]->pts_ro[j].y+avg); lines[i]->pts_lout[j].y = pctMe*lines[i]->pts_lout[j].y+pctLn*(lines[i]->pts_lo[j].y+avg); lines[i]->pts_rout[j].y = pctMe*lines[i]->pts_rout[j].y+pctLn*(lines[i]->pts_ro[j].y+avg); } } //if( pctTransLine < .1 ) pctTransLine += .001; //alpha -= .35*dt; } void grafDrawer::transitionFlatten( float zDepth, float timeToDoIt ) { if( flatTime == 0 ) flatTime = ofGetElapsedTimef(); float pct = 1 - ((ofGetElapsedTimef()-flatTime) / timeToDoIt); for( int i = 0; i < lines.size(); i++) { for( int j = 0; j < lines[i]->pts_l.size(); j++) { lines[i]->pts_l[j].z = pct*lines[i]->pts_l[j].z + (1-pct)*zDepth; lines[i]->pts_r[j].z = pct*lines[i]->pts_r[j].z + (1-pct)*zDepth; lines[i]->pts_lout[j].z = pct*lines[i]->pts_lout[j].z + (1-pct)*zDepth; lines[i]->pts_rout[j].z = pct*lines[i]->pts_rout[j].z + (1-pct)*zDepth; } } } void grafDrawer::resetTransitions() { pctTransLine =.001; prelimTransTime = 0; flatTime = 0; } void grafDrawer::average( float pct ) { for( int i = 0; i < lines.size(); i++) lines[i]->average(pct); } void grafDrawer::draw( int lastStroke, int lastPoint) { glEnable( GL_DEPTH_TEST); for( int i = 0; i < lines.size(); i++) { if( i < lastStroke ) lines[i]->draw(-1,alpha); else if( i == lastStroke ) lines[i]->draw(lastPoint,alpha); //if( i < lastStroke ) lines[i]->drawOutline(-1,alpha,lineWidth); //else if( i == lastStroke ) lines[i]->drawOutline(lastPoint,alpha,lineWidth); } glDisable( GL_DEPTH_TEST ); } void grafDrawer::drawTimeLine(ofPoint center, float currentTime, float startTime, float z_const, ofTrueTypeFont * font, float scale ) { ofSetColor(255,255,255,255); float timeStart = startTime; float printTime = currentTime; currentTime = (1000 * currentTime )/ z_const; float linePoints[6]; linePoints[0] = center.y; linePoints[1] = center.x; linePoints[2] = startTime; linePoints[3] = center.y; linePoints[4] = center.x; linePoints[5] = currentTime; glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &linePoints[0]); glDrawArrays(GL_LINES, 0, 2); float h = .010; int count = 0; for( float t = timeStart; t < currentTime; t += (300 / z_const)) { if( count % 2 == 0) h = .020; else h = .010; linePoints[2] = t; linePoints[3] = center.y+h; linePoints[5] = t; glVertexPointer(3, GL_FLOAT, 0, &linePoints[0]); glDrawArrays(GL_LINES, 0, 2); count++; } // h = .030; glDisableClientState(GL_VERTEX_ARRAY); glPushMatrix(); glTranslatef(center.y,center.x,currentTime); glRotatef(90,0,0,1); glScalef(.5 * (1.0/scale),.5 * (1.0/scale),0); font->drawString( ofToString( printTime, 2 ) , 2,0); glPopMatrix(); } void grafDrawer::drawBoundingBox( ofPoint pmin, ofPoint pmax, ofPoint pcenter ) { glColor4f(1,1,1,1); // draw cube float pos[18]; glEnableClientState(GL_VERTEX_ARRAY); // front pos[0] = pmin.x; pos[1] = pmax.y; pos[2] = pmin.z; pos[3] = pmax.x; pos[4] = pmax.y; pos[5] = pmin.z; pos[6] = pmax.x; pos[7] = pmin.y; pos[8] = pmin.z; pos[9] = pmin.x; pos[10] = pmin.y; pos[11] = pmin.z; glVertexPointer(3, GL_FLOAT, 0, pos); glDrawArrays(GL_LINE_LOOP, 0, 4); // back pos[0] = pmin.x; pos[1] = pmax.y; pos[2] = pmax.z; pos[3] = pmax.x; pos[4] = pmax.y; pos[5] = pmax.z; pos[6] = pmax.x; pos[7] = pmin.y; pos[8] = pmax.z; pos[9] = pmin.x; pos[10] = pmin.y; pos[11] = pmax.z; glVertexPointer(3, GL_FLOAT, 0, pos); glDrawArrays(GL_LINE_LOOP, 0, 4); // top pos[0] = pmin.x; pos[1] = pmax.y; pos[2] = pmin.z; pos[3] = pmin.x; pos[4] = pmax.y; pos[5] = pmax.z; pos[6] = pmax.x; pos[7] = pmin.y; pos[8] = pmin.z; pos[9] = pmax.x; pos[10] = pmin.y; pos[11] = pmax.z; glVertexPointer(3, GL_FLOAT, 0, pos); glDrawArrays(GL_LINE_LOOP, 0, 4); // bottom pos[0] = pmin.x; pos[1] = pmin.y; pos[2] = pmin.z; pos[3] = pmin.x; pos[4] = pmin.y; pos[5] = pmax.z; pos[6] = pmax.x; pos[7] = pmin.y; pos[8] = pmax.z; pos[9] = pmax.x; pos[10] = pmin.y; pos[11] = pmin.z; pos[12] = pmin.x; pos[13] = pmin.y; pos[14] = pmin.z; glVertexPointer(3, GL_FLOAT, 0, pos); glDrawArrays(GL_LINE_LOOP, 0, 5); // centered /*pos[0] = pcenter.x-100; pos[1] = pcenter.y; pos[2] = pcenter.z; pos[3] = pcenter.x+100; pos[4] = pcenter.y; pos[5] = pcenter.z; pos[6] = pcenter.x; pos[7] = pcenter.y-100; pos[8] = pcenter.z; pos[9] = pcenter.x; pos[10] = pcenter.y+100; pos[11] = pcenter.z;*/ //glVertexPointer(3, GL_FLOAT, 0, pos); //glDrawArrays(GL_LINES, 0, 4); glDisable(GL_VERTEX_ARRAY); }
[ "csugrue@gmail.com" ]
csugrue@gmail.com
77add05879219a88a29082eb5d2aefa1924b3370
cd6a693f5d02d4b25c49d5804fabdb1b2c150a82
/include/EnumReflector.h
5361a5a09ba287a8a90d8d5b3d3d0970b932da90
[]
no_license
minortones/kissur
f9b04e560964728f5d6a436f448172b1b6b0c4be
72b69c135975a332f5c7662a80a43f1c69bd34e0
refs/heads/master
2020-05-17T15:37:11.332273
2016-02-21T04:07:46
2016-02-21T04:07:46
21,754,863
0
1
null
null
null
null
UTF-8
C++
false
false
1,160
h
#ifndef ENUM_REFLECTOR_H #define ENUM_REFLECTOR_H #include "Reflector.h" #include "EnumString.h" template<typename T> class EnumReflector : public IReflector { public: EnumReflector(); ~EnumReflector(); const char* ToString(const void* pValue) const override; const char* Typename() const override; ksU32 TypeID() const override; }; template<typename T> EnumReflector<T>::EnumReflector() {} template<typename T> EnumReflector<T>::~EnumReflector() {} template<typename T> const char* EnumReflector<T>::ToString( const void* pValue) const { return enumToString( *static_cast<const T*>(pValue) ); } template<typename T> kissType EnumReflector<T>::TypeID() const { return TypeUID<T>::TypeID(); } template<typename T> const char* EnumReflector<T>::Typename() const { return TypeUID<T>::Typename(); } ///////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////// template<typename T> IReflector* Refl::getReflectInterface(const enable_if_t< std::is_enum<T>::value, T>& pRHS) { static EnumReflector<T> enumReflect; return &enumReflect; } #endif
[ "minortones@yahoo.com" ]
minortones@yahoo.com
5a60c8352a5a1db085d189446ec5e8c091d1a489
0434508a7eb1237757b7a731d081a65559d88a0c
/FileTest2.cpp
e65414cb74eabbc1ffa8e31a49e09b07bbfe3272
[]
no_license
poseneror/ass-spl-1
76c0cf72f87ce44463e0cc123a2bebf05bca062e
2312be90cee5fc7d723f22e7563e1e67fed0d808
refs/heads/master
2021-09-05T19:36:47.484095
2018-01-30T15:54:45
2018-01-30T15:54:45
110,820,198
0
0
null
null
null
null
UTF-8
C++
false
false
4,604
cpp
// // Created by Guy-Amit on 11/8/2017. // #include "Files.h" #include "vector" #include <string> #include <iostream> using namespace std; int red=0; vector<string> test = {"0","1","2","3","4","5","6","7","8","9"}; vector<int> testInt; vector<string> temp; vector<int> tempInt; void extractVals(vector<BaseFile*> children){ temp.clear(); for (int i = 0; i <children.size() ; ++i) { temp.push_back(children[i]->getName()); } } void extractValsInt(vector<BaseFile*> children){ tempInt.clear(); for (int i = 0; i <children.size() ; ++i) { tempInt.push_back(children[i]->getSize()); } } template <typename T> bool comperVec(vector<T> v1, vector<T> v2){ for (int i = 0; i <v1.size() ; ++i) { if(v1[i]!=v2[i]) return false; } return true; } void null_check_parent(Directory root){ if(root.getParent()!= nullptr) red++; } int main(int , char **) { string name="root"; Directory root(name , nullptr); /*****************************/ /* Testing the root Directory*/ /*****************************/ null_check_parent(root); File * f =new File("hugabuga",5); root.addFile(f); root.removeFile(f->getName()); //test remove by name-root should by empty after deletion if(root.getChildren().size()>0) {red++; std::cout<<"the file hugabuga was not removed"<<std::endl; } File * g =new File("hugabuga",5); root.addFile(g); root.removeFile(g); //test remove by pointer-root should be empty after deletion if(root.getChildren().size()>0) {red++; std::cout<<"the file hugabuga was not removed"<<std::endl;} root.removeFile("guy"); //should print "file does not exists" std::cout<<"END of Root checks, please do not continue if there where errors"<<std::endl; /*********************************************/ /* Testing files and directories from level 1*/ /*********************************************/ //adding files to root for (int i = 0; i <10 ; ++i) { root.addFile(new File(std::to_string(i),i)); } // /addtion check extractVals(root.getChildren()); if(!comperVec(test,temp)){ red++; std::cout << "files addition filed" << std::endl; } //add same file check try { root.addFile(new File("0", 3)); root.addFile(new File("1", 4)); extractVals(root.getChildren()); if (!comperVec(test, temp)) { red++; std::cout << "you cant add the same file twice in the same directory" << std::endl; } } catch(std::exception){} //creating two directories under root Directory* emptyDir=new Directory("emptyDir",&root); Directory* dir1=new Directory("dir",&root); root.addFile(emptyDir); root.addFile(dir1); //adding files to dir1 for (int i = 0; i <10 ; ++i) { dir1->addFile(new File(std::to_string(i),i)); } dir1->addFile(new File(std::to_string(10),10)); root.removeFile("1"); //should remove from root and not from dir1 test={"0","2","3","4","5","6","7","8","9","emptyDir","dir"}; extractVals(root.getChildren()); if(!comperVec(test,temp)) { red++; std::cout<<"the file '1' was not removed"<<std::endl; } //sort test dir1->addFile(new File("01",2)); dir1->addFile(new File("02",5)); dir1->addFile(new File("00",4)); dir1->sortByName(); test={"0","00","01","02","1","10","2","3","4","5","6","7","8","9"}; extractVals(dir1->getChildren()); if(!comperVec(test,temp)) { red++; std::cout<<"sort by name does not work"<<std::endl; } dir1->sortBySize(); testInt ={0,1,2,2,3,4,4,5,5,6,7,8,9,10}; extractValsInt(dir1->getChildren()); if(!comperVec(test,temp)) { red++; std::cout<<"sort by size does not work"<<std::endl; } std::cout<<"END of level 1 checks, please do not continue if there where errors"<<std::endl; /*********************************************/ /* Testing files and directories from level 2*/ /*********************************************/ Directory* innerDir=new Directory("innerDir",dir1); dir1->addFile(innerDir); std::string path_inner="/dir/innerDir"; //compare innerDir.GetAbsolutePath to path_inner if(innerDir->getAbsolutePath()!=path_inner){ red++; std::cout<<"absolute path is not correct"<<std::endl; } std::cout<<"END of level 2 checks, please do not continue if there where errors"<<std::endl; std::cout << "the number of red test is:"<<red<<std::endl; }
[ "posener.or@gmail.com" ]
posener.or@gmail.com
08123dcf3def53504de3a9891c8ca8c7be463fe1
854daae5dfecf40c24b9dd6aa3ff18737377804f
/Engine/ResourceSystem.cpp
bbfe499035b29b2c45d280b28fd66aecc2d4db8f
[]
no_license
northwolf521/FlipEngine1
51f09af960503200085884294ce2b0b6be31169d
d1e562f03ff167c3e3f4e2cc9db27c242836bd89
refs/heads/master
2021-01-21T09:34:11.048692
2015-12-09T14:07:48
2015-12-09T14:07:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,632
cpp
#include "ResourceSystem.h" #include "Image.h" #include "ImageLoader.h" #include "Texture.h" #include <algorithm> #include <iostream> #include "MeshLoaderB3D.h" #include "Shader.h" #include "glutils.h" #include "../sys/sys_public.h" #include "Mesh.h" #include "Material.h" #include "File.h" #include "Model_lwo.h" #include "MeshLoader3DS.h" #include "../ShaderSource.h" static LoaderPlugin loaderPlugin[] = { { "jpg", loadImageJPG}, { "png", loadImagePNG}, { "tga", loadImageTGA}, { "bmp", loadImageBMP}, }; static int TexPluginCount = sizeof(loaderPlugin) / sizeof(LoaderPlugin); static Texture* defaultTexture; //-------------------------------------------------------------------------------------------- static Shader* LoadPostionShader() { Shader* shader = new Shader; shader->LoadFromBuffer(position_vert, position_frag); shader->SetName("position"); shader->BindAttribLocation(eAttrib_Position); shader->GetUniformLocation(eUniform_MVP); shader->GetUniformLocation(eUniform_Color); GL_CheckError("LoadPostionShader"); return shader; } static Shader* LoadPositionTexShader() { Shader* shader = new Shader; shader->LoadFromBuffer(positiontex_vert, positiontex_frag); shader->SetName("positionTex"); shader->BindAttribLocation(eAttrib_Position); shader->BindAttribLocation(eAttrib_TexCoord); shader->GetUniformLocation(eUniform_MVP); shader->GetUniformLocation(eUniform_Samper0); GL_CheckError("LoadPositionTexShader"); return shader; } static Shader* LoadPhongShader() { Shader* shader = new Shader; shader->LoadFromFile("../media/shader/phong.vert", "../media/shader/phong.frag"); shader->SetName("phong"); shader->BindAttribLocation(eAttrib_Position); shader->BindAttribLocation(eAttrib_TexCoord); shader->BindAttribLocation(eAttrib_Normal); shader->GetUniformLocation(eUniform_MVP); shader->GetUniformLocation(eUniform_EyePos); shader->GetUniformLocation(eUniform_LightPos); shader->GetUniformLocation(eUniform_ModelView); shader->GetUniformLocation(eUniform_InvModelView); shader->GetUniformLocation(eUniform_Samper0); GL_CheckError("load phong shader"); return shader; } static Shader* LoadBumpShader() { Shader* shader = resourceSys->AddShaderFromFile("../media/shader/bump.vert", "../media/shader/bump.frag"); shader->SetName("bump"); shader->BindAttribLocation(eAttrib_Position); shader->BindAttribLocation(eAttrib_TexCoord); shader->BindAttribLocation(eAttrib_Normal); shader->BindAttribLocation(eAttrib_Tangent); shader->BindAttribLocation(eAttrib_Binormal); shader->GetUniformLocation(eUniform_MVP); shader->GetUniformLocation(eUniform_EyePos); shader->GetUniformLocation(eUniform_LightPos); shader->GetUniformLocation(eUniform_ModelView); shader->GetUniformLocation(eUniform_InvModelView); shader->GetUniformLocation(eUniform_Samper0); shader->GetUniformLocation(eUniform_BumpMap); return shader; } static Shader* LoadBlurShader() { Shader* shader = new Shader; shader->LoadFromFile("../media/blur.vs", "../media/blur.fs"); shader->SetName("blur"); shader->BindAttribLocation(eAttrib_Position); shader->BindAttribLocation(eAttrib_TexCoord); shader->GetUniformLocation(eUniform_MVP); shader->GetUniformLocation(eUniform_Samper0); return shader; } static ShaderPlugin shaderplugin[] = { { eShader_Position, LoadPostionShader }, { eShader_PositionTex, LoadPositionTexShader }, //{ eShader_Phong, LoadPhongShader }, //{ eShader_Blur, LoadBlurShader }, //{ eShader_Bump, LoadBumpShader }, }; static int ShaderPluginCount = sizeof(shaderplugin) / sizeof(ShaderPlugin); //-------------------------------------------------------------------------------------------- static sysTextContent_t textContent; //ResourceManager* ResourceManager::sm_pSharedInstance = nullptr; ResourceSystem::ResourceSystem() { } ResourceSystem::~ResourceSystem() { } Texture* ResourceSystem::AddTexture(const char* file) { Texture* texture = NULL; lfStr fullPath = file; void* it = _textures.Get(fullPath); if( it != NULL ) { texture = (Texture*)it; return texture; } Image image; std::string basename(file); std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower); for (int i = 0; i < TexPluginCount; ++i) { if (basename.find(loaderPlugin[i].name) == std::string::npos) continue; if( !loaderPlugin[i].pFunc(fullPath.c_str(), image) ) { Sys_Printf( "load image %s failed\n", fullPath.c_str() ); return defaultTexture; } else { texture = new Texture(); texture->Init(&image); _textures.Put(fullPath, texture); return texture; } } Sys_Printf( "load image %s failed\n", fullPath.c_str() ); return defaultTexture; }; Mesh* ResourceSystem::AddMesh(const char* file) { lfStr str = file; if (str.Find(".lwo") != -1) { unsigned int failId; int failedPos; lwObject* object = lwGetObject(file, &failId, &failedPos); Mesh* mesh = new Mesh; mesh->ConvertLWOToModelSurfaces(object); delete object; return mesh; } else if (str.Find(".3ds") != -1) { return LoadMesh3DS(file); } else { MeshLoaderB3D meshLoader; meshLoader.Load(file); return meshLoader._mesh; } return NULL; } Texture* ResourceSystem::AddText( const char* text ) { if( Sys_DrawText(text, &textContent)) { // get the texture pixels, width, height Texture* texture = new Texture; texture->Init(textContent.w, textContent.h, textContent.pData); return texture; } else { Sys_Printf("sys_drawtext error %s\n", text); return defaultTexture; } } Shader* ResourceSystem::AddShaderFromFile( const char* vfile, const char* ffile ) { Shader* shader = new Shader; shader->LoadFromFile(vfile, ffile); return shader; } Material* ResourceSystem::AddMaterial( const char* file ) { Material* mtr; lfStr fullPath = file; auto it = _materials.Get(fullPath); if( it != NULL ) { mtr = (Material*) it; return mtr; } mtr = new Material(); mtr->SetName(file); const char* buffer = F_ReadFileData(file); //"../media/Position.mtr"); if (buffer == NULL) { Sys_Error("add material failed %s, file data is null\n", file); return NULL; } mtr->LoadMemory(buffer); _materials.Put(fullPath, mtr); return mtr; } bool ResourceSystem::LoadGLResource() { memset(_shaders, 0, 32); for (int i =0; i<ShaderPluginCount; i++) { _shaders[shaderplugin[i].name] = shaderplugin[i].func(); } defaultTexture = AddTexture("../Media/nskinbl.jpg"); return true; } Shader* ResourceSystem::FindShader( int shaderId ) { if (shaderId >= MAX_SHADER_COUNT && shaderId < 0) { Sys_Error("find shader out of bounds"); return NULL; } return _shaders[shaderId]; }
[ "356661627@qq.com" ]
356661627@qq.com
2b382a3c792639941874e9dfc616596d7055e470
6bb8d364eeb7d41aff3abe9e5fd040bb9e6c3925
/src/version.cpp
4e82843e6b56d27bac96fbbd62658c55d5599703
[ "MIT" ]
permissive
UKCDev/UKCoin
533fe230fc08a05ccee839f779a389fe2768ca6f
395aea978c1d61457a2b10e14f24350a9906a553
refs/heads/master
2021-01-21T13:30:16.084302
2018-05-13T12:05:51
2018-05-13T12:05:51
102,132,281
0
3
null
2017-09-25T16:11:54
2017-09-01T16:27:38
C
UTF-8
C++
false
false
2,638
cpp
// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("UK"); // Client version number #define CLIENT_VERSION_SUFFIX "III" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" // More informative with version number at this time. # define GIT_COMMIT_DATE "" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE);
[ "31538795+UKCDev@users.noreply.github.com" ]
31538795+UKCDev@users.noreply.github.com
7679d4d9ab6a6baf25121b4d2a767041cffc3fab
9cb14eaff82ba9cf75c6c99e34c9446ee9d7c17b
/codeforces/557/a.cpp
8b356f29c5592ef10ae53b6ee741d0b98b74aea4
[]
no_license
rafa95359/programacionCOmpetitiva
fe7008e85a41e958517a0c336bdb5da9c8a5df83
d471229758e9c4f3cac7459845e04c7056e2a1e0
refs/heads/master
2022-02-19T06:43:37.794325
2019-09-02T15:09:35
2019-09-02T15:09:35
183,834,924
0
0
null
null
null
null
UTF-8
C++
false
false
445
cpp
#include <bits/stdc++.h> using namespace std; #define para(i,a,n) for(int i=a;i<n;i++) #define N 1000000 typedef long long Long ; Long value(Long a,Long b,Long c ){ Long med=(a+b+c)/2; return med; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); Long n; cin>>n; para(i,0,n){ Long a,b,c; cin>>a>>b>>c; cout<<value(a,b,c)<<endl; } return 0; }
[ "rafalopezlizana@gmail.com" ]
rafalopezlizana@gmail.com
2c31ecbd5855d8f648992e34791696c03ca717d2
1112f3dd177d9e1a7563ee5e8e98610482c328bc
/c++/zero-matrix.cpp
d2028158792b750bd5dbe6af38568029a2ec1140
[]
no_license
SimonKocurek/Algorithms-and-Fun
01d8d751af63766ae34fcbbd2bb46e9178707a66
f4090393dfcdaba87babf7401876da161a16a1dd
refs/heads/master
2022-02-28T10:28:40.353537
2019-09-15T12:39:54
2019-09-15T12:39:54
115,929,701
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
cpp
#include <iostream> #include <vector> using namespace std; struct point { int x, y; }; auto get_zero_points(vector<vector<int>> &matrix) { vector<point> result; for (int y = 0; y < matrix.size(); ++y) { auto &line = matrix[y]; for (int x = 0; x < line.size(); ++x) { if (line[x] == 0) { result.push_back({x, y}); } } } return result; } void zero_matrix(vector<vector<int>> &matrix) { auto zero_points = get_zero_points(matrix); for (auto &zero_point : zero_points) { for (int x = 0; x < matrix[0].size(); ++x) { matrix[zero_point.y][x] = 0; } for (int y = 0; y < matrix.size(); ++y) { matrix[y][zero_point.x] = 0; } } } int main() { vector<vector<int>> matrix = { {1, 2, 3, 0}, {4, 5, 6, 7}, {8, 9, 10, 11}, {12, 0, 13, 14}, {15, 16, 17, 18}}; zero_matrix(matrix); for (auto &line : matrix) { for (auto value : line) { cout << value << " "; } cout << "\n"; } return 0; }
[ "simon.kocurek@gmail.com" ]
simon.kocurek@gmail.com
5b917562ba1e9546502cf61582d5a3d3a4719393
1fac2f62ec0135fb70ef7a17ac45dce8833e2a9c
/Amazon.cpp
32ee6c92aab96dcd9164167ef5204425d5c7b6b3
[]
no_license
dacr26/AmazonDriver
d525c5c6d30482e5ca041f0c0300d0cb8d5a8741
0f4e0c78519b710f12e4ef918b7896b36093864b
refs/heads/master
2020-04-05T02:53:36.471181
2018-11-13T02:22:07
2018-11-13T02:22:07
156,493,522
0
0
null
null
null
null
UTF-8
C++
false
false
355
cpp
/* * Amazon.cpp * * Created on: Nov 6, 2018 * Author: ruoranwang */ #include "Amazon.h" namespace edu { namespace neu { namespace csye6205 { Amazon::Amazon() { // TODO Auto-generated constructor stub } Amazon::~Amazon() { // TODO Auto-generated destructor stub } } /* namespace csye6205 */ } /* namespace neu */ } /* namespace edu */
[ "noreply@github.com" ]
dacr26.noreply@github.com
400b65cec300f10ed2eb925b0842728aaa8ef0df
b01ae19d6bce9229b83d0165601719ae53ae2ed0
/ios/versioned-react-native/ABI45_0_0/ReactNative/ReactCommon/react/renderer/core/tests/ABI45_0_0DynamicPropsUtilitiesTest.cpp
febba091dfac6d28c9c50067f0d6d0f10b12d557
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
Abhishek12345679/expo
1655f4f71afbee0e8ef4680e43586168f75e1914
8257de135f6d333860a73676509332c9cde04ba5
refs/heads/main
2023-02-20T19:46:17.694860
2022-11-21T15:48:20
2022-11-21T15:48:20
568,898,209
1
0
MIT
2022-11-21T16:39:42
2022-11-21T16:39:41
null
UTF-8
C++
false
false
2,044
cpp
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <gtest/gtest.h> #include <ABI45_0_0React/ABI45_0_0renderer/core/DynamicPropsUtilities.h> using namespace folly; using namespace ABI45_0_0facebook::ABI45_0_0React; /* Tests that verify expected behaviour from `folly::dynamic::merge_patch`. `merge_patch` is used for props forwarding on Android to enable Background Executor and will be removed once JNI layer is reimplmeneted. */ TEST(DynamicPropsUtilitiesTest, handleNestedObjects) { dynamic map1 = dynamic::object; map1["style"] = dynamic::object("backgroundColor", "red"); dynamic map2 = dynamic::object; map2["style"] = dynamic::object("backgroundColor", "blue")("color", "black"); map2["height"] = 100; auto result = mergeDynamicProps(map1, map2); ABI45_0_0EXPECT_TRUE(result["style"].isObject()); ABI45_0_0EXPECT_TRUE(result["style"]["backgroundColor"].isString()); ABI45_0_0EXPECT_TRUE(result["style"]["color"].isString()); ABI45_0_0EXPECT_TRUE(result["height"].isInt()); ABI45_0_0EXPECT_EQ(result["style"]["backgroundColor"].asString(), "blue"); ABI45_0_0EXPECT_EQ(result["style"]["color"], "black"); ABI45_0_0EXPECT_EQ(result["height"], 100); } TEST(DynamicPropsUtilitiesTest, handleEmptyObject) { dynamic map1 = dynamic::object; dynamic map2 = dynamic::object; map2["height"] = 100; auto result = mergeDynamicProps(map1, map2); ABI45_0_0EXPECT_TRUE(result["height"].isInt()); ABI45_0_0EXPECT_EQ(result["height"], 100); result = mergeDynamicProps(map1, map2); ABI45_0_0EXPECT_TRUE(result["height"].isInt()); ABI45_0_0EXPECT_EQ(result["height"], 100); } TEST(DynamicPropsUtilitiesTest, handleNull) { dynamic map1 = dynamic::object; map1["height"] = 100; dynamic map2 = dynamic::object; map2["height"] = nullptr; auto result = mergeDynamicProps(map1, map2); ABI45_0_0EXPECT_TRUE(result["height"].isNull()); }
[ "noreply@github.com" ]
Abhishek12345679.noreply@github.com
1eec8028a74809b10e347c012591081e76ede39b
f552f8eceee3fd8ad48c5a679bce0366f8f310c0
/XmlUtils.h
bc0b6b77f85142bc78c775f956ef9b4b00d5bda9
[]
no_license
mihazet/avr-ide
79689bf00c22d97cc2c728e60a4bc8d4c62297ce
09bcaccd6b61e49800f77f4953aea7e6b9478f5f
refs/heads/master
2021-01-10T21:06:56.814438
2013-07-22T06:28:12
2013-07-22T06:28:12
39,128,559
0
1
null
null
null
null
UTF-8
C++
false
false
1,139
h
#ifndef XML_UTILS_H #define XML_UTILS_H class XmlUtils { public: // helper function for read/write xml static wxString ReadElementStringByTag(wxXmlNode *parent, const wxString& tag) { wxXmlNode *children = parent->GetChildren(); while (children) { if (children->GetName() == tag) return children->GetNodeContent(); children = children->GetNext(); } return wxEmptyString; } static wxXmlNode *ReadElementByTag(wxXmlNode *parent, const wxString& tag) { wxXmlNode *children = parent->GetChildren(); while (children) { if (children->GetName() == tag) return children; children = children->GetNext(); } return 0; } static void WriteElementString(wxXmlNode *parent, const wxString& key, const wxString& value) { wxXmlNode *node = new wxXmlNode(wxXML_ELEMENT_NODE, key); new wxXmlNode(node, wxXML_TEXT_NODE, "", value); parent->AddChild(node); } static wxXmlNode *WriteElement(wxXmlNode *parent, const wxString& name) { wxXmlNode *node = new wxXmlNode(wxXML_ELEMENT_NODE, name); parent->AddChild(node); return node; } }; #endif
[ "miha8210@gmail.com" ]
miha8210@gmail.com
bca24069ea401dd820a74a76fc5c1381334897fe
6923f79f1eaaba0ab28b25337ba6cb56be97d32d
/GPU-Gems-Book-Source-Code/GPU-Gems-1-CD-Content/Performance_and_Practicalities/Integrating_HW_Shading/source/Paint.h
6771f1859243a09bb0fc69d25ac3027aa040d8b3
[]
no_license
burakbayramli/books
9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0
5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95
refs/heads/master
2023-08-17T05:31:08.885134
2023-08-14T10:05:37
2023-08-14T10:05:37
72,460,321
223
174
null
2022-10-24T12:15:06
2016-10-31T17:24:00
Jupyter Notebook
ISO-8859-1
C++
false
false
371
h
// from C4Dfx by Jörn Loviscach, www.l7h.cn // a function to render a single object and a function to render the scene #if !defined(PAINT_H) #define PAINT_H class ObjectIterator; class Materials; class BaseDocument; class ShadowMaps; extern void RenderSingleObject(ObjectIterator* oi); extern void Paint(BaseDocument* doc, Materials* mat, ShadowMaps* shadow); #endif
[ "me@yomama.com" ]
me@yomama.com
8dbfb5e0635ac854031172b9392575d2cb76e9fd
4b51c9e1145858a13243ef012180099634e1ca0d
/src/encrypt.h
5bb8738316f3a98d72887d894049ae941def6492
[ "MIT" ]
permissive
agongee/muse-kv
bfd8433934ac96ae0e4c5413c8bf3d2a68bbbd6d
9953c1e0923da27e8b5939a56a15d4fa502a65da
refs/heads/master
2020-06-25T14:24:24.477881
2019-09-18T02:04:54
2019-09-18T02:04:54
199,335,420
2
1
null
null
null
null
UTF-8
C++
false
false
2,712
h
/* MIT License Copyright (c) 2019 Taehun Kang(agongee123@gmail.com), Jaewoo Pyo(jwpyo98@gmail.com) and Bogyeong Park(parkbo0201@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. */ /* This file helps to encrypt and decrypt message */ #ifndef ENCRYPT_H #define ENCRYPT_H namespace encrypt_ { //calculate GCD of n1 and n2 by euclidean method inline int GCD(int n1, int n2) { if(n1 == 0) return n2; return GCD(n2%n1, n1); } std::pair<int, int> get_prime(int lowerbdd, int upperbdd); int get_encrypt_key(int P); int get_decrypt_key(int P, int e); int encrypt(int N, int e, uint8_t message); std::string encrypt_string(int N, int e, std::string message); uint8_t decrypt(int N, int d, int message); std::string decrypt_string(int N, int d, std::string encrypted_message); //generating encrypt key and decrypt key by using RSA Algorithm inline void key_generator() { while(true) { std::pair<int, int>primes = get_prime(256, 1024); int p = primes.first; int q = primes.second; int N = p * q; int P = (p - 1) * (q - 1); int e = get_encrypt_key(P); int d = get_decrypt_key(P, e); if(d < 0) continue; std::cout << "prime numbers : " << p << ", " << q << std::endl; std::cout << "encrypt key : " << e << std::endl; std::cout << "decrypt key : " << d << std::endl; int num; std::cin >> num; int encrypted_message = encrypt(N, e, num); std::cout << encrypted_message << std::endl; std::cout << (int)decrypt(N, d, encrypted_message) << std::endl; } } } #include "encrypt.cpp" #endif
[ "noreply@github.com" ]
agongee.noreply@github.com
d7f3fca77a83762ccb7bd230b5a517537dc4a688
f6439b5ed1614fd8db05fa963b47765eae225eb5
/media/cast/test/receiver.cc
e87055420f891f8b2219d102766a0bf78515e3c4
[ "BSD-3-Clause" ]
permissive
aranajhonny/chromium
b8a3c975211e1ea2f15b83647b4d8eb45252f1be
caf5bcb822f79b8997720e589334266551a50a13
refs/heads/master
2021-05-11T00:20:34.020261
2018-01-21T03:31:45
2018-01-21T03:31:45
118,301,142
2
0
null
null
null
null
UTF-8
C++
false
false
22,936
cc
// 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 <algorithm> #include <climits> #include <cstdarg> #include <cstdio> #include <deque> #include <map> #include <string> #include <utility> #include "base/at_exit.h" #include "base/command_line.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "base/time/default_tick_clock.h" #include "base/timer/timer.h" #include "media/audio/audio_io.h" #include "media/audio/audio_manager.h" #include "media/audio/audio_parameters.h" #include "media/audio/fake_audio_log_factory.h" #include "media/base/audio_bus.h" #include "media/base/channel_layout.h" #include "media/base/video_frame.h" #include "media/cast/cast_config.h" #include "media/cast/cast_environment.h" #include "media/cast/cast_receiver.h" #include "media/cast/logging/logging_defines.h" #include "media/cast/net/udp_transport.h" #include "media/cast/test/utility/audio_utility.h" #include "media/cast/test/utility/barcode.h" #include "media/cast/test/utility/default_config.h" #include "media/cast/test/utility/in_process_receiver.h" #include "media/cast/test/utility/input_builder.h" #include "media/cast/test/utility/standalone_cast_environment.h" #include "net/base/net_util.h" #if defined(OS_LINUX) #include "media/cast/test/linux_output_window.h" #endif // OS_LINUX namespace media { namespace cast { // Settings chosen to match default sender settings. #define DEFAULT_SEND_PORT "0" #define DEFAULT_RECEIVE_PORT "2344" #define DEFAULT_SEND_IP "0.0.0.0" #define DEFAULT_AUDIO_FEEDBACK_SSRC "2" #define DEFAULT_AUDIO_INCOMING_SSRC "1" #define DEFAULT_AUDIO_PAYLOAD_TYPE "127" #define DEFAULT_VIDEO_FEEDBACK_SSRC "12" #define DEFAULT_VIDEO_INCOMING_SSRC "11" #define DEFAULT_VIDEO_PAYLOAD_TYPE "96" #if defined(OS_LINUX) const char* kVideoWindowWidth = "1280"; const char* kVideoWindowHeight = "720"; #endif // OS_LINUX void GetPorts(int* tx_port, int* rx_port) { test::InputBuilder tx_input( "Enter send port.", DEFAULT_SEND_PORT, 1, INT_MAX); *tx_port = tx_input.GetIntInput(); test::InputBuilder rx_input( "Enter receive port.", DEFAULT_RECEIVE_PORT, 1, INT_MAX); *rx_port = rx_input.GetIntInput(); } std::string GetIpAddress(const std::string display_text) { test::InputBuilder input(display_text, DEFAULT_SEND_IP, INT_MIN, INT_MAX); std::string ip_address = input.GetStringInput(); // Ensure IP address is either the default value or in correct form. while (ip_address != DEFAULT_SEND_IP && std::count(ip_address.begin(), ip_address.end(), '.') != 3) { ip_address = input.GetStringInput(); } return ip_address; } void GetAudioSsrcs(FrameReceiverConfig* audio_config) { test::InputBuilder input_tx( "Choose audio sender SSRC.", DEFAULT_AUDIO_FEEDBACK_SSRC, 1, INT_MAX); audio_config->feedback_ssrc = input_tx.GetIntInput(); test::InputBuilder input_rx( "Choose audio receiver SSRC.", DEFAULT_AUDIO_INCOMING_SSRC, 1, INT_MAX); audio_config->incoming_ssrc = input_rx.GetIntInput(); } void GetVideoSsrcs(FrameReceiverConfig* video_config) { test::InputBuilder input_tx( "Choose video sender SSRC.", DEFAULT_VIDEO_FEEDBACK_SSRC, 1, INT_MAX); video_config->feedback_ssrc = input_tx.GetIntInput(); test::InputBuilder input_rx( "Choose video receiver SSRC.", DEFAULT_VIDEO_INCOMING_SSRC, 1, INT_MAX); video_config->incoming_ssrc = input_rx.GetIntInput(); } #if defined(OS_LINUX) void GetWindowSize(int* width, int* height) { // Resolution values based on sender settings test::InputBuilder input_w( "Choose window width.", kVideoWindowWidth, 144, 1920); *width = input_w.GetIntInput(); test::InputBuilder input_h( "Choose window height.", kVideoWindowHeight, 176, 1080); *height = input_h.GetIntInput(); } #endif // OS_LINUX void GetAudioPayloadtype(FrameReceiverConfig* audio_config) { test::InputBuilder input("Choose audio receiver payload type.", DEFAULT_AUDIO_PAYLOAD_TYPE, 96, 127); audio_config->rtp_payload_type = input.GetIntInput(); } FrameReceiverConfig GetAudioReceiverConfig() { FrameReceiverConfig audio_config = GetDefaultAudioReceiverConfig(); GetAudioSsrcs(&audio_config); GetAudioPayloadtype(&audio_config); audio_config.rtp_max_delay_ms = 300; return audio_config; } void GetVideoPayloadtype(FrameReceiverConfig* video_config) { test::InputBuilder input("Choose video receiver payload type.", DEFAULT_VIDEO_PAYLOAD_TYPE, 96, 127); video_config->rtp_payload_type = input.GetIntInput(); } FrameReceiverConfig GetVideoReceiverConfig() { FrameReceiverConfig video_config = GetDefaultVideoReceiverConfig(); GetVideoSsrcs(&video_config); GetVideoPayloadtype(&video_config); video_config.rtp_max_delay_ms = 300; return video_config; } AudioParameters ToAudioParameters(const FrameReceiverConfig& config) { const int samples_in_10ms = config.frequency / 100; return AudioParameters(AudioParameters::AUDIO_PCM_LOW_LATENCY, GuessChannelLayout(config.channels), config.frequency, 32, samples_in_10ms); } // An InProcessReceiver that renders video frames to a LinuxOutputWindow and // audio frames via Chromium's audio stack. // // InProcessReceiver pushes audio and video frames to this subclass, and these // frames are pushed into a queue. Then, for audio, the Chromium audio stack // will make polling calls on a separate, unknown thread whereby audio frames // are pulled out of the audio queue as needed. For video, however, NaivePlayer // is responsible for scheduling updates to the screen itself. For both, the // queues are pruned (i.e., received frames are skipped) when the system is not // able to play back as fast as frames are entering the queue. // // This is NOT a good reference implementation for a Cast receiver player since: // 1. It only skips frames to handle slower-than-expected playout, or halts // playback to handle frame underruns. // 2. It makes no attempt to synchronize the timing of playout of the video // frames with the audio frames. // 3. It does nothing to smooth or hide discontinuities in playback due to // timing issues or missing frames. class NaivePlayer : public InProcessReceiver, public AudioOutputStream::AudioSourceCallback { public: NaivePlayer(const scoped_refptr<CastEnvironment>& cast_environment, const net::IPEndPoint& local_end_point, const net::IPEndPoint& remote_end_point, const FrameReceiverConfig& audio_config, const FrameReceiverConfig& video_config, int window_width, int window_height) : InProcessReceiver(cast_environment, local_end_point, remote_end_point, audio_config, video_config), // Maximum age is the duration of 3 video frames. 3 was chosen // arbitrarily, but seems to work well. max_frame_age_(base::TimeDelta::FromSeconds(1) * 3 / video_config.max_frame_rate), #if defined(OS_LINUX) render_(0, 0, window_width, window_height, "Cast_receiver"), #endif // OS_LINUX num_video_frames_processed_(0), num_audio_frames_processed_(0), currently_playing_audio_frame_start_(-1) {} virtual ~NaivePlayer() {} virtual void Start() OVERRIDE { AudioManager::Get()->GetTaskRunner()->PostTask( FROM_HERE, base::Bind(&NaivePlayer::StartAudioOutputOnAudioManagerThread, base::Unretained(this))); // Note: No need to wait for audio polling to start since the push-and-pull // mechanism is synchronized via the |audio_playout_queue_|. InProcessReceiver::Start(); } virtual void Stop() OVERRIDE { // First, stop audio output to the Chromium audio stack. base::WaitableEvent done(false, false); DCHECK(!AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); AudioManager::Get()->GetTaskRunner()->PostTask( FROM_HERE, base::Bind(&NaivePlayer::StopAudioOutputOnAudioManagerThread, base::Unretained(this), &done)); done.Wait(); // Now, stop receiving new frames. InProcessReceiver::Stop(); // Finally, clear out any frames remaining in the queues. while (!audio_playout_queue_.empty()) { const scoped_ptr<AudioBus> to_be_deleted( audio_playout_queue_.front().second); audio_playout_queue_.pop_front(); } video_playout_queue_.clear(); } private: void StartAudioOutputOnAudioManagerThread() { DCHECK(AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); DCHECK(!audio_output_stream_); audio_output_stream_.reset(AudioManager::Get()->MakeAudioOutputStreamProxy( ToAudioParameters(audio_config()), "")); if (audio_output_stream_.get() && audio_output_stream_->Open()) { audio_output_stream_->Start(this); } else { LOG(ERROR) << "Failed to open an audio output stream. " << "Audio playback disabled."; audio_output_stream_.reset(); } } void StopAudioOutputOnAudioManagerThread(base::WaitableEvent* done) { DCHECK(AudioManager::Get()->GetTaskRunner()->BelongsToCurrentThread()); if (audio_output_stream_.get()) { audio_output_stream_->Stop(); audio_output_stream_->Close(); audio_output_stream_.reset(); } done->Signal(); } //////////////////////////////////////////////////////////////////// // InProcessReceiver overrides. virtual void OnVideoFrame(const scoped_refptr<VideoFrame>& video_frame, const base::TimeTicks& playout_time, bool is_continuous) OVERRIDE { DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN)); LOG_IF(WARNING, !is_continuous) << "Video: Discontinuity in received frames."; video_playout_queue_.push_back(std::make_pair(playout_time, video_frame)); ScheduleVideoPlayout(); uint16 frame_no; if (media::cast::test::DecodeBarcode(video_frame, &frame_no)) { video_play_times_.insert( std::pair<uint16, base::TimeTicks>(frame_no, playout_time)); } else { VLOG(2) << "Barcode decode failed!"; } } virtual void OnAudioFrame(scoped_ptr<AudioBus> audio_frame, const base::TimeTicks& playout_time, bool is_continuous) OVERRIDE { DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN)); LOG_IF(WARNING, !is_continuous) << "Audio: Discontinuity in received frames."; base::AutoLock auto_lock(audio_lock_); uint16 frame_no; if (media::cast::DecodeTimestamp(audio_frame->channel(0), audio_frame->frames(), &frame_no)) { // Since there are lots of audio packets with the same frame_no, // we really want to make sure that we get the playout_time from // the first one. If is_continous is true, then it's possible // that we already missed the first one. if (is_continuous && frame_no == last_audio_frame_no_ + 1) { audio_play_times_.insert( std::pair<uint16, base::TimeTicks>(frame_no, playout_time)); } last_audio_frame_no_ = frame_no; } else { VLOG(2) << "Audio decode failed!"; last_audio_frame_no_ = -2; } audio_playout_queue_.push_back( std::make_pair(playout_time, audio_frame.release())); } // End of InProcessReceiver overrides. //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// // AudioSourceCallback implementation. virtual int OnMoreData(AudioBus* dest, AudioBuffersState buffers_state) OVERRIDE { // Note: This method is being invoked by a separate thread unknown to us // (i.e., outside of CastEnvironment). int samples_remaining = dest->frames(); while (samples_remaining > 0) { // Get next audio frame ready for playout. if (!currently_playing_audio_frame_.get()) { base::AutoLock auto_lock(audio_lock_); // Prune the queue, skipping entries that are too old. // TODO(miu): Use |buffers_state| to account for audio buffering delays // upstream. const base::TimeTicks earliest_time_to_play = cast_env()->Clock()->NowTicks() - max_frame_age_; while (!audio_playout_queue_.empty() && audio_playout_queue_.front().first < earliest_time_to_play) { PopOneAudioFrame(true); } if (audio_playout_queue_.empty()) break; currently_playing_audio_frame_ = PopOneAudioFrame(false).Pass(); currently_playing_audio_frame_start_ = 0; } // Copy some or all of the samples in |currently_playing_audio_frame_| to // |dest|. Once all samples in |currently_playing_audio_frame_| have been // consumed, release it. const int num_samples_to_copy = std::min(samples_remaining, currently_playing_audio_frame_->frames() - currently_playing_audio_frame_start_); currently_playing_audio_frame_->CopyPartialFramesTo( currently_playing_audio_frame_start_, num_samples_to_copy, 0, dest); samples_remaining -= num_samples_to_copy; currently_playing_audio_frame_start_ += num_samples_to_copy; if (currently_playing_audio_frame_start_ == currently_playing_audio_frame_->frames()) { currently_playing_audio_frame_.reset(); } } // If |dest| has not been fully filled, then an underrun has occurred; and // fill the remainder of |dest| with zeros. if (samples_remaining > 0) { // Note: Only logging underruns after the first frame has been received. LOG_IF(WARNING, currently_playing_audio_frame_start_ != -1) << "Audio: Playback underrun of " << samples_remaining << " samples!"; dest->ZeroFramesPartial(dest->frames() - samples_remaining, samples_remaining); } return dest->frames(); } virtual void OnError(AudioOutputStream* stream) OVERRIDE { LOG(ERROR) << "AudioOutputStream reports an error. " << "Playback is unlikely to continue."; } // End of AudioSourceCallback implementation. //////////////////////////////////////////////////////////////////// void ScheduleVideoPlayout() { DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN)); // Prune the queue, skipping entries that are too old. const base::TimeTicks now = cast_env()->Clock()->NowTicks(); const base::TimeTicks earliest_time_to_play = now - max_frame_age_; while (!video_playout_queue_.empty() && video_playout_queue_.front().first < earliest_time_to_play) { PopOneVideoFrame(true); } // If the queue is not empty, schedule playout of its first frame. if (video_playout_queue_.empty()) { video_playout_timer_.Stop(); } else { video_playout_timer_.Start( FROM_HERE, video_playout_queue_.front().first - now, base::Bind(&NaivePlayer::PlayNextVideoFrame, base::Unretained(this))); } } void PlayNextVideoFrame() { DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN)); if (!video_playout_queue_.empty()) { const scoped_refptr<VideoFrame> video_frame = PopOneVideoFrame(false); #ifdef OS_LINUX render_.RenderFrame(video_frame); #endif // OS_LINUX } ScheduleVideoPlayout(); CheckAVSync(); } scoped_refptr<VideoFrame> PopOneVideoFrame(bool is_being_skipped) { DCHECK(cast_env()->CurrentlyOn(CastEnvironment::MAIN)); if (is_being_skipped) { VLOG(1) << "VideoFrame[" << num_video_frames_processed_ << " (dt=" << (video_playout_queue_.front().first - last_popped_video_playout_time_).InMicroseconds() << " usec)]: Skipped."; } else { VLOG(1) << "VideoFrame[" << num_video_frames_processed_ << " (dt=" << (video_playout_queue_.front().first - last_popped_video_playout_time_).InMicroseconds() << " usec)]: Playing " << (cast_env()->Clock()->NowTicks() - video_playout_queue_.front().first).InMicroseconds() << " usec later than intended."; } last_popped_video_playout_time_ = video_playout_queue_.front().first; const scoped_refptr<VideoFrame> ret = video_playout_queue_.front().second; video_playout_queue_.pop_front(); ++num_video_frames_processed_; return ret; } scoped_ptr<AudioBus> PopOneAudioFrame(bool was_skipped) { audio_lock_.AssertAcquired(); if (was_skipped) { VLOG(1) << "AudioFrame[" << num_audio_frames_processed_ << " (dt=" << (audio_playout_queue_.front().first - last_popped_audio_playout_time_).InMicroseconds() << " usec)]: Skipped."; } else { VLOG(1) << "AudioFrame[" << num_audio_frames_processed_ << " (dt=" << (audio_playout_queue_.front().first - last_popped_audio_playout_time_).InMicroseconds() << " usec)]: Playing " << (cast_env()->Clock()->NowTicks() - audio_playout_queue_.front().first).InMicroseconds() << " usec later than intended."; } last_popped_audio_playout_time_ = audio_playout_queue_.front().first; scoped_ptr<AudioBus> ret(audio_playout_queue_.front().second); audio_playout_queue_.pop_front(); ++num_audio_frames_processed_; return ret.Pass(); } void CheckAVSync() { if (video_play_times_.size() > 30 && audio_play_times_.size() > 30) { size_t num_events = 0; base::TimeDelta delta; std::map<uint16, base::TimeTicks>::iterator audio_iter, video_iter; for (video_iter = video_play_times_.begin(); video_iter != video_play_times_.end(); ++video_iter) { audio_iter = audio_play_times_.find(video_iter->first); if (audio_iter != audio_play_times_.end()) { num_events++; // Positive values means audio is running behind video. delta += audio_iter->second - video_iter->second; } } if (num_events > 30) { VLOG(0) << "Audio behind by: " << (delta / num_events).InMilliseconds() << "ms"; video_play_times_.clear(); audio_play_times_.clear(); } } else if (video_play_times_.size() + audio_play_times_.size() > 500) { // We are decoding audio or video timestamps, but not both, clear it out. video_play_times_.clear(); audio_play_times_.clear(); } } // Frames in the queue older than this (relative to NowTicks()) will be // dropped (i.e., playback is falling behind). const base::TimeDelta max_frame_age_; // Outputs created, started, and destroyed by this NaivePlayer. #ifdef OS_LINUX test::LinuxOutputWindow render_; #endif // OS_LINUX scoped_ptr<AudioOutputStream> audio_output_stream_; // Video playout queue. typedef std::pair<base::TimeTicks, scoped_refptr<VideoFrame> > VideoQueueEntry; std::deque<VideoQueueEntry> video_playout_queue_; base::TimeTicks last_popped_video_playout_time_; int64 num_video_frames_processed_; base::OneShotTimer<NaivePlayer> video_playout_timer_; // Audio playout queue, synchronized by |audio_lock_|. base::Lock audio_lock_; typedef std::pair<base::TimeTicks, AudioBus*> AudioQueueEntry; std::deque<AudioQueueEntry> audio_playout_queue_; base::TimeTicks last_popped_audio_playout_time_; int64 num_audio_frames_processed_; // These must only be used on the audio thread calling OnMoreData(). scoped_ptr<AudioBus> currently_playing_audio_frame_; int currently_playing_audio_frame_start_; std::map<uint16, base::TimeTicks> audio_play_times_; std::map<uint16, base::TimeTicks> video_play_times_; int32 last_audio_frame_no_; }; } // namespace cast } // namespace media int main(int argc, char** argv) { base::AtExitManager at_exit; CommandLine::Init(argc, argv); InitLogging(logging::LoggingSettings()); scoped_refptr<media::cast::CastEnvironment> cast_environment( new media::cast::StandaloneCastEnvironment); // Start up Chromium audio system. media::FakeAudioLogFactory fake_audio_log_factory_; const scoped_ptr<media::AudioManager> audio_manager( media::AudioManager::Create(&fake_audio_log_factory_)); CHECK(media::AudioManager::Get()); media::cast::FrameReceiverConfig audio_config = media::cast::GetAudioReceiverConfig(); media::cast::FrameReceiverConfig video_config = media::cast::GetVideoReceiverConfig(); // Determine local and remote endpoints. int remote_port, local_port; media::cast::GetPorts(&remote_port, &local_port); if (!local_port) { LOG(ERROR) << "Invalid local port."; return 1; } std::string remote_ip_address = media::cast::GetIpAddress("Enter remote IP."); std::string local_ip_address = media::cast::GetIpAddress("Enter local IP."); net::IPAddressNumber remote_ip_number; net::IPAddressNumber local_ip_number; if (!net::ParseIPLiteralToNumber(remote_ip_address, &remote_ip_number)) { LOG(ERROR) << "Invalid remote IP address."; return 1; } if (!net::ParseIPLiteralToNumber(local_ip_address, &local_ip_number)) { LOG(ERROR) << "Invalid local IP address."; return 1; } net::IPEndPoint remote_end_point(remote_ip_number, remote_port); net::IPEndPoint local_end_point(local_ip_number, local_port); // Create and start the player. int window_width = 0; int window_height = 0; #if defined(OS_LINUX) media::cast::GetWindowSize(&window_width, &window_height); #endif // OS_LINUX media::cast::NaivePlayer player(cast_environment, local_end_point, remote_end_point, audio_config, video_config, window_width, window_height); player.Start(); base::MessageLoop().Run(); // Run forever (i.e., until SIGTERM). NOTREACHED(); return 0; }
[ "jhonnyjosearana@gmail.com" ]
jhonnyjosearana@gmail.com
9e7f5d7988682aacdb7195e4c0e83f08e5596c11
3e637dc8bbd968017fff17ae78122dda07011775
/third_party/skia/src/gpu/gl/GrGLProgram.cpp
f16812b54d179ebccdc4c434011b46c6566dfa08
[ "BSD-3-Clause" ]
permissive
lineCode/chromium_ui
8cba926b4e1deadb8dc81b7550719fb7fb2cda29
e40185109eede35e80224780dd473dfe8369a397
refs/heads/master
2020-11-24T12:35:56.932529
2018-11-11T14:40:49
2018-11-11T14:40:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
54,932
cpp
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrGLProgram.h" #include "GrAllocator.h" #include "GrCustomStage.h" #include "GrGLProgramStage.h" #include "gl/GrGLShaderBuilder.h" #include "GrGLShaderVar.h" #include "GrProgramStageFactory.h" #include "SkTrace.h" #include "SkXfermode.h" namespace { enum { /// Used to mark a StageUniLocation field that should be bound /// to a uniform during getUniformLocationsAndInitCache(). kUseUniform = 2000 }; } // namespace #define PRINT_SHADERS 0 typedef GrGLProgram::ProgramDesc::StageDesc StageDesc; #define VIEW_MATRIX_NAME "uViewM" #define POS_ATTR_NAME "aPosition" #define COL_ATTR_NAME "aColor" #define COV_ATTR_NAME "aCoverage" #define EDGE_ATTR_NAME "aEdge" #define COL_UNI_NAME "uColor" #define COV_UNI_NAME "uCoverage" #define COL_FILTER_UNI_NAME "uColorFilter" #define COL_MATRIX_UNI_NAME "uColorMatrix" #define COL_MATRIX_VEC_UNI_NAME "uColorMatrixVec" namespace { inline void tex_attr_name(int coordIdx, GrStringBuilder* s) { *s = "aTexCoord"; s->appendS32(coordIdx); } inline const char* float_vector_type_str(int count) { return GrGLShaderVar::TypeString(GrSLFloatVectorType(count)); } inline const char* vector_all_coords(int count) { static const char* ALL[] = {"ERROR", "", ".xy", ".xyz", ".xyzw"}; GrAssert(count >= 1 && count < (int)GR_ARRAY_COUNT(ALL)); return ALL[count]; } inline const char* all_ones_vec(int count) { static const char* ONESVEC[] = {"ERROR", "1.0", "vec2(1,1)", "vec3(1,1,1)", "vec4(1,1,1,1)"}; GrAssert(count >= 1 && count < (int)GR_ARRAY_COUNT(ONESVEC)); return ONESVEC[count]; } inline const char* all_zeros_vec(int count) { static const char* ZEROSVEC[] = {"ERROR", "0.0", "vec2(0,0)", "vec3(0,0,0)", "vec4(0,0,0,0)"}; GrAssert(count >= 1 && count < (int)GR_ARRAY_COUNT(ZEROSVEC)); return ZEROSVEC[count]; } inline const char* declared_color_output_name() { return "fsColorOut"; } inline const char* dual_source_output_name() { return "dualSourceOut"; } inline void tex_matrix_name(int stage, GrStringBuilder* s) { *s = "uTexM"; s->appendS32(stage); } inline void sampler_name(int stage, GrStringBuilder* s) { *s = "uSampler"; s->appendS32(stage); } inline void tex_domain_name(int stage, GrStringBuilder* s) { *s = "uTexDom"; s->appendS32(stage); } } GrGLProgram::GrGLProgram() { } GrGLProgram::~GrGLProgram() { } void GrGLProgram::overrideBlend(GrBlendCoeff* srcCoeff, GrBlendCoeff* dstCoeff) const { switch (fProgramDesc.fDualSrcOutput) { case ProgramDesc::kNone_DualSrcOutput: break; // the prog will write a coverage value to the secondary // output and the dst is blended by one minus that value. case ProgramDesc::kCoverage_DualSrcOutput: case ProgramDesc::kCoverageISA_DualSrcOutput: case ProgramDesc::kCoverageISC_DualSrcOutput: *dstCoeff = (GrBlendCoeff)GrGpu::kIS2C_GrBlendCoeff; break; default: GrCrash("Unexpected dual source blend output"); break; } } // assigns modulation of two vars to an output var // vars can be vec4s or floats (or one of each) // result is always vec4 // if either var is "" then assign to the other var // if both are "" then assign all ones static inline void modulate_helper(const char* outputVar, const char* var0, const char* var1, GrStringBuilder* code) { GrAssert(NULL != outputVar); GrAssert(NULL != var0); GrAssert(NULL != var1); GrAssert(NULL != code); bool has0 = '\0' != *var0; bool has1 = '\0' != *var1; if (!has0 && !has1) { code->appendf("\t%s = %s;\n", outputVar, all_ones_vec(4)); } else if (!has0) { code->appendf("\t%s = vec4(%s);\n", outputVar, var1); } else if (!has1) { code->appendf("\t%s = vec4(%s);\n", outputVar, var0); } else { code->appendf("\t%s = vec4(%s * %s);\n", outputVar, var0, var1); } } // assigns addition of two vars to an output var // vars can be vec4s or floats (or one of each) // result is always vec4 // if either var is "" then assign to the other var // if both are "" then assign all zeros static inline void add_helper(const char* outputVar, const char* var0, const char* var1, GrStringBuilder* code) { GrAssert(NULL != outputVar); GrAssert(NULL != var0); GrAssert(NULL != var1); GrAssert(NULL != code); bool has0 = '\0' != *var0; bool has1 = '\0' != *var1; if (!has0 && !has1) { code->appendf("\t%s = %s;\n", outputVar, all_zeros_vec(4)); } else if (!has0) { code->appendf("\t%s = vec4(%s);\n", outputVar, var1); } else if (!has1) { code->appendf("\t%s = vec4(%s);\n", outputVar, var0); } else { code->appendf("\t%s = vec4(%s + %s);\n", outputVar, var0, var1); } } // given two blend coeffecients determine whether the src // and/or dst computation can be omitted. static inline void needBlendInputs(SkXfermode::Coeff srcCoeff, SkXfermode::Coeff dstCoeff, bool* needSrcValue, bool* needDstValue) { if (SkXfermode::kZero_Coeff == srcCoeff) { switch (dstCoeff) { // these all read the src case SkXfermode::kSC_Coeff: case SkXfermode::kISC_Coeff: case SkXfermode::kSA_Coeff: case SkXfermode::kISA_Coeff: *needSrcValue = true; break; default: *needSrcValue = false; break; } } else { *needSrcValue = true; } if (SkXfermode::kZero_Coeff == dstCoeff) { switch (srcCoeff) { // these all read the dst case SkXfermode::kDC_Coeff: case SkXfermode::kIDC_Coeff: case SkXfermode::kDA_Coeff: case SkXfermode::kIDA_Coeff: *needDstValue = true; break; default: *needDstValue = false; break; } } else { *needDstValue = true; } } /** * Create a blend_coeff * value string to be used in shader code. Sets empty * string if result is trivially zero. */ static void blendTermString(GrStringBuilder* str, SkXfermode::Coeff coeff, const char* src, const char* dst, const char* value) { switch (coeff) { case SkXfermode::kZero_Coeff: /** 0 */ *str = ""; break; case SkXfermode::kOne_Coeff: /** 1 */ *str = value; break; case SkXfermode::kSC_Coeff: str->printf("(%s * %s)", src, value); break; case SkXfermode::kISC_Coeff: str->printf("((%s - %s) * %s)", all_ones_vec(4), src, value); break; case SkXfermode::kDC_Coeff: str->printf("(%s * %s)", dst, value); break; case SkXfermode::kIDC_Coeff: str->printf("((%s - %s) * %s)", all_ones_vec(4), dst, value); break; case SkXfermode::kSA_Coeff: /** src alpha */ str->printf("(%s.a * %s)", src, value); break; case SkXfermode::kISA_Coeff: /** inverse src alpha (i.e. 1 - sa) */ str->printf("((1.0 - %s.a) * %s)", src, value); break; case SkXfermode::kDA_Coeff: /** dst alpha */ str->printf("(%s.a * %s)", dst, value); break; case SkXfermode::kIDA_Coeff: /** inverse dst alpha (i.e. 1 - da) */ str->printf("((1.0 - %s.a) * %s)", dst, value); break; default: GrCrash("Unexpected xfer coeff."); break; } } /** * Adds a line to the fragment shader code which modifies the color by * the specified color filter. */ static void addColorFilter(GrStringBuilder* fsCode, const char * outputVar, SkXfermode::Coeff uniformCoeff, SkXfermode::Coeff colorCoeff, const char* inColor) { GrStringBuilder colorStr, constStr; blendTermString(&colorStr, colorCoeff, COL_FILTER_UNI_NAME, inColor, inColor); blendTermString(&constStr, uniformCoeff, COL_FILTER_UNI_NAME, inColor, COL_FILTER_UNI_NAME); add_helper(outputVar, colorStr.c_str(), constStr.c_str(), fsCode); } /** * Adds code to the fragment shader code which modifies the color by * the specified color matrix. */ static void addColorMatrix(GrStringBuilder* fsCode, const char * outputVar, const char* inColor) { fsCode->appendf("\t%s = %s * vec4(%s.rgb / %s.a, %s.a) + %s;\n", outputVar, COL_MATRIX_UNI_NAME, inColor, inColor, inColor, COL_MATRIX_VEC_UNI_NAME); fsCode->appendf("\t%s.rgb *= %s.a;\n", outputVar, outputVar); } void GrGLProgram::genEdgeCoverage(const GrGLContextInfo& gl, GrVertexLayout layout, CachedData* programData, GrStringBuilder* coverageVar, GrGLShaderBuilder* segments) const { if (layout & GrDrawTarget::kEdge_VertexLayoutBit) { const char *vsName, *fsName; segments->addVarying(kVec4f_GrSLType, "Edge", &vsName, &fsName); segments->fVSAttrs.push_back().set(kVec4f_GrSLType, GrGLShaderVar::kAttribute_TypeModifier, EDGE_ATTR_NAME); segments->fVSCode.appendf("\t%s = " EDGE_ATTR_NAME ";\n", vsName); switch (fProgramDesc.fVertexEdgeType) { case GrDrawState::kHairLine_EdgeType: segments->fFSCode.appendf("\tfloat edgeAlpha = abs(dot(vec3(gl_FragCoord.xy,1), %s.xyz));\n", fsName); segments->fFSCode.append("\tedgeAlpha = max(1.0 - edgeAlpha, 0.0);\n"); break; case GrDrawState::kQuad_EdgeType: segments->fFSCode.append("\tfloat edgeAlpha;\n"); // keep the derivative instructions outside the conditional segments->fFSCode.appendf("\tvec2 duvdx = dFdx(%s.xy);\n", fsName); segments->fFSCode.appendf("\tvec2 duvdy = dFdy(%s.xy);\n", fsName); segments->fFSCode.appendf("\tif (%s.z > 0.0 && %s.w > 0.0) {\n", fsName, fsName); // today we know z and w are in device space. We could use derivatives segments->fFSCode.appendf("\t\tedgeAlpha = min(min(%s.z, %s.w) + 0.5, 1.0);\n", fsName, fsName); segments->fFSCode.append ("\t} else {\n"); segments->fFSCode.appendf("\t\tvec2 gF = vec2(2.0*%s.x*duvdx.x - duvdx.y,\n" "\t\t 2.0*%s.x*duvdy.x - duvdy.y);\n", fsName, fsName); segments->fFSCode.appendf("\t\tedgeAlpha = (%s.x*%s.x - %s.y);\n", fsName, fsName, fsName); segments->fFSCode.append("\t\tedgeAlpha = clamp(0.5 - edgeAlpha / length(gF), 0.0, 1.0);\n" "\t}\n"); if (kES2_GrGLBinding == gl.binding()) { segments->fHeader.printf("#extension GL_OES_standard_derivatives: enable\n"); } break; case GrDrawState::kHairQuad_EdgeType: segments->fFSCode.appendf("\tvec2 duvdx = dFdx(%s.xy);\n", fsName); segments->fFSCode.appendf("\tvec2 duvdy = dFdy(%s.xy);\n", fsName); segments->fFSCode.appendf("\tvec2 gF = vec2(2.0*%s.x*duvdx.x - duvdx.y,\n" "\t 2.0*%s.x*duvdy.x - duvdy.y);\n", fsName, fsName); segments->fFSCode.appendf("\tfloat edgeAlpha = (%s.x*%s.x - %s.y);\n", fsName, fsName, fsName); segments->fFSCode.append("\tedgeAlpha = sqrt(edgeAlpha*edgeAlpha / dot(gF, gF));\n"); segments->fFSCode.append("\tedgeAlpha = max(1.0 - edgeAlpha, 0.0);\n"); if (kES2_GrGLBinding == gl.binding()) { segments->fHeader.printf("#extension GL_OES_standard_derivatives: enable\n"); } break; case GrDrawState::kCircle_EdgeType: segments->fFSCode.append("\tfloat edgeAlpha;\n"); segments->fFSCode.appendf("\tfloat d = distance(gl_FragCoord.xy, %s.xy);\n", fsName); segments->fFSCode.appendf("\tfloat outerAlpha = smoothstep(d - 0.5, d + 0.5, %s.z);\n", fsName); segments->fFSCode.appendf("\tfloat innerAlpha = %s.w == 0.0 ? 1.0 : smoothstep(%s.w - 0.5, %s.w + 0.5, d);\n", fsName, fsName, fsName); segments->fFSCode.append("\tedgeAlpha = outerAlpha * innerAlpha;\n"); break; default: GrCrash("Unknown Edge Type!"); break; } *coverageVar = "edgeAlpha"; } else { coverageVar->reset(); } } namespace { void genInputColor(GrGLProgram::ProgramDesc::ColorInput colorInput, GrGLProgram::CachedData* programData, GrGLShaderBuilder* segments, GrStringBuilder* inColor) { switch (colorInput) { case GrGLProgram::ProgramDesc::kAttribute_ColorInput: { segments->fVSAttrs.push_back().set(kVec4f_GrSLType, GrGLShaderVar::kAttribute_TypeModifier, COL_ATTR_NAME); const char *vsName, *fsName; segments->addVarying(kVec4f_GrSLType, "Color", &vsName, &fsName); segments->fVSCode.appendf("\t%s = " COL_ATTR_NAME ";\n", vsName); *inColor = fsName; } break; case GrGLProgram::ProgramDesc::kUniform_ColorInput: segments->addUniform(GrGLShaderBuilder::kFragment_VariableLifetime, kVec4f_GrSLType, COL_UNI_NAME); programData->fUniLocations.fColorUni = kUseUniform; *inColor = COL_UNI_NAME; break; case GrGLProgram::ProgramDesc::kTransBlack_ColorInput: GrAssert(!"needComputedColor should be false."); break; case GrGLProgram::ProgramDesc::kSolidWhite_ColorInput: break; default: GrCrash("Unknown color type."); break; } } void genAttributeCoverage(GrGLShaderBuilder* segments, GrStringBuilder* inOutCoverage) { segments->fVSAttrs.push_back().set(kVec4f_GrSLType, GrGLShaderVar::kAttribute_TypeModifier, COV_ATTR_NAME); const char *vsName, *fsName; segments->addVarying(kVec4f_GrSLType, "Coverage", &vsName, &fsName); segments->fVSCode.appendf("\t%s = " COV_ATTR_NAME ";\n", vsName); if (inOutCoverage->size()) { segments->fFSCode.appendf("\tvec4 attrCoverage = %s * %s;\n", fsName, inOutCoverage->c_str()); *inOutCoverage = "attrCoverage"; } else { *inOutCoverage = fsName; } } void genUniformCoverage(GrGLShaderBuilder* segments, GrGLProgram::CachedData* programData, GrStringBuilder* inOutCoverage) { segments->addUniform(GrGLShaderBuilder::kFragment_VariableLifetime, kVec4f_GrSLType, COV_UNI_NAME); programData->fUniLocations.fCoverageUni = kUseUniform; if (inOutCoverage->size()) { segments->fFSCode.appendf("\tvec4 uniCoverage = %s * %s;\n", COV_UNI_NAME, inOutCoverage->c_str()); *inOutCoverage = "uniCoverage"; } else { *inOutCoverage = COV_UNI_NAME; } } } void GrGLProgram::genGeometryShader(const GrGLContextInfo& gl, GrGLShaderBuilder* segments) const { #if GR_GL_EXPERIMENTAL_GS if (fProgramDesc.fExperimentalGS) { GrAssert(gl.glslGeneration() >= k150_GrGLSLGeneration); segments->fGSHeader.append("layout(triangles) in;\n" "layout(triangle_strip, max_vertices = 6) out;\n"); segments->fGSCode.append("void main() {\n" "\tfor (int i = 0; i < 3; ++i) {\n" "\t\tgl_Position = gl_in[i].gl_Position;\n"); if (this->fProgramDesc.fEmitsPointSize) { segments->fGSCode.append("\t\tgl_PointSize = 1.0;\n"); } GrAssert(segments->fGSInputs.count() == segments->fGSOutputs.count()); int count = segments->fGSInputs.count(); for (int i = 0; i < count; ++i) { segments->fGSCode.appendf("\t\t%s = %s[i];\n", segments->fGSOutputs[i].getName().c_str(), segments->fGSInputs[i].getName().c_str()); } segments->fGSCode.append("\t\tEmitVertex();\n" "\t}\n" "\tEndPrimitive();\n" "}\n"); } #endif } const char* GrGLProgram::adjustInColor(const GrStringBuilder& inColor) const { if (inColor.size()) { return inColor.c_str(); } else { if (ProgramDesc::kSolidWhite_ColorInput == fProgramDesc.fColorInput) { return all_ones_vec(4); } else { return all_zeros_vec(4); } } } // If this destructor is in the header file, we must include GrGLProgramStage // instead of just forward-declaring it. GrGLProgram::CachedData::~CachedData() { for (int i = 0; i < GrDrawState::kNumStages; ++i) { delete fCustomStage[i]; } } bool GrGLProgram::genProgram(const GrGLContextInfo& gl, GrCustomStage** customStages, GrGLProgram::CachedData* programData) const { GrGLShaderBuilder segments; const uint32_t& layout = fProgramDesc.fVertexLayout; programData->fUniLocations.reset(); #if GR_GL_EXPERIMENTAL_GS segments.fUsesGS = fProgramDesc.fExperimentalGS; #endif SkXfermode::Coeff colorCoeff, uniformCoeff; bool applyColorMatrix = SkToBool(fProgramDesc.fColorMatrixEnabled); // The rest of transfer mode color filters have not been implemented if (fProgramDesc.fColorFilterXfermode < SkXfermode::kCoeffModesCnt) { GR_DEBUGCODE(bool success =) SkXfermode::ModeAsCoeff(static_cast<SkXfermode::Mode> (fProgramDesc.fColorFilterXfermode), &uniformCoeff, &colorCoeff); GR_DEBUGASSERT(success); } else { colorCoeff = SkXfermode::kOne_Coeff; uniformCoeff = SkXfermode::kZero_Coeff; } // no need to do the color filter / matrix at all if coverage is 0. The // output color is scaled by the coverage. All the dual source outputs are // scaled by the coverage as well. if (ProgramDesc::kTransBlack_ColorInput == fProgramDesc.fCoverageInput) { colorCoeff = SkXfermode::kZero_Coeff; uniformCoeff = SkXfermode::kZero_Coeff; applyColorMatrix = false; } // If we know the final color is going to be all zeros then we can // simplify the color filter coeffecients. needComputedColor will then // come out false below. if (ProgramDesc::kTransBlack_ColorInput == fProgramDesc.fColorInput) { colorCoeff = SkXfermode::kZero_Coeff; if (SkXfermode::kDC_Coeff == uniformCoeff || SkXfermode::kDA_Coeff == uniformCoeff) { uniformCoeff = SkXfermode::kZero_Coeff; } else if (SkXfermode::kIDC_Coeff == uniformCoeff || SkXfermode::kIDA_Coeff == uniformCoeff) { uniformCoeff = SkXfermode::kOne_Coeff; } } bool needColorFilterUniform; bool needComputedColor; needBlendInputs(uniformCoeff, colorCoeff, &needColorFilterUniform, &needComputedColor); // the dual source output has no canonical var name, have to // declare an output, which is incompatible with gl_FragColor/gl_FragData. bool dualSourceOutputWritten = false; segments.fHeader.printf(GrGetGLSLVersionDecl(gl.binding(), gl.glslGeneration())); GrGLShaderVar colorOutput; bool isColorDeclared = GrGLSLSetupFSColorOuput(gl.glslGeneration(), declared_color_output_name(), &colorOutput); if (isColorDeclared) { segments.fFSOutputs.push_back(colorOutput); } segments.addUniform(GrGLShaderBuilder::kVertex_VariableLifetime, kMat33f_GrSLType, VIEW_MATRIX_NAME); programData->fUniLocations.fViewMatrixUni = kUseUniform; segments.fVSAttrs.push_back().set(kVec2f_GrSLType, GrGLShaderVar::kAttribute_TypeModifier, POS_ATTR_NAME); segments.fVSCode.append( "void main() {\n" "\tvec3 pos3 = " VIEW_MATRIX_NAME " * vec3("POS_ATTR_NAME", 1);\n" "\tgl_Position = vec4(pos3.xy, 0, pos3.z);\n"); // incoming color to current stage being processed. GrStringBuilder inColor; if (needComputedColor) { genInputColor((ProgramDesc::ColorInput) fProgramDesc.fColorInput, programData, &segments, &inColor); } // we output point size in the GS if present if (fProgramDesc.fEmitsPointSize && !segments.fUsesGS){ segments.fVSCode.append("\tgl_PointSize = 1.0;\n"); } segments.fFSCode.append("void main() {\n"); // add texture coordinates that are used to the list of vertex attr decls GrStringBuilder texCoordAttrs[GrDrawState::kMaxTexCoords]; for (int t = 0; t < GrDrawState::kMaxTexCoords; ++t) { if (GrDrawTarget::VertexUsesTexCoordIdx(t, layout)) { tex_attr_name(t, texCoordAttrs + t); segments.fVSAttrs.push_back().set(kVec2f_GrSLType, GrGLShaderVar::kAttribute_TypeModifier, texCoordAttrs[t].c_str()); } } /////////////////////////////////////////////////////////////////////////// // We need to convert generic effect representations to GL-specific // backends so they can be accesseed in genStageCode() and in subsequent, // uses of programData, but it's safest to do so below when we're *sure* // we need them. for (int s = 0; s < GrDrawState::kNumStages; ++s) { programData->fCustomStage[s] = NULL; } /////////////////////////////////////////////////////////////////////////// // compute the final color // if we have color stages string them together, feeding the output color // of each to the next and generating code for each stage. if (needComputedColor) { GrStringBuilder outColor; for (int s = 0; s < fProgramDesc.fFirstCoverageStage; ++s) { if (fProgramDesc.fStages[s].isEnabled()) { // create var to hold stage result outColor = "color"; outColor.appendS32(s); segments.fFSCode.appendf("\tvec4 %s;\n", outColor.c_str()); const char* inCoords; // figure out what our input coords are if (GrDrawTarget::StagePosAsTexCoordVertexLayoutBit(s) & layout) { inCoords = POS_ATTR_NAME; } else { int tcIdx = GrDrawTarget::VertexTexCoordsForStage(s, layout); // we better have input tex coordinates if stage is enabled. GrAssert(tcIdx >= 0); GrAssert(texCoordAttrs[tcIdx].size()); inCoords = texCoordAttrs[tcIdx].c_str(); } if (NULL != customStages[s]) { const GrProgramStageFactory& factory = customStages[s]->getFactory(); programData->fCustomStage[s] = factory.createGLInstance(*customStages[s]); } this->genStageCode(gl, s, fProgramDesc.fStages[s], inColor.size() ? inColor.c_str() : NULL, outColor.c_str(), inCoords, &segments, &programData->fUniLocations.fStages[s], programData->fCustomStage[s]); inColor = outColor; } } } // if have all ones or zeros for the "dst" input to the color filter then we // may be able to make additional optimizations. if (needColorFilterUniform && needComputedColor && !inColor.size()) { GrAssert(ProgramDesc::kSolidWhite_ColorInput == fProgramDesc.fColorInput); bool uniformCoeffIsZero = SkXfermode::kIDC_Coeff == uniformCoeff || SkXfermode::kIDA_Coeff == uniformCoeff; if (uniformCoeffIsZero) { uniformCoeff = SkXfermode::kZero_Coeff; bool bogus; needBlendInputs(SkXfermode::kZero_Coeff, colorCoeff, &needColorFilterUniform, &bogus); } } if (needColorFilterUniform) { segments.addUniform(GrGLShaderBuilder::kFragment_VariableLifetime, kVec4f_GrSLType, COL_FILTER_UNI_NAME); programData->fUniLocations.fColorFilterUni = kUseUniform; } bool wroteFragColorZero = false; if (SkXfermode::kZero_Coeff == uniformCoeff && SkXfermode::kZero_Coeff == colorCoeff && !applyColorMatrix) { segments.fFSCode.appendf("\t%s = %s;\n", colorOutput.getName().c_str(), all_zeros_vec(4)); wroteFragColorZero = true; } else if (SkXfermode::kDst_Mode != fProgramDesc.fColorFilterXfermode) { segments.fFSCode.append("\tvec4 filteredColor;\n"); const char* color = adjustInColor(inColor); addColorFilter(&segments.fFSCode, "filteredColor", uniformCoeff, colorCoeff, color); inColor = "filteredColor"; } if (applyColorMatrix) { segments.addUniform(GrGLShaderBuilder::kFragment_VariableLifetime, kMat44f_GrSLType, COL_MATRIX_UNI_NAME); segments.addUniform(GrGLShaderBuilder::kFragment_VariableLifetime, kVec4f_GrSLType, COL_MATRIX_VEC_UNI_NAME); programData->fUniLocations.fColorMatrixUni = kUseUniform; programData->fUniLocations.fColorMatrixVecUni = kUseUniform; segments.fFSCode.append("\tvec4 matrixedColor;\n"); const char* color = adjustInColor(inColor); addColorMatrix(&segments.fFSCode, "matrixedColor", color); inColor = "matrixedColor"; } /////////////////////////////////////////////////////////////////////////// // compute the partial coverage (coverage stages and edge aa) GrStringBuilder inCoverage; bool coverageIsZero = ProgramDesc::kTransBlack_ColorInput == fProgramDesc.fCoverageInput; // we don't need to compute coverage at all if we know the final shader // output will be zero and we don't have a dual src blend output. if (!wroteFragColorZero || ProgramDesc::kNone_DualSrcOutput != fProgramDesc.fDualSrcOutput) { if (!coverageIsZero) { this->genEdgeCoverage(gl, layout, programData, &inCoverage, &segments); switch (fProgramDesc.fCoverageInput) { case ProgramDesc::kSolidWhite_ColorInput: // empty string implies solid white break; case ProgramDesc::kAttribute_ColorInput: genAttributeCoverage(&segments, &inCoverage); break; case ProgramDesc::kUniform_ColorInput: genUniformCoverage(&segments, programData, &inCoverage); break; default: GrCrash("Unexpected input coverage."); } GrStringBuilder outCoverage; const int& startStage = fProgramDesc.fFirstCoverageStage; for (int s = startStage; s < GrDrawState::kNumStages; ++s) { if (fProgramDesc.fStages[s].isEnabled()) { // create var to hold stage output outCoverage = "coverage"; outCoverage.appendS32(s); segments.fFSCode.appendf("\tvec4 %s;\n", outCoverage.c_str()); const char* inCoords; // figure out what our input coords are if (GrDrawTarget::StagePosAsTexCoordVertexLayoutBit(s) & layout) { inCoords = POS_ATTR_NAME; } else { int tcIdx = GrDrawTarget::VertexTexCoordsForStage(s, layout); // we better have input tex coordinates if stage is // enabled. GrAssert(tcIdx >= 0); GrAssert(texCoordAttrs[tcIdx].size()); inCoords = texCoordAttrs[tcIdx].c_str(); } if (NULL != customStages[s]) { const GrProgramStageFactory& factory = customStages[s]->getFactory(); programData->fCustomStage[s] = factory.createGLInstance(*customStages[s]); } this->genStageCode(gl, s, fProgramDesc.fStages[s], inCoverage.size() ? inCoverage.c_str() : NULL, outCoverage.c_str(), inCoords, &segments, &programData->fUniLocations.fStages[s], programData->fCustomStage[s]); inCoverage = outCoverage; } } } if (ProgramDesc::kNone_DualSrcOutput != fProgramDesc.fDualSrcOutput) { segments.fFSOutputs.push_back().set(kVec4f_GrSLType, GrGLShaderVar::kOut_TypeModifier, dual_source_output_name()); bool outputIsZero = coverageIsZero; GrStringBuilder coeff; if (!outputIsZero && ProgramDesc::kCoverage_DualSrcOutput != fProgramDesc.fDualSrcOutput && !wroteFragColorZero) { if (!inColor.size()) { outputIsZero = true; } else { if (fProgramDesc.fDualSrcOutput == ProgramDesc::kCoverageISA_DualSrcOutput) { coeff.printf("(1 - %s.a)", inColor.c_str()); } else { coeff.printf("(vec4(1,1,1,1) - %s)", inColor.c_str()); } } } if (outputIsZero) { segments.fFSCode.appendf("\t%s = %s;\n", dual_source_output_name(), all_zeros_vec(4)); } else { modulate_helper(dual_source_output_name(), coeff.c_str(), inCoverage.c_str(), &segments.fFSCode); } dualSourceOutputWritten = true; } } /////////////////////////////////////////////////////////////////////////// // combine color and coverage as frag color if (!wroteFragColorZero) { if (coverageIsZero) { segments.fFSCode.appendf("\t%s = %s;\n", colorOutput.getName().c_str(), all_zeros_vec(4)); } else { modulate_helper(colorOutput.getName().c_str(), inColor.c_str(), inCoverage.c_str(), &segments.fFSCode); } if (ProgramDesc::kUnpremultiplied_RoundDown_OutputConfig == fProgramDesc.fOutputConfig) { segments.fFSCode.appendf("\t%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(floor(%s.rgb / %s.a * 255.0)/255.0, %s.a);\n", colorOutput.getName().c_str(), colorOutput.getName().c_str(), colorOutput.getName().c_str(), colorOutput.getName().c_str(), colorOutput.getName().c_str()); } else if (ProgramDesc::kUnpremultiplied_RoundUp_OutputConfig == fProgramDesc.fOutputConfig) { segments.fFSCode.appendf("\t%s = %s.a <= 0.0 ? vec4(0,0,0,0) : vec4(ceil(%s.rgb / %s.a * 255.0)/255.0, %s.a);\n", colorOutput.getName().c_str(), colorOutput.getName().c_str(), colorOutput.getName().c_str(), colorOutput.getName().c_str(), colorOutput.getName().c_str()); } } segments.fVSCode.append("}\n"); segments.fFSCode.append("}\n"); /////////////////////////////////////////////////////////////////////////// // insert GS #if GR_DEBUG this->genGeometryShader(gl, &segments); #endif /////////////////////////////////////////////////////////////////////////// // compile and setup attribs and unis if (!CompileShaders(gl, segments, programData)) { return false; } if (!this->bindOutputsAttribsAndLinkProgram(gl, texCoordAttrs, isColorDeclared, dualSourceOutputWritten, programData)) { return false; } this->getUniformLocationsAndInitCache(gl, programData); return true; } namespace { inline void expand_decls(const VarArray& vars, const GrGLContextInfo& gl, GrStringBuilder* string) { const int count = vars.count(); for (int i = 0; i < count; ++i) { vars[i].appendDecl(gl, string); } } inline void print_shader(int stringCnt, const char** strings, int* stringLengths) { for (int i = 0; i < stringCnt; ++i) { if (NULL == stringLengths || stringLengths[i] < 0) { GrPrintf(strings[i]); } else { GrPrintf("%.*s", stringLengths[i], strings[i]); } } } typedef SkTArray<const char*, true> StrArray; #define PREALLOC_STR_ARRAY(N) SkSTArray<(N), const char*, true> typedef SkTArray<int, true> LengthArray; #define PREALLOC_LENGTH_ARRAY(N) SkSTArray<(N), int, true> // these shouldn't relocate typedef GrTAllocator<GrStringBuilder> TempArray; #define PREALLOC_TEMP_ARRAY(N) GrSTAllocator<(N), GrStringBuilder> inline void append_string(const GrStringBuilder& str, StrArray* strings, LengthArray* lengths) { int length = (int) str.size(); if (length) { strings->push_back(str.c_str()); lengths->push_back(length); } GrAssert(strings->count() == lengths->count()); } inline void append_decls(const VarArray& vars, const GrGLContextInfo& gl, StrArray* strings, LengthArray* lengths, TempArray* temp) { expand_decls(vars, gl, &temp->push_back()); append_string(temp->back(), strings, lengths); } } bool GrGLProgram::CompileShaders(const GrGLContextInfo& gl, const GrGLShaderBuilder& segments, CachedData* programData) { enum { kPreAllocStringCnt = 8 }; PREALLOC_STR_ARRAY(kPreAllocStringCnt) strs; PREALLOC_LENGTH_ARRAY(kPreAllocStringCnt) lengths; PREALLOC_TEMP_ARRAY(kPreAllocStringCnt) temps; GrStringBuilder unis; GrStringBuilder inputs; GrStringBuilder outputs; append_string(segments.fHeader, &strs, &lengths); append_decls(segments.fVSUnis, gl, &strs, &lengths, &temps); append_decls(segments.fVSAttrs, gl, &strs, &lengths, &temps); append_decls(segments.fVSOutputs, gl, &strs, &lengths, &temps); append_string(segments.fVSCode, &strs, &lengths); #if PRINT_SHADERS print_shader(strs.count(), &strs[0], &lengths[0]); GrPrintf("\n"); #endif programData->fVShaderID = CompileShader(gl, GR_GL_VERTEX_SHADER, strs.count(), &strs[0], &lengths[0]); if (!programData->fVShaderID) { return false; } if (segments.fUsesGS) { strs.reset(); lengths.reset(); temps.reset(); append_string(segments.fHeader, &strs, &lengths); append_string(segments.fGSHeader, &strs, &lengths); append_decls(segments.fGSInputs, gl, &strs, &lengths, &temps); append_decls(segments.fGSOutputs, gl, &strs, &lengths, &temps); append_string(segments.fGSCode, &strs, &lengths); #if PRINT_SHADERS print_shader(strs.count(), &strs[0], &lengths[0]); GrPrintf("\n"); #endif programData->fGShaderID = CompileShader(gl, GR_GL_GEOMETRY_SHADER, strs.count(), &strs[0], &lengths[0]); } else { programData->fGShaderID = 0; } strs.reset(); lengths.reset(); temps.reset(); append_string(segments.fHeader, &strs, &lengths); GrStringBuilder precisionStr(GrGetGLSLShaderPrecisionDecl(gl.binding())); append_string(precisionStr, &strs, &lengths); append_decls(segments.fFSUnis, gl, &strs, &lengths, &temps); append_decls(segments.fFSInputs, gl, &strs, &lengths, &temps); // We shouldn't have declared outputs on 1.10 GrAssert(k110_GrGLSLGeneration != gl.glslGeneration() || segments.fFSOutputs.empty()); append_decls(segments.fFSOutputs, gl, &strs, &lengths, &temps); append_string(segments.fFSFunctions, &strs, &lengths); append_string(segments.fFSCode, &strs, &lengths); #if PRINT_SHADERS print_shader(strs.count(), &strs[0], &lengths[0]); GrPrintf("\n"); #endif programData->fFShaderID = CompileShader(gl, GR_GL_FRAGMENT_SHADER, strs.count(), &strs[0], &lengths[0]); if (!programData->fFShaderID) { return false; } return true; } #define GL_CALL(X) GR_GL_CALL(gl.interface(), X) #define GL_CALL_RET(R, X) GR_GL_CALL_RET(gl.interface(), R, X) GrGLuint GrGLProgram::CompileShader(const GrGLContextInfo& gl, GrGLenum type, int stringCnt, const char** strings, int* stringLengths) { SK_TRACE_EVENT1("GrGLProgram::CompileShader", "stringCount", SkStringPrintf("%i", stringCnt).c_str()); GrGLuint shader; GL_CALL_RET(shader, CreateShader(type)); if (0 == shader) { return 0; } GrGLint compiled = GR_GL_INIT_ZERO; GL_CALL(ShaderSource(shader, stringCnt, strings, stringLengths)); GL_CALL(CompileShader(shader)); GL_CALL(GetShaderiv(shader, GR_GL_COMPILE_STATUS, &compiled)); if (!compiled) { GrGLint infoLen = GR_GL_INIT_ZERO; GL_CALL(GetShaderiv(shader, GR_GL_INFO_LOG_LENGTH, &infoLen)); SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger if (infoLen > 0) { // retrieve length even though we don't need it to workaround // bug in chrome cmd buffer param validation. GrGLsizei length = GR_GL_INIT_ZERO; GL_CALL(GetShaderInfoLog(shader, infoLen+1, &length, (char*)log.get())); print_shader(stringCnt, strings, stringLengths); GrPrintf("\n%s", log.get()); } GrAssert(!"Shader compilation failed!"); GL_CALL(DeleteShader(shader)); return 0; } return shader; } bool GrGLProgram::bindOutputsAttribsAndLinkProgram( const GrGLContextInfo& gl, GrStringBuilder texCoordAttrNames[], bool bindColorOut, bool bindDualSrcOut, CachedData* programData) const { GL_CALL_RET(programData->fProgramID, CreateProgram()); if (!programData->fProgramID) { return false; } const GrGLint& progID = programData->fProgramID; GL_CALL(AttachShader(progID, programData->fVShaderID)); if (programData->fGShaderID) { GL_CALL(AttachShader(progID, programData->fGShaderID)); } GL_CALL(AttachShader(progID, programData->fFShaderID)); if (bindColorOut) { GL_CALL(BindFragDataLocation(programData->fProgramID, 0, declared_color_output_name())); } if (bindDualSrcOut) { GL_CALL(BindFragDataLocationIndexed(programData->fProgramID, 0, 1, dual_source_output_name())); } // Bind the attrib locations to same values for all shaders GL_CALL(BindAttribLocation(progID, PositionAttributeIdx(), POS_ATTR_NAME)); for (int t = 0; t < GrDrawState::kMaxTexCoords; ++t) { if (texCoordAttrNames[t].size()) { GL_CALL(BindAttribLocation(progID, TexCoordAttributeIdx(t), texCoordAttrNames[t].c_str())); } } GL_CALL(BindAttribLocation(progID, ColorAttributeIdx(), COL_ATTR_NAME)); GL_CALL(BindAttribLocation(progID, CoverageAttributeIdx(), COV_ATTR_NAME)); GL_CALL(BindAttribLocation(progID, EdgeAttributeIdx(), EDGE_ATTR_NAME)); GL_CALL(LinkProgram(progID)); GrGLint linked = GR_GL_INIT_ZERO; GL_CALL(GetProgramiv(progID, GR_GL_LINK_STATUS, &linked)); if (!linked) { GrGLint infoLen = GR_GL_INIT_ZERO; GL_CALL(GetProgramiv(progID, GR_GL_INFO_LOG_LENGTH, &infoLen)); SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger if (infoLen > 0) { // retrieve length even though we don't need it to workaround // bug in chrome cmd buffer param validation. GrGLsizei length = GR_GL_INIT_ZERO; GL_CALL(GetProgramInfoLog(progID, infoLen+1, &length, (char*)log.get())); GrPrintf((char*)log.get()); } GrAssert(!"Error linking program"); GL_CALL(DeleteProgram(progID)); programData->fProgramID = 0; return false; } return true; } void GrGLProgram::getUniformLocationsAndInitCache(const GrGLContextInfo& gl, CachedData* programData) const { const GrGLint& progID = programData->fProgramID; if (kUseUniform == programData->fUniLocations.fViewMatrixUni) { GL_CALL_RET(programData->fUniLocations.fViewMatrixUni, GetUniformLocation(progID, VIEW_MATRIX_NAME)); GrAssert(kUnusedUniform != programData->fUniLocations.fViewMatrixUni); } if (kUseUniform == programData->fUniLocations.fColorUni) { GL_CALL_RET(programData->fUniLocations.fColorUni, GetUniformLocation(progID, COL_UNI_NAME)); GrAssert(kUnusedUniform != programData->fUniLocations.fColorUni); } if (kUseUniform == programData->fUniLocations.fColorFilterUni) { GL_CALL_RET(programData->fUniLocations.fColorFilterUni, GetUniformLocation(progID, COL_FILTER_UNI_NAME)); GrAssert(kUnusedUniform != programData->fUniLocations.fColorFilterUni); } if (kUseUniform == programData->fUniLocations.fColorMatrixUni) { GL_CALL_RET(programData->fUniLocations.fColorMatrixUni, GetUniformLocation(progID, COL_MATRIX_UNI_NAME)); } if (kUseUniform == programData->fUniLocations.fColorMatrixVecUni) { GL_CALL_RET(programData->fUniLocations.fColorMatrixVecUni, GetUniformLocation(progID, COL_MATRIX_VEC_UNI_NAME)); } if (kUseUniform == programData->fUniLocations.fCoverageUni) { GL_CALL_RET(programData->fUniLocations.fCoverageUni, GetUniformLocation(progID, COV_UNI_NAME)); GrAssert(kUnusedUniform != programData->fUniLocations.fCoverageUni); } for (int s = 0; s < GrDrawState::kNumStages; ++s) { StageUniLocations& locations = programData->fUniLocations.fStages[s]; if (fProgramDesc.fStages[s].isEnabled()) { if (kUseUniform == locations.fTextureMatrixUni) { GrStringBuilder texMName; tex_matrix_name(s, &texMName); GL_CALL_RET(locations.fTextureMatrixUni, GetUniformLocation(progID, texMName.c_str())); GrAssert(kUnusedUniform != locations.fTextureMatrixUni); } if (kUseUniform == locations.fSamplerUni) { GrStringBuilder samplerName; sampler_name(s, &samplerName); GL_CALL_RET(locations.fSamplerUni, GetUniformLocation(progID,samplerName.c_str())); GrAssert(kUnusedUniform != locations.fSamplerUni); } if (kUseUniform == locations.fTexDomUni) { GrStringBuilder texDomName; tex_domain_name(s, &texDomName); GL_CALL_RET(locations.fTexDomUni, GetUniformLocation(progID, texDomName.c_str())); GrAssert(kUnusedUniform != locations.fTexDomUni); } if (NULL != programData->fCustomStage[s]) { programData->fCustomStage[s]-> initUniforms(gl.interface(), progID); } } } GL_CALL(UseProgram(progID)); // init sampler unis and set bogus values for state tracking for (int s = 0; s < GrDrawState::kNumStages; ++s) { if (kUnusedUniform != programData->fUniLocations.fStages[s].fSamplerUni) { GL_CALL(Uniform1i(programData->fUniLocations.fStages[s].fSamplerUni, s)); } programData->fTextureMatrices[s] = GrMatrix::InvalidMatrix(); programData->fTextureDomain[s].setEmpty(); // this is arbitrary, just initialize to something programData->fTextureOrientation[s] = GrGLTexture::kBottomUp_Orientation; // Must not reset fStageOverride[] here. } programData->fViewMatrix = GrMatrix::InvalidMatrix(); programData->fViewportSize.set(-1, -1); programData->fColor = GrColor_ILLEGAL; programData->fColorFilterColor = GrColor_ILLEGAL; } //============================================================================ // Stage code generation //============================================================================ void GrGLProgram::genStageCode(const GrGLContextInfo& gl, int stageNum, const GrGLProgram::StageDesc& desc, const char* fsInColor, // NULL means no incoming color const char* fsOutColor, const char* vsInCoord, GrGLShaderBuilder* segments, StageUniLocations* locations, GrGLProgramStage* customStage) const { GrAssert(stageNum >= 0 && stageNum <= GrDrawState::kNumStages); GrAssert((desc.fInConfigFlags & StageDesc::kInConfigBitMask) == desc.fInConfigFlags); /// Vertex Shader Stuff // decide whether we need a matrix to transform texture coords // and whether the varying needs a perspective coord. const char* matName = NULL; if (desc.fOptFlags & StageDesc::kIdentityMatrix_OptFlagBit) { segments->fVaryingDims = segments->fCoordDims; } else { GrStringBuilder texMatName; tex_matrix_name(stageNum, &texMatName); const GrGLShaderVar* mat = &segments->addUniform( GrGLShaderBuilder::kVertex_VariableLifetime, kMat33f_GrSLType, texMatName.c_str()); // Can't use texMatName.c_str() because it's on the stack! matName = mat->getName().c_str(); locations->fTextureMatrixUni = kUseUniform; if (desc.fOptFlags & StageDesc::kNoPerspective_OptFlagBit) { segments->fVaryingDims = segments->fCoordDims; } else { segments->fVaryingDims = segments->fCoordDims + 1; } } GrAssert(segments->fVaryingDims > 0); // Must setup variables after computing segments->fVaryingDims if (NULL != customStage) { customStage->setupVariables(segments, stageNum); } GrStringBuilder samplerName; sampler_name(stageNum, &samplerName); // const GrGLShaderVar* sampler = & segments->addUniform(GrGLShaderBuilder::kFragment_VariableLifetime, kSampler2D_GrSLType, samplerName.c_str()); locations->fSamplerUni = kUseUniform; const char *varyingVSName, *varyingFSName; segments->addVarying(GrSLFloatVectorType(segments->fVaryingDims), "Stage", stageNum, &varyingVSName, &varyingFSName); if (!matName) { GrAssert(segments->fVaryingDims == segments->fCoordDims); segments->fVSCode.appendf("\t%s = %s;\n", varyingVSName, vsInCoord); } else { // varying = texMatrix * texCoord segments->fVSCode.appendf("\t%s = (%s * vec3(%s, 1))%s;\n", varyingVSName, matName, vsInCoord, vector_all_coords(segments->fVaryingDims)); } // GrGLShaderVar* kernel = NULL; // const char* imageIncrementName = NULL; if (NULL != customStage) { segments->fVSCode.appendf("\t{ // stage %d %s\n", stageNum, customStage->name()); customStage->emitVS(segments, varyingVSName); segments->fVSCode.appendf("\t}\n"); } /// Fragment Shader Stuff segments->fSampleCoords = varyingFSName; GrGLShaderBuilder::SamplerMode sampleMode = GrGLShaderBuilder::kExplicitDivide_SamplerMode; if (desc.fOptFlags & (StageDesc::kIdentityMatrix_OptFlagBit | StageDesc::kNoPerspective_OptFlagBit)) { sampleMode = GrGLShaderBuilder::kDefault_SamplerMode; } else if (NULL == customStage) { sampleMode = GrGLShaderBuilder::kProj_SamplerMode; } segments->setupTextureAccess(sampleMode, stageNum); segments->computeSwizzle(desc.fInConfigFlags); segments->computeModulate(fsInColor); static const uint32_t kMulByAlphaMask = (StageDesc::kMulRGBByAlpha_RoundUp_InConfigFlag | StageDesc::kMulRGBByAlpha_RoundDown_InConfigFlag); if (desc.fOptFlags & StageDesc::kCustomTextureDomain_OptFlagBit) { GrStringBuilder texDomainName; tex_domain_name(stageNum, &texDomainName); // const GrGLShaderVar* texDomain = & segments->addUniform( GrGLShaderBuilder::kFragment_VariableLifetime, kVec4f_GrSLType, texDomainName.c_str()); GrStringBuilder coordVar("clampCoord"); segments->fFSCode.appendf("\t%s %s = clamp(%s, %s.xy, %s.zw);\n", float_vector_type_str(segments->fCoordDims), coordVar.c_str(), segments->fSampleCoords.c_str(), texDomainName.c_str(), texDomainName.c_str()); segments->fSampleCoords = coordVar; locations->fTexDomUni = kUseUniform; } // NOTE: GrGLProgramStages are now responsible for fetching if (NULL == customStage) { if (desc.fInConfigFlags & kMulByAlphaMask) { // only one of the mul by alpha flags should be set GrAssert(GrIsPow2(kMulByAlphaMask & desc.fInConfigFlags)); GrAssert(!(desc.fInConfigFlags & StageDesc::kSmearAlpha_InConfigFlag)); GrAssert(!(desc.fInConfigFlags & StageDesc::kSmearRed_InConfigFlag)); segments->fFSCode.appendf("\t%s = %s(%s, %s)%s;\n", fsOutColor, segments->fTexFunc.c_str(), samplerName.c_str(), segments->fSampleCoords.c_str(), segments->fSwizzle.c_str()); if (desc.fInConfigFlags & StageDesc::kMulRGBByAlpha_RoundUp_InConfigFlag) { segments->fFSCode.appendf("\t%s = vec4(ceil(%s.rgb*%s.a*255.0)/255.0,%s.a)%s;\n", fsOutColor, fsOutColor, fsOutColor, fsOutColor, segments->fModulate.c_str()); } else { segments->fFSCode.appendf("\t%s = vec4(floor(%s.rgb*%s.a*255.0)/255.0,%s.a)%s;\n", fsOutColor, fsOutColor, fsOutColor, fsOutColor, segments->fModulate.c_str()); } } else { segments->emitDefaultFetch(fsOutColor, samplerName.c_str()); } } if (NULL != customStage) { // Enclose custom code in a block to avoid namespace conflicts segments->fFSCode.appendf("\t{ // stage %d %s \n", stageNum, customStage->name()); customStage->emitFS(segments, fsOutColor, fsInColor, samplerName.c_str()); segments->fFSCode.appendf("\t}\n"); } }
[ "gloam@163.com" ]
gloam@163.com
e11226157d525ebf80b614e85c5a2a00ebb174b5
761c1ae19594e49d7047d059b25640c3e558f3d5
/HighFrequency/288. Unique Word Abbreviation.cpp
9ab0e07f35004737ed8ce746c83d0172905831c1
[]
no_license
SunNEET/LeetCode
a09772c4f3c23788afebceb4f6c2150d3c127695
96b08c45f5241579aaf27625510570d718965ec2
refs/heads/master
2020-03-12T15:43:07.019708
2019-06-25T03:53:56
2019-06-25T03:53:56
130,697,627
0
0
null
null
null
null
UTF-8
C++
false
false
1,125
cpp
class ValidWordAbbr { // 題目解讀有坑, 簡單的說, 每個字典裡的字都一律縮寫成只保留頭尾, 中間變數字 // 規則解讀 // (1)isUnique("apple"): 假如apple沒在字典裡出現過, a3e也沒出現過 -> unique // (2)isUnique("deer"): 假如deer在字典出現過n次, 而且只有他會縮寫成d2r -> unique private: unordered_map<string,int> dict_cnt; unordered_map<string,int> abbr_cnt; public: ValidWordAbbr(vector<string> dictionary) { for(int i=0;i<(int)dictionary.size();i++) { dict_cnt[dictionary[i]]++; abbr_cnt[makeAbbr(dictionary[i])]++; } } string makeAbbr(string s) { string res=""; res += s[0] + to_string((int)s.length()-2) + s[(int)s.length()-1]; return res; } bool isUnique(string word) { if(dict_cnt[word]!=abbr_cnt[makeAbbr(word)]) return false; return true; } }; /** * Your ValidWordAbbr object will be instantiated and called as such: * ValidWordAbbr obj = new ValidWordAbbr(dictionary); * bool param_1 = obj.isUnique(word); */
[ "sunnyinvadeher@gmail.com" ]
sunnyinvadeher@gmail.com
418b6c3245f4254019c741db7db4745e9c8d5ef9
66511b371329a068a3e52452c47a161e4d650109
/fgame/flamethrower.h
ba778c604d5989fede10f3b72ec3a5a2dabcc3f8
[]
no_license
HaZardModding/fakk2_coop_mod
8f619f288e09dbce6a1dc8adfe25759bdf682b8c
3ab0c8ce011c93ff861924f02284f7948c7ce8b8
refs/heads/master
2022-11-21T02:35:04.523416
2020-07-22T06:40:16
2020-07-22T06:40:16
281,033,547
2
0
null
null
null
null
UTF-8
C++
false
false
1,580
h
//----------------------------------------------------------------------------- // // $Logfile:: /fakk2_code/fakk2_new/fgame/flamethrower.h $ // $Revision:: 6 $ // $Author:: Markd $ // $Date:: 6/14/00 3:50p $ // // Copyright (C) 1998 by Ritual Entertainment, Inc. // All rights reserved. // // This source may not be distributed and/or modified without // expressly written permission by Ritual Entertainment, Inc. // // $Log:: /fakk2_code/fakk2_new/fgame/flamethrower.h $ // // 6 6/14/00 3:50p Markd // Cleaned up more Intel Compiler warnings // // 5 5/26/00 7:44p Markd // 2nd phase save games // // 4 5/24/00 3:14p Markd // first phase of save/load games // // 3 5/05/00 5:18p Aldie // comment // // 2 5/05/00 5:17p Aldie // Flamethrower // // DESCRIPTION: // Flamethrower weapon #ifndef __FLAMETHROWER_H__ #define __FLAMETHROWER_H__ #include "weapon.h" #include "weaputils.h" class Flamethrower : public Weapon { private: Animate *m_gas; public: CLASS_PROTOTYPE( Flamethrower ); Flamethrower(); virtual void Shoot( Event *ev ); virtual void Archive( Archiver &arc ); }; inline void Flamethrower::Archive ( Archiver &arc ) { Weapon::Archive( arc ); arc.ArchiveObjectPointer( ( Class ** )&m_gas ); } #endif // __FLAMETHROWER_H__
[ "chrissstrahl@yahoo.de" ]
chrissstrahl@yahoo.de
19ae199086b2f10c4eae1bc647fe99ab519f8b5e
a815edcd3c7dcbb79d7fc20801c0170f3408b1d6
/chrome/browser/chromeos/child_accounts/screen_time_controller.cc
c48859a58e00ed7a6bc7f6d1ebc39d2943f97419
[ "BSD-3-Clause" ]
permissive
oguzzkilic/chromium
06be90df9f2e7f218bff6eee94235b6e684e2b40
1de71b638f99c15a3f97ec7b25b0c6dc920fbee0
refs/heads/master
2023-03-04T00:01:27.864257
2018-07-17T10:33:19
2018-07-17T10:33:19
141,275,697
1
0
null
2018-07-17T10:48:53
2018-07-17T10:48:52
null
UTF-8
C++
false
false
18,193
cc
// Copyright 2018 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/chromeos/child_accounts/screen_time_controller.h" #include "ash/public/cpp/vector_icons/vector_icons.h" #include "base/optional.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/ash/login_screen_client.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/session_manager/core/session_manager.h" #include "content/public/browser/browser_context.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/time_format.h" #include "ui/message_center/public/cpp/notification.h" namespace chromeos { namespace { constexpr base::TimeDelta kWarningNotificationTimeout = base::TimeDelta::FromMinutes(5); constexpr base::TimeDelta kExitNotificationTimeout = base::TimeDelta::FromMinutes(1); constexpr base::TimeDelta kScreenTimeUsageUpdateFrequency = base::TimeDelta::FromMinutes(1); // The notification id. All the time limit notifications share the same id so // that a subsequent notification can replace the previous one. constexpr char kTimeLimitNotificationId[] = "time-limit-notification"; // The notifier id representing the app. constexpr char kTimeLimitNotifierId[] = "family-link"; // Dictionary keys for prefs::kScreenTimeLastState. constexpr char kScreenStateLocked[] = "locked"; constexpr char kScreenStateCurrentPolicyType[] = "active_policy"; constexpr char kScreenStateTimeUsageLimitEnabled[] = "time_usage_limit_enabled"; constexpr char kScreenStateRemainingUsage[] = "remaining_usage"; constexpr char kScreenStateUsageLimitStarted[] = "usage_limit_started"; constexpr char kScreenStateNextStateChangeTime[] = "next_state_change_time"; constexpr char kScreenStateNextPolicyType[] = "next_active_policy"; constexpr char kScreenStateNextUnlockTime[] = "next_unlock_time"; constexpr char kScreenStateLastStateChanged[] = "last_state_changed"; } // namespace // static void ScreenTimeController::RegisterProfilePrefs(PrefRegistrySimple* registry) { registry->RegisterTimePref(prefs::kCurrentScreenStartTime, base::Time()); registry->RegisterTimePref(prefs::kFirstScreenStartTime, base::Time()); registry->RegisterIntegerPref(prefs::kScreenTimeMinutesUsed, 0); registry->RegisterDictionaryPref(prefs::kUsageTimeLimit); registry->RegisterDictionaryPref(prefs::kScreenTimeLastState); } ScreenTimeController::ScreenTimeController(content::BrowserContext* context) : context_(context), pref_service_(Profile::FromBrowserContext(context)->GetPrefs()) { session_manager::SessionManager::Get()->AddObserver(this); pref_change_registrar_.Init(pref_service_); pref_change_registrar_.Add( prefs::kUsageTimeLimit, base::BindRepeating(&ScreenTimeController::OnPolicyChanged, base::Unretained(this))); } ScreenTimeController::~ScreenTimeController() { session_manager::SessionManager::Get()->RemoveObserver(this); SaveScreenTimeProgressBeforeExit(); } base::TimeDelta ScreenTimeController::GetScreenTimeDuration() const { base::TimeDelta previous_duration = base::TimeDelta::FromMinutes( pref_service_->GetInteger(prefs::kScreenTimeMinutesUsed)); if (current_screen_start_time_.is_null()) return previous_duration; base::TimeDelta current_screen_duration = base::Time::Now() - current_screen_start_time_; return current_screen_duration + previous_duration; } void ScreenTimeController::CheckTimeLimit() { // Stop any currently running timer. ResetTimers(); base::Time now = base::Time::Now(); base::Optional<usage_time_limit::State> last_state = GetLastStateFromPref(); // Used time should be 0 when time usage limit is disabled. base::TimeDelta used_time = base::TimeDelta::FromMinutes(0); if (last_state && last_state->is_time_usage_limit_enabled) used_time = GetScreenTimeDuration(); const base::DictionaryValue* time_limit = pref_service_->GetDictionary(prefs::kUsageTimeLimit); usage_time_limit::State state = usage_time_limit::GetState(time_limit->CreateDeepCopy(), used_time, first_screen_start_time_, now, last_state); SaveCurrentStateToPref(state); // Show/hide time limits message based on the policy enforcement. UpdateTimeLimitsMessage( state.is_locked, state.is_locked ? state.next_unlock_time : base::Time()); if (state.is_locked) { DCHECK(!state.next_unlock_time.is_null()); if (!session_manager::SessionManager::Get()->IsScreenLocked()) ForceScreenLockByPolicy(state.next_unlock_time); } else { base::Optional<TimeLimitNotificationType> notification_type; switch (state.next_state_active_policy) { case usage_time_limit::ActivePolicies::kFixedLimit: notification_type = kBedTime; break; case usage_time_limit::ActivePolicies::kUsageLimit: notification_type = kScreenTime; break; case usage_time_limit::ActivePolicies::kNoActivePolicy: case usage_time_limit::ActivePolicies::kOverride: break; default: NOTREACHED(); } if (notification_type.has_value()) { // Schedule notification based on the remaining screen time until lock. const base::TimeDelta remaining_time = state.next_state_change_time - now; if (remaining_time >= kWarningNotificationTimeout) { warning_notification_timer_.Start( FROM_HERE, remaining_time - kWarningNotificationTimeout, base::BindRepeating( &ScreenTimeController::ShowNotification, base::Unretained(this), notification_type.value(), kWarningNotificationTimeout)); } if (remaining_time >= kExitNotificationTimeout) { exit_notification_timer_.Start( FROM_HERE, remaining_time - kExitNotificationTimeout, base::BindRepeating( &ScreenTimeController::ShowNotification, base::Unretained(this), notification_type.value(), kExitNotificationTimeout)); } } // The screen limit should start counting only when the time usage limit is // set, ignoring the amount of time that the device was used before. if (state.is_time_usage_limit_enabled && (!last_state || !last_state->is_time_usage_limit_enabled)) { RefreshScreenLimit(); } } if (!state.next_state_change_time.is_null()) { next_state_timer_.Start( FROM_HERE, state.next_state_change_time - base::Time::Now(), base::BindRepeating(&ScreenTimeController::CheckTimeLimit, base::Unretained(this))); } // Schedule timer to refresh the screen time usage. base::Time reset_time = usage_time_limit::GetExpectedResetTime(time_limit->CreateDeepCopy(), now); if (reset_time <= now) { RefreshScreenLimit(); } else { reset_screen_time_timer_.Start( FROM_HERE, reset_time - now, base::BindRepeating(&ScreenTimeController::RefreshScreenLimit, base::Unretained(this))); } } void ScreenTimeController::ForceScreenLockByPolicy( base::Time next_unlock_time) { DCHECK(!session_manager::SessionManager::Get()->IsScreenLocked()); chromeos::DBusThreadManager::Get() ->GetSessionManagerClient() ->RequestLockScreen(); // Update the time limits message when the lock screen UI is ready. next_unlock_time_ = next_unlock_time; } void ScreenTimeController::UpdateTimeLimitsMessage( bool visible, base::Time next_unlock_time) { DCHECK(visible || next_unlock_time.is_null()); if (!session_manager::SessionManager::Get()->IsScreenLocked()) return; AccountId account_id = chromeos::ProfileHelper::Get() ->GetUserByProfile(Profile::FromBrowserContext(context_)) ->GetAccountId(); LoginScreenClient::Get()->login_screen()->SetAuthEnabledForUser( account_id, !visible, visible ? next_unlock_time : base::Optional<base::Time>()); } void ScreenTimeController::ShowNotification( ScreenTimeController::TimeLimitNotificationType type, const base::TimeDelta& time_remaining) { const base::string16 title = l10n_util::GetStringUTF16( type == kScreenTime ? IDS_SCREEN_TIME_NOTIFICATION_TITLE : IDS_BED_TIME_NOTIFICATION_TITLE); std::unique_ptr<message_center::Notification> notification = message_center::Notification::CreateSystemNotification( message_center::NOTIFICATION_TYPE_SIMPLE, kTimeLimitNotificationId, title, ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_DURATION, ui::TimeFormat::LENGTH_LONG, time_remaining), gfx::Image(), l10n_util::GetStringUTF16(IDS_TIME_LIMIT_NOTIFICATION_DISPLAY_SOURCE), GURL(), message_center::NotifierId( message_center::NotifierId::SYSTEM_COMPONENT, kTimeLimitNotifierId), message_center::RichNotificationData(), new message_center::NotificationDelegate(), ash::kNotificationSupervisedUserIcon, message_center::SystemNotificationWarningLevel::NORMAL); NotificationDisplayService::GetForProfile( Profile::FromBrowserContext(context_)) ->Display(NotificationHandler::Type::TRANSIENT, *notification); } void ScreenTimeController::RefreshScreenLimit() { base::Time now = base::Time::Now(); pref_service_->SetTime(prefs::kFirstScreenStartTime, now); pref_service_->SetTime(prefs::kCurrentScreenStartTime, now); pref_service_->SetInteger(prefs::kScreenTimeMinutesUsed, 0); pref_service_->CommitPendingWrite(); first_screen_start_time_ = now; current_screen_start_time_ = now; } void ScreenTimeController::OnPolicyChanged() { CheckTimeLimit(); } void ScreenTimeController::ResetTimers() { next_state_timer_.Stop(); warning_notification_timer_.Stop(); exit_notification_timer_.Stop(); save_screen_time_timer_.Stop(); reset_screen_time_timer_.Stop(); } void ScreenTimeController::SaveScreenTimeProgressBeforeExit() { pref_service_->SetInteger(prefs::kScreenTimeMinutesUsed, GetScreenTimeDuration().InMinutes()); pref_service_->ClearPref(prefs::kCurrentScreenStartTime); pref_service_->CommitPendingWrite(); current_screen_start_time_ = base::Time(); ResetTimers(); } void ScreenTimeController::SaveScreenTimeProgressPeriodically() { pref_service_->SetInteger(prefs::kScreenTimeMinutesUsed, GetScreenTimeDuration().InMinutes()); current_screen_start_time_ = base::Time::Now(); pref_service_->SetTime(prefs::kCurrentScreenStartTime, current_screen_start_time_); pref_service_->CommitPendingWrite(); } void ScreenTimeController::SaveCurrentStateToPref( const usage_time_limit::State& state) { auto state_dict = std::make_unique<base::Value>(base::Value::Type::DICTIONARY); state_dict->SetKey(kScreenStateLocked, base::Value(state.is_locked)); state_dict->SetKey(kScreenStateCurrentPolicyType, base::Value(static_cast<int>(state.active_policy))); state_dict->SetKey(kScreenStateTimeUsageLimitEnabled, base::Value(state.is_time_usage_limit_enabled)); state_dict->SetKey(kScreenStateRemainingUsage, base::Value(state.remaining_usage.InMinutes())); state_dict->SetKey(kScreenStateUsageLimitStarted, base::Value(state.time_usage_limit_started.ToDoubleT())); state_dict->SetKey(kScreenStateNextStateChangeTime, base::Value(state.next_state_change_time.ToDoubleT())); state_dict->SetKey( kScreenStateNextPolicyType, base::Value(static_cast<int>(state.next_state_active_policy))); state_dict->SetKey(kScreenStateNextUnlockTime, base::Value(state.next_unlock_time.ToDoubleT())); state_dict->SetKey(kScreenStateLastStateChanged, base::Value(state.last_state_changed.ToDoubleT())); pref_service_->Set(prefs::kScreenTimeLastState, *state_dict); pref_service_->CommitPendingWrite(); } base::Optional<usage_time_limit::State> ScreenTimeController::GetLastStateFromPref() { const base::DictionaryValue* last_state = pref_service_->GetDictionary(prefs::kScreenTimeLastState); usage_time_limit::State result; if (last_state->empty()) return base::nullopt; // Verify is_locked from the pref is a boolean value. const base::Value* is_locked = last_state->FindKey(kScreenStateLocked); if (!is_locked || !is_locked->is_bool()) return base::nullopt; result.is_locked = is_locked->GetBool(); // Verify active policy type is a value of usage_time_limit::ActivePolicies. const base::Value* active_policy = last_state->FindKey(kScreenStateCurrentPolicyType); // TODO(crbug.com/823536): Add kCount in usage_time_limit::ActivePolicies // instead of checking kUsageLimit here. if (!active_policy || !active_policy->is_int() || active_policy->GetInt() < 0 || active_policy->GetInt() > static_cast<int>(usage_time_limit::ActivePolicies::kUsageLimit)) { return base::nullopt; } result.active_policy = static_cast<usage_time_limit::ActivePolicies>(active_policy->GetInt()); // Verify time_usage_limit_enabled from the pref is a boolean value. const base::Value* time_usage_limit_enabled = last_state->FindKey(kScreenStateTimeUsageLimitEnabled); if (!time_usage_limit_enabled || !time_usage_limit_enabled->is_bool()) return base::nullopt; result.is_time_usage_limit_enabled = time_usage_limit_enabled->GetBool(); // Verify remaining_usage from the pref is a int value. const base::Value* remaining_usage = last_state->FindKey(kScreenStateRemainingUsage); if (!remaining_usage || !remaining_usage->is_int()) return base::nullopt; result.remaining_usage = base::TimeDelta::FromMinutes(remaining_usage->GetInt()); // Verify time_usage_limit_started from the pref is a double value. const base::Value* time_usage_limit_started = last_state->FindKey(kScreenStateUsageLimitStarted); if (!time_usage_limit_started || !time_usage_limit_started->is_double()) return base::nullopt; result.time_usage_limit_started = base::Time::FromDoubleT(time_usage_limit_started->GetDouble()); // Verify next_state_change_time from the pref is a double value. const base::Value* next_state_change_time = last_state->FindKey(kScreenStateNextStateChangeTime); if (!next_state_change_time || !next_state_change_time->is_double()) return base::nullopt; result.next_state_change_time = base::Time::FromDoubleT(next_state_change_time->GetDouble()); // Verify next policy type is a value of usage_time_limit::ActivePolicies. const base::Value* next_active_policy = last_state->FindKey(kScreenStateNextPolicyType); if (!next_active_policy || !next_active_policy->is_int() || next_active_policy->GetInt() < 0 || next_active_policy->GetInt() > static_cast<int>(usage_time_limit::ActivePolicies::kUsageLimit)) { return base::nullopt; } result.next_state_active_policy = static_cast<usage_time_limit::ActivePolicies>( next_active_policy->GetInt()); // Verify next_unlock_time from the pref is a double value. const base::Value* next_unlock_time = last_state->FindKey(kScreenStateNextUnlockTime); if (!next_unlock_time || !next_unlock_time->is_double()) return base::nullopt; result.next_unlock_time = base::Time::FromDoubleT(next_unlock_time->GetDouble()); // Verify last_state_changed from the pref is a double value. const base::Value* last_state_changed = last_state->FindKey(kScreenStateLastStateChanged); if (!last_state_changed || !last_state_changed->is_double()) return base::nullopt; result.last_state_changed = base::Time::FromDoubleT(last_state_changed->GetDouble()); return result; } void ScreenTimeController::OnSessionStateChanged() { session_manager::SessionState session_state = session_manager::SessionManager::Get()->session_state(); if (session_state == session_manager::SessionState::LOCKED) { if (next_unlock_time_) { UpdateTimeLimitsMessage(true /*visible*/, next_unlock_time_.value()); next_unlock_time_.reset(); } SaveScreenTimeProgressBeforeExit(); } else if (session_state == session_manager::SessionState::ACTIVE) { base::Time now = base::Time::Now(); const base::Time first_screen_start_time = pref_service_->GetTime(prefs::kFirstScreenStartTime); if (first_screen_start_time.is_null()) { pref_service_->SetTime(prefs::kFirstScreenStartTime, now); first_screen_start_time_ = now; } else { first_screen_start_time_ = first_screen_start_time; } const base::Time current_screen_start_time = pref_service_->GetTime(prefs::kCurrentScreenStartTime); if (!current_screen_start_time.is_null() && current_screen_start_time < now && (now - current_screen_start_time) < 2 * kScreenTimeUsageUpdateFrequency) { current_screen_start_time_ = current_screen_start_time; } else { // If kCurrentScreenStartTime is not set or it's been too long since the // last update, set the time to now. current_screen_start_time_ = now; } pref_service_->SetTime(prefs::kCurrentScreenStartTime, current_screen_start_time_); pref_service_->CommitPendingWrite(); CheckTimeLimit(); save_screen_time_timer_.Start( FROM_HERE, kScreenTimeUsageUpdateFrequency, base::BindRepeating( &ScreenTimeController::SaveScreenTimeProgressPeriodically, base::Unretained(this))); } } } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
fc7f8dfe1e4db7486ec6b0407e5f57ebf33327fb
792f2ee67210556f224daf88ef0b9785becadc9b
/atcoder/Other/chokudai_S001_k.cpp
ccf43a9acc942654b49aad21823c6dd3beb28bc0
[]
no_license
firiexp/contest_log
e5b345286e7d69ebf2a599d4a81bdb19243ca18d
6474a7127d3a2fed768ebb62031d5ff30eeeef86
refs/heads/master
2021-07-20T01:16:47.869936
2020-04-30T03:27:51
2020-04-30T03:27:51
150,196,219
0
0
null
null
null
null
UTF-8
C++
false
false
3,457
cpp
#include <iostream> #include <algorithm> #include <iomanip> #include <map> #include <set> #include <queue> #include <stack> #include <numeric> #include <bitset> #include <cmath> static const int MOD = 1000000007; using ll = long long; using u32 = unsigned; using u64 = unsigned long long; using namespace std; template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208; template<u32 M = 1000000007> struct modint{ u32 val; modint(): val(0){} template<typename T> modint(T t){t %= (T)M; if(t < 0) t += (T)M; val = t;} modint pow(ll k) const { modint res(1), x(val); while(k){ if(k&1) res *= x; x *= x; k >>= 1; } return res; } template<typename T> modint& operator=(T t){t %= (T)M; if(t < 0) t += (T)M; val = t; return *this;} modint inv() const {return pow(M-2);} modint& operator+=(modint a){val += a.val; if(val >= M) val -= M; return *this;} modint& operator-=(modint a){if(val < a.val) val += M-a.val; else val -= a.val; return *this;} modint& operator*=(modint a){val = (u64)val*a.val%M; return *this;} modint& operator/=(modint a){return (*this) *= a.inv();} modint operator+(modint a) const {return modint(val) +=a;} modint operator-(modint a) const {return modint(val) -=a;} modint operator*(modint a) const {return modint(val) *=a;} modint operator/(modint a) const {return modint(val) /=a;} modint operator-(){return modint(M-val);} bool operator==(const modint a) const {return val == a.val;} bool operator!=(const modint a) const {return val != a.val;} bool operator<(const modint a) const {return val < a.val;} }; class Factorial { using mint = modint<MOD>; vector<mint> facts, factinv; public: explicit Factorial(int n) : facts(static_cast<u32>(n+1)), factinv(static_cast<u32>(n+1)) { facts[0] = 1; for (int i = 1; i < n+1; ++i) facts[i] = facts[i-1]*mint(i); factinv[n] = facts[n].inv(); for (int i = n-1; i >= 0; --i) factinv[i] = factinv[i+1] * mint(i+1); } mint fact(int k) const { if(k >= 0) return facts[k]; else return factinv[-k]; } mint operator[](const int &k) const { if(k >= 0) return facts[k]; else return factinv[-k]; } mint C(int p, int q) const { if(q < 0 || p < q) return 0; return facts[p] * factinv[q] * factinv[p-q]; } mint P(int p, int q) const { if(q < 0 || p < q) return 0; return facts[p] * factinv[p-q]; } mint H(int p, int q) const { if(p < 0 || q < 0) return 0; return q == 0 ? 1 : C(p+q-1, q); } }; using mint = modint<MOD>; template<class T> class BIT { vector<T> bit; public: BIT(int n): bit(vector<T>(n+1, 0)){} T sum(int k){ T ret = 0; for (++k; k > 0; k -= (k & -k)) ret += bit[k]; return ret; } void add(int k, T x){ for (++k; k < bit.size(); k += (k & -k)) bit[k] += x; } }; int main() { int n; cin >> n; vector<int> v(n); for (auto &&i : v) scanf("%d", &i); mint ans = 1; Factorial f(n); BIT<int> S(n+1); for (int i = 0; i < n; ++i) { ans += f[n-i-1]*mint(v[i]-1-S.sum(v[i]-1)); S.add(v[i], 1); } cout << ans.val << "\n"; return 0; }
[ "firiexp@PC.localdomain" ]
firiexp@PC.localdomain
9fea92ccdca8488d1a52af72db2b62769532b23a
e4516bc1ef2407c524af95f5b6754b3a3c37b3cc
/answers/pat/1073. Scientific Notation (20).cpp
83260d4ef3419d4d92436b767a4b4d83bae6e2dc
[ "MIT" ]
permissive
FeiZhan/Algo-Collection
7102732d61f324ffe5509ee48c5015b2a96cd58d
9ecfe00151aa18e24846e318c8ed7bea9af48a57
refs/heads/master
2023-06-10T17:36:53.473372
2023-06-02T01:33:59
2023-06-02T01:33:59
3,762,869
4
0
null
null
null
null
UTF-8
C++
false
false
1,314
cpp
// #include <cstdio> #include <iostream> using namespace std; #include <cstdlib> #include <string> int main (int argc, char *argv[]) { string scien; while (cin >> scien) { size_t found = scien.find('e'); if (found == string::npos) { found = scien.find('E'); } string fractional = scien.substr(0, found); int exponent = atoi(scien.substr(found + 1).c_str()); size_t dot = fractional.find('.'); if (string::npos == dot) { dot = fractional.length(); } //cout << fractional << " e " << exponent << endl; if (exponent > 0) { int zeros = exponent - fractional.length() + dot + 1; if (zeros > 0) { fractional += string(zeros, '0'); } if (fractional.size() > dot && '.' == fractional[dot]) { fractional.erase(dot, 1); } if (fractional.size() > dot + exponent) { fractional.insert(dot + exponent, 1, '.'); } } else { int zeros = - exponent - dot + 2; if (zeros > 0) { fractional.insert(1, zeros, '0'); } if (fractional.size() > dot + zeros + 1 && '.' == fractional[dot + zeros]) { fractional.erase(dot + zeros, 1); } fractional.insert(dot + zeros + exponent, 1, '.'); } if ('+' == fractional[0]) { fractional.erase(0, 1); } cout << fractional << endl; } return 0; }
[ "dog217@126.com" ]
dog217@126.com
2c56e9d9c0ec790cf09ad0f2d8785bffa665d13e
90047daeb462598a924d76ddf4288e832e86417c
/base/metrics/histogram_functions.h
5960aca657497357e7146aff8b0e5997b9d356f6
[ "BSD-3-Clause" ]
permissive
massbrowser/android
99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080
a9c4371682c9443d6e1d66005d4db61a24a9617c
refs/heads/master
2022-11-04T21:15:50.656802
2017-06-08T12:31:39
2017-06-08T12:31:39
93,747,579
2
2
BSD-3-Clause
2022-10-31T10:34:25
2017-06-08T12:36:07
null
UTF-8
C++
false
false
4,966
h
// 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. #ifndef BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ #define BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ #include "base/metrics/histogram.h" #include "base/metrics/histogram_base.h" #include "base/time/time.h" // Functions for recording metrics. // // For best practices on deciding when to emit to a histogram and what form // the histogram should take, see // https://chromium.googlesource.com/chromium/src.git/+/HEAD/tools/metrics/histograms/README.md // Functions for recording UMA histograms. These can be used for cases // when the histogram name is generated at runtime. The functionality is // equivalent to macros defined in histogram_macros.h but allowing non-constant // histogram names. These functions are slower compared to their macro // equivalent because the histogram objects are not cached between calls. // So, these shouldn't be used in performance critical code. namespace base { // For histograms with linear buckets. // Used for capturing integer data with a linear bucketing scheme. This can be // used when you want the exact value of some small numeric count, with a max of // 100 or less. If you need to capture a range of greater than 100, we recommend // the use of the COUNT histograms below. // Sample usage: // base::UmaHistogramExactLinear("Histogram.Linear", some_value, 10); BASE_EXPORT void UmaHistogramExactLinear(const std::string& name, int sample, int value_max); // For adding sample to enum histogram. // Sample usage: // base::UmaHistogramEnumeration("My.Enumeration", VALUE, EVENT_MAX_VALUE); // Note that new Enum values can be added, but existing enums must never be // renumbered or deleted and reused. template <typename T> void UmaHistogramEnumeration(const std::string& name, T sample, T max) { static_assert(std::is_enum<T>::value, "Non enum passed to UmaHistogramEnumeration"); DCHECK_LE(static_cast<uintmax_t>(max), static_cast<uintmax_t>(INT_MAX)); DCHECK_LE(static_cast<uintmax_t>(sample), static_cast<uintmax_t>(max)); return UmaHistogramExactLinear(name, static_cast<int>(sample), static_cast<int>(max)); } // For adding boolean sample to histogram. // Sample usage: // base::UmaHistogramBoolean("My.Boolean", true) BASE_EXPORT void UmaHistogramBoolean(const std::string& name, bool sample); // For adding histogram with percent. // Percents are integer between 1 and 100. // Sample usage: // base::UmaHistogramPercentage("My.Percent", 69) BASE_EXPORT void UmaHistogramPercentage(const std::string& name, int percent); // For adding counts histogram. // Sample usage: // base::UmaHistogramCustomCounts("My.Counts", some_value, 1, 600, 30) BASE_EXPORT void UmaHistogramCustomCounts(const std::string& name, int sample, int min, int max, int buckets); // Counts specialization for maximum counts 100, 1000, 10k, 100k, 1M and 10M. BASE_EXPORT void UmaHistogramCounts100(const std::string& name, int sample); BASE_EXPORT void UmaHistogramCounts1000(const std::string& name, int sample); BASE_EXPORT void UmaHistogramCounts10000(const std::string& name, int sample); BASE_EXPORT void UmaHistogramCounts100000(const std::string& name, int sample); BASE_EXPORT void UmaHistogramCounts1M(const std::string& name, int sample); BASE_EXPORT void UmaHistogramCounts10M(const std::string& name, int sample); // For histograms storing times. BASE_EXPORT void UmaHistogramCustomTimes(const std::string& name, TimeDelta sample, TimeDelta min, TimeDelta max, int buckets); // For short timings from 1 ms up to 10 seconds (50 buckets). BASE_EXPORT void UmaHistogramTimes(const std::string& name, TimeDelta sample); // For medium timings up to 3 minutes (50 buckets). BASE_EXPORT void UmaHistogramMediumTimes(const std::string& name, TimeDelta sample); // For time intervals up to 1 hr (50 buckets). BASE_EXPORT void UmaHistogramLongTimes(const std::string& name, TimeDelta sample); // For recording memory related histograms. // Used to measure common KB-granularity memory stats. Range is up to 500M. BASE_EXPORT void UmaHistogramMemoryKB(const std::string& name, int sample); // Used to measure common MB-granularity memory stats. Range is up to ~64G. BASE_EXPORT void UmaHistogramMemoryLargeMB(const std::string& name, int sample); } // namespace base #endif // BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
3476552727f79e860fc2e317bee5af682f7a60e5
b1098a2540fd27d05f33219e6bb2868cdda04c89
/imperative/python/src/module_trace.cpp
44cb72768b4c98b789541dc6b5f56535e053e23a
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
chenjiahui0131/MegEngine
de5f96a8a855a7b2d324316e79ea071c34f8ab6a
6579c984704767086d2721ba3ec3881a3ac24f83
refs/heads/master
2023-08-23T21:56:30.765344
2021-10-20T10:03:29
2021-10-20T10:03:29
400,480,179
0
0
null
null
null
null
UTF-8
C++
false
false
1,355
cpp
/** * \file imperative/python/src/module_trace.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #include "./module_trace.h" #include "./helper.h" // include op pybind11 caster namespace py = pybind11; namespace mgb::imperative::python { apply_result_t apply_module_trace(ApplyContext& ctx) { apply_result_t outputs; auto args = py::tuple(ctx.nargs + 1); args[0] = py::cast(ctx.op); for (size_t i = 0; i < ctx.nargs; i++) { args[i + 1] = TensorWrapper::make(ctx.args[i]->shared_from_this()); } auto pyout = PyObject_Call(cpp_apply_module_trace, args.ptr(), nullptr); if (!pyout) throw py::error_already_set(); auto ret = py::reinterpret_steal<py::object>(pyout); // assumption: python function always returns PyList auto tup = py::reinterpret_borrow<py::list>(ret); for (auto i = 0; i < tup.size(); i++) { auto tw = TensorWrapper::try_cast(tup[i].ptr()); outputs.emplace_back(tw->m_tensor); } return outputs; } } // namespace mgb::imperative::python
[ "megengine@megvii.com" ]
megengine@megvii.com
96d51ac6628a2cc374def2888f6bb4ceef8869af
e9edfd5c5d99c67fb41c8011031dae34631ca0fe
/src/UnfoldingEvent.cpp
14fc4e67197bd6abae47d58d3e0664fd9cbf630c
[]
no_license
pham-theanh/testing-program
5ac079281abbb461fdf756112414b633bec975d2
11b91692dace890e443e8c153f8d165357b9101a
refs/heads/master
2020-12-02T10:06:05.038058
2018-10-16T08:15:44
2018-10-16T08:15:44
96,690,932
0
0
null
null
null
null
UTF-8
C++
false
false
14,043
cpp
#include "UnfoldingChecker.hpp" #include <unistd.h> UnfoldingEvent::UnfoldingEvent(int nb_events, Transition t, EventSet causes) { this->id = nb_events; this->causes = causes; this->transition = t; } void UnfoldingEvent::print() { std::cout << "e" << this->id << " = < t" << this->transition.id << "-p" << this->transition.actor_id << "("; if (this->transition.type.length() > 1) std::cout << this->transition.type << ")" << "," << "("; if (this->causes.empty()) std::cout << "-) >"; else { for (auto evt : this->causes.events_) std::cout << "e" << evt->id << ","; std::cout << " ) >"; } } // Recursively compute the history of a given event by adding the causes of all ancestors EventSet UnfoldingEvent::getHistory() const { if (causes.empty()) // No direct ancestor => empty history return causes; else { //EventSet res = causes; EventSet res; for (auto ancestor : causes.events_) { EventSet h1; // if event ancestor is already in history set -> we do not need to get it's history if (not res.contains(ancestor)) h1 = ancestor->getHistory(); h1.insert(ancestor); res = res.makeUnion(res, h1); } return res; } } bool UnfoldingEvent::inHistory(UnfoldingEvent *otherEvent) { if (this->getHistory().contains(otherEvent)) return true; return false; } /*Check whether 2 events a Test and a Send/Receive concern the same communication, * Here the events are supposed that they are not causality related * */ bool UnfoldingEvent::concernSameComm(UnfoldingEvent*event, UnfoldingEvent* otherEvent){ UnfoldingEvent*testEvt, *SdRcEvt, *testedEvt; //std::cout <<" \n hien thi evet trong ham concern :"; //event->print(); //otherEvent->print(); //std::cout <<" \n ham concern 1: \n"; if (event->transition.mailbox_id != otherEvent->transition.mailbox_id) return false; if (event->transition.type=="Test") {testEvt = event; SdRcEvt = otherEvent;} else {testEvt = otherEvent; SdRcEvt = event;} // 2 sends or 2 receives can not concern the same communication int comId = testEvt->transition.commId; EventSet testEvtH = testEvt->getHistory(); EventSet SdRcEvtH = SdRcEvt->getHistory(); for(auto it : testEvtH.events_) if ( it->transition.actor_id == testEvt->transition.actor_id and it->transition.commId ==comId) testedEvt = it; if (testedEvt->transition.type == SdRcEvt->transition.type) return false; int mbId = testedEvt->transition.mailbox_id; //std::cout <<" \n ham concern 2: \n"; if (testedEvt->transition.type =="Isend") { EventSet testedEvtH = testedEvt->getHistory(); int nbSend =0, nbReceive =0; //count the number of Isend event before testedEvt for (auto it: testedEvtH.events_) if (it->transition.mailbox_id == mbId and it->transition.type == "Isend") nbSend++; //count the number of Ireceive event before SdRcEvt for (auto it: SdRcEvtH.events_) if (it->transition.mailbox_id == mbId and it->transition.type == "Ireceive") nbReceive++; if(nbSend == nbReceive) return true; } if (testedEvt->transition.type =="Ireceive") { //std::cout <<" \n ham concern 3: \n"; EventSet testedEvtH = testedEvt->getHistory(); int nbSend =0, nbReceive =0; //count the number of Receive event before testedEvt for (auto it: testedEvtH.events_) if (it->transition.mailbox_id == mbId and it->transition.type == "Ireceive") nbReceive++; //count the number of Isend event before SdRcEvt for (auto it: SdRcEvtH.events_) if (it->transition.mailbox_id == mbId and it->transition.type == "Isend") nbSend++; //if (nbSend == nbReceive) std::cout<<"\n CONCERN the same COMM nbsend =" << nbSend <<" nb receive = "<< nbReceive << " \n"; if(nbSend == nbReceive) return true; } return false; } /** @brief check for conflict in the history of provided events * * In the paper, this.isConflict(other) is written "this # other" */ bool UnfoldingEvent::isConflict(UnfoldingEvent*event, UnfoldingEvent* otherEvent) { // event e should not conflict with itself //if(event->conflictEvts.contains(otherEvent) or otherEvent->conflictEvts.contains(event) ) return true; if (*event == *otherEvent) return false; // std::cout<<"\n trong ham cflict"; EventSet h1, h2; h1 = event->getHistory(); h2 = otherEvent->getHistory(); // checking causality relation, if they are in a causality relation return false if (h1.contains(otherEvent) or h2.contains(event)) return false; // check direct conflict if (event->transition.isDependent(otherEvent->transition)) return true; // if 2 event they have the same causes, just check their last transition if (event->causes == otherEvent->causes) return event->transition.isDependent(otherEvent->transition); // if not, then check dependent relation on their full histories else { h1.insert(event); h2.insert(otherEvent); EventSet his = h1; //FIXME remove all common events for (auto evt : his.events_) if (h2.contains(evt)) { h1.erase(evt); h2.erase(evt); } return h1.depends(h2); } // std::cout<<"\n trong ham cflict6"; return false; } /** @brief Checks if current event is in immediate conflict with the provided one * * For that, there is two conditions to meet: * - both events are in conflict (there is a conflict in their histories) * - Union(hist1, hist2, evt2) is a valid configuration * AND Union(hist1, evt1, hist2) is a valid configuration * * In the paper, e1.isImmediate(e2) will be written "e1 #ⁱ e2" */ bool UnfoldingEvent::isImmediateConflict(UnfoldingEvent *evt1, UnfoldingEvent *evt2) { // event e should not conflict with itself if (*evt1 == *evt2) return false; // The first condition is easy to check if (not evt1->isConflict(evt1 ,evt2)) return false; // Now, check the second condition EventSet hist1 = evt1->getHistory(); EventSet hist2 = evt2->getHistory(); // First compare the existing configurations // romove all common events EventSet hist11 = hist1, hist21 = hist2; for (auto e1 : hist2.events_) if (evt1->isConflict(evt1,e1))return false; // Compare the first config to the second new event for (auto e1 : hist1.events_) if (evt2->isConflict(evt2,e1)) return false; // Every tests passed return true; } bool UnfoldingEvent::isImmediateConflict1(UnfoldingEvent *evt1, UnfoldingEvent *evt2) { // event e should not conflict with itself if (*evt1 == *evt2) return false; bool chk1 = false, chk2 = false ; /* if (evt1->id == 28 and evt2->id ==19) if (evt1->transition.isDependent(evt2->transition)){ std::cout <<"\n hai tran depend voi nhau \n "; }*/ if (not evt1->transition.isDependent(evt2->transition)) { chk1 = true; chk2 = true; if (evt1->transition.type =="Test" and (evt2->transition.type =="Isend" or evt2->transition.type == "Ireceive")) { if( not evt1->concernSameComm(evt1,evt2)) return false; else { chk2 = false; } } if (evt2->transition.type =="Test" and (evt1->transition.type =="Isend" or evt1->transition.type == "Ireceive")) { if( not evt1->concernSameComm(evt1,evt2)) return false; else { chk2 = false;} } } // 2 transitions are not depend and they are one is test other one is send/receive -> return false if (chk1 and chk2 ) return false; // Now, check the second condition EventSet hist1 = evt1->getHistory(); EventSet hist2 = evt2->getHistory(); EventSet hist11 = hist1, hist21 = hist2; // if causality ralated - > no immidiate conflict if (hist1.contains(evt2) or hist2.contains(evt1)) return false; for (auto e1 : hist1.events_) if (hist2.contains(e1)) {hist11.erase(e1); hist21.erase(e1);} //if(hist11.empty() or hist21.empty()) if (evt1->id == 28 and evt2->id == 19) std::cout<<" \n kt depend trong ham isImmidiate empy no roi"; //std::cout <<"\n kiem tra dk depends \n "; EventSet evtS1, evtS2; evtS1.insert(evt1); evtS2.insert(evt2); if(hist11.depends(hist21) or evtS1.depends(hist21) or evtS2.depends(hist11)) { //std::cout <<" DEPENDS HISTORY roi\n "; return false;} //std::cout <<"se tra ve true nhe ### \n"; return true; } // checking conflict relation between one event and one configuration or one history, it used when computing enC // there is a better way by checking the event with maximal events in the configuration, (change type of enC ) bool UnfoldingEvent::conflictWithConfig(UnfoldingEvent *event, Configuration config) { if (config.size() == 0) return false; // we don't really need to check the whole config. The maximal event should be enough. for (auto evt : config.maxEvent.events_) if (event->isConflict(event, evt)) return true; return false; } // this operator is used for ordering in a set (need a key) bool UnfoldingEvent::operator<(const UnfoldingEvent& other) const { if ((this->transition.actor_id < other.transition.actor_id) or (this->transition.id < other.transition.id) or (not (this->causes == other.causes))) return true; return false; } /** @brief check semantic equality (same transition, same causes) */ bool UnfoldingEvent::operator==(const UnfoldingEvent& other) const { if ((this->transition.id != other.transition.id) or (this->transition.actor_id != other.transition.actor_id)) return false; if (this->causes.size() != other.causes.size()) return false; for (auto it : this->causes.events_) { bool chk1 = false; for (auto it1 : other.causes.events_) if (*it == *it1) { chk1 = true; break; } if (not chk1)return false; } return true; } void Configuration::updateMaxEvent(UnfoldingEvent *e) { this->lastEvent = e; // update the maximal events for current Conf removing causes from maxEvent and adding e to the maxEvent for (auto evt : e->causes.events_) { maxEvent.erase(evt); //setMaxEvents.erase(evt->id); } maxEvent.insert(e); /* update the maximal events for the actor=> removing the evt shares the same actor with e, then adding e to the actorMaxEvent */ for (auto evt : actorMaxEvent.events_) if (evt->transition.actor_id == e->transition.actor_id) actorMaxEvent.erase(evt); actorMaxEvent.insert(e); } Configuration Configuration::plus(UnfoldingEvent *evt) { Configuration res; res.events_ = this->events_; res.maxEvent = this->maxEvent; res.actorMaxEvent = this->actorMaxEvent; if (not res.contains(evt)) res.events_.insert(evt); return res; } bool EventSet::contains(UnfoldingEvent *e) { for (auto evt : this->events_) if (*evt == *e) return true; return false; } void EventSet::subtruct(EventSet otherSet) { for (auto evt : otherSet.events_) if (this->contains(evt)) this->erase(evt); } UnfoldingEvent* EventSet::find(UnfoldingEvent *e) { for (auto evt : this->events_) if (*evt == *e) { return evt; } } UnfoldingEvent * Configuration :: findTestedComm(UnfoldingEvent *testEvt){ for (auto it : this->events_) if (it->transition.commId == testEvt->transition.commId and it->transition.type != "Test" and it->transition.actor_id == testEvt->transition.actor_id) return it; } /** @brief Check if I'm dependent with another EventSet * Here we suppose that 2 given event sets do not have common events * */ bool EventSet::depends(EventSet s2) { if(this->events_.empty() or s2.events_.empty()) return false; for (auto e1 : this->events_) for (auto e2 : s2.events_) if (e1->transition.isDependent(e2->transition)) return true; else if ((e1->transition.type =="Test" and (e2->transition.type =="Isend" or e2->transition.type == "Ireceive")) or (e2->transition.type =="Test" and (e1->transition.type =="Isend" or e1->transition.type == "Ireceive"))) if(e1->concernSameComm(e1,e2)) return true; return false; } bool EventSet::isConfig() { if ((this->size() == 1) && (this->begin()->causes.empty())) return true; // checking conflict relation between one event and all other events in the set for (auto e1 : events_) { for (auto e2 : events_) { if (*e1 == *e2) continue; if (e1->isConflict(e1,e2)) return false; } // Every event of the history should be in the set for (auto ancestor : e1->getHistory().events_) if (not (this->contains(ancestor))) return false; } return true; } EventSet EventSet::makeUnion(EventSet s1, EventSet s2) { EventSet res= s1; // res.events_.insert(s1.events_.begin(), s1.events_.end()); // res.events_.insert(s2.events_.begin(), s2.events_.end()); for (auto evt : s2.events_) res.insert(evt); return res; } EventSet EventSet::makeIntersection(EventSet s1, EventSet s2) { EventSet res; std::set_intersection(s1.events_.begin(), s1.events_.end(), s2.events_.begin(), s2.events_.end(), std::inserter(res.events_, res.events_.begin())); return res; } EventSet EventSet::minus(UnfoldingEvent *evt) { EventSet res; res.events_ = this->events_; for (auto e : this->events_) if (*e == *evt) res.erase(e); return res; } EventSet EventSet::plus(UnfoldingEvent *evt) { EventSet res; res.events_ = this->events_; if(not res.contains(evt)) res.events_.insert(evt); return res; } size_t EventSet::size() const{ return events_.size(); } bool EventSet::empty() const { return this->events_.empty(); } UnfoldingEvent* EventSet::begin() const { return *events_.begin(); } UnfoldingEvent* EventSet::end() const { return *events_.end(); } bool EventSet::operator==(const EventSet& other) const { return this->events_ == other.events_; } void EventSet::insert(UnfoldingEvent* e) { if (not this->contains(e)) events_.insert(e); } void EventSet::erase(UnfoldingEvent *e) { std::set<UnfoldingEvent*> evtS = this->events_; for (auto it : evtS) if(*it == *e) this->events_.erase(it); } bool EventSet::conflictWithEvt(UnfoldingEvent *e) { for (auto evt : this->events_) if (evt->isConflict(evt,e)) return true; return false; } bool EventSet::isEmptyIntersection(EventSet evtS1, EventSet evtS2) { if(evtS1.size() ==0 or evtS2.size() ==0) return false; for (auto evt : evtS2.events_) if (evtS1.contains(evt)) return false; return true; }
[ "noreply@github.com" ]
pham-theanh.noreply@github.com
73f3f7177e37639629441fec3929bcb69b5fad6d
6c9b803226601ed8e6fab9c1a9b5183c43a59f23
/ConsoleApplication6/ConsoleApplication6.cpp
8be3f3e4ee698a2b156962a2548b6d2417f2cfd8
[]
no_license
happyDmac09/BMI-Calculator
4da9571dd9ccbc0d5a644c7b84f8e690a9b44b73
80e8e2bfd36863875557d8dbac8272ee3472fba4
refs/heads/master
2021-04-28T18:49:37.691651
2018-02-17T18:04:09
2018-02-17T18:04:09
121,880,999
0
0
null
null
null
null
UTF-8
C++
false
false
138
cpp
// ConsoleApplication6.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main() { return 0; }
[ "35273499+happyDmac09@users.noreply.github.com" ]
35273499+happyDmac09@users.noreply.github.com
f235d573d827721584c030d391e1e01e47023c9c
5095bbe94f3af8dc3b14a331519cfee887f4c07e
/howwet/Shared/Gobjs/GSTRING.CPP
a73da018425274269db6226a0de400b6b74534f7
[]
no_license
sativa/apsim_development
efc2b584459b43c89e841abf93830db8d523b07a
a90ffef3b4ed8a7d0cce1c169c65364be6e93797
refs/heads/master
2020-12-24T06:53:59.364336
2008-09-17T05:31:07
2008-09-17T05:31:07
64,154,433
0
0
null
null
null
null
UTF-8
C++
false
false
11,656
cpp
#include <consts.h> #include <gobjs\gstring.h> #include <iostream.h> #include <strstrea.h> #include <stdio.h> IMPLEMENT_CASTABLE(GString); IMPLEMENT_STREAMABLE(GString); // ******************************************************************* void GString::Streamer::Write(opstream& os) const { // ******************************************************************* // Short description: // Writes an instance of GString to the passed ipstream. // Notes: // Changes: // DPH 23/6/94 // Calls: // Internal variables // -------------------- Executable code section ---------------------- string& St = *GetObject(); os << St; } // ******************************************************************* void *GString::Streamer::Read(ipstream& is, uint32 /*version*/) const { // ******************************************************************* // Short description: // Reads an instance of GString from the passed ipstream. // Notes: // Changes: // DPH 23/6/94 // Calls: // Internal variables // -------------------- Executable code section ---------------------- string& St = *GetObject(); is >> St; return GetObject(); } // ******************************************************************* void GString::Replace(const GString& String1, const GString& String2) { // ******************************************************************* // Short description: // Replace string 1 with string 2 and return result. // Notes: // Changes: // DPH 17/11/94 // Calls: // Internal variables size_t Pos; // Position in string // -------------------- Executable code section ---------------------- // Determine if there is something to replace. Pos = find(String1); while (Pos != NPOS) { replace(Pos, String1.length(), String2); Pos = find(String1, Pos + String2.length()); } } // ******************************************************************* void GString::Replace(const char *String1, const char *String2) { // ******************************************************************* // Short description: // Replace string 1 with string 2 and return result. // Notes: // Changes: // DPH 17/11/94 // Calls: // Internal variables GString Str1; // String1 GString Str2; // String2 // -------------------- Executable code section ---------------------- Str1.assign(String1); Str2.assign(String2); Replace(Str1, Str2); }; // ******************************************************************* void GString::Assign (const GString& Str, size_t Pos, size_t n) { // ******************************************************************* // Short description: // Assign a portion of string Str // Notes: // Changes: // DPH 18/11/94 // Calls: // Internal variables // none // -------------------- Executable code section ---------------------- assign(Str, Pos); if (n < length()) remove(n); } // ******************************************************************* char GString::Read_token(istream& In_stream, const GString& Init_skip_chars, const GString& Delimiter_chars) { // ******************************************************************* // Short description: // Read in a token. Skip all leading skip characters and stop when a delimiter // character is found. Returns the character causing a parse stop. // Notes: // Changes: // DPH 21/11/94 // Calls: // Internal variables char Character[2]; // Character read from stream. bool Still_skipping_init = true; // Are we still skipping initial chars? // -------------------- Executable code section ---------------------- // Clear the strings contents assign(""); // Skip all initial characters. while (In_stream && Still_skipping_init) { In_stream.get((char*) &Character, 2, 0); if (strlen(Character) == 0) Still_skipping_init = false; else if (Init_skip_chars.contains(Character)) Still_skipping_init = true; else Still_skipping_init = false; } // Append characters to string until a delimiter is found. while (strlen(Character) != 0 && !Delimiter_chars.contains(Character) && In_stream) { append(Character); In_stream.get((char*) &Character, 2, 0); } // If reached end of file then return 0; if (!In_stream) return 0; return Character[0]; } // ******************************************************************* void *GString::Get_pointer(void) { // ******************************************************************* // Short description: // Treat string as a pointer. // Notes: // Changes: // DPH 21/11/94 // Calls: // Internal variables void *Pointer_to_return; // pointer to return to caller. // -------------------- Executable code section ---------------------- sscanf(c_str(), "%p", &Pointer_to_return); return Pointer_to_return; } // ******************************************************************* void GString::Set_pointer(void *Pointer) { // ******************************************************************* // Short description: // Set string up as a pointer // Notes: // Changes: // DPH 21/11/94 // Calls: // Internal variables char Temp_string[50]; // Temporary string. // -------------------- Executable code section ---------------------- sprintf(Temp_string, "%p", Pointer); assign(Temp_string); } // ******************************************************************* float GString::Get_real(void) { // ******************************************************************* // Short description: // Treat string as a real value // Notes: // Changes: // DPH 21/11/94 // Calls: // Internal variables float Real_value = 0.0; // Real value to return char *End_char; // -------------------- Executable code section ---------------------- if (length() > 0) { Real_value = strtod(c_str(), &End_char); if (*End_char != NULL && *End_char != ' ') Real_value = 0.0; } return Real_value; } // ******************************************************************* void GString::Set_real(float Real_value) { // ******************************************************************* // Short description: // Set string up as a pointer // Notes: // Changes: // DPH 21/11/94 // Calls: // Internal variables char Temp_string[50]; // Temporary string. // -------------------- Executable code section ---------------------- ostrstream Out_stream(Temp_string, sizeof(Temp_string)); Out_stream << Real_value << ends; assign(Temp_string); } // ******************************************************************* int GString::Get_integer(void) { // ******************************************************************* // Short description: // Treat string as an integer value // Notes: // Changes: // DPH 21/11/94 // Calls: // Internal variables int Integer_value = 0; // integer value to return // -------------------- Executable code section ---------------------- if (length() > 0) Integer_value = atoi(c_str()); return Integer_value; } // ******************************************************************* void GString::Set_integer(int Integer_value) { // ******************************************************************* // Short description: // Set string up as a pointer // Notes: // Changes: // DPH 21/11/94 // Calls: // Internal variables char Temp_string[50]; // Temporary string. // -------------------- Executable code section ---------------------- ostrstream Out_stream(Temp_string, sizeof(Temp_string)); Out_stream << Integer_value << ends; assign(Temp_string); } // ******************************************************************* char GString::Get_last_char(void) { // ******************************************************************* // Short description: // Return the last non blank character to caller. // Notes: // Changes: // DPH 23/11/94 // Calls: // Internal variables size_t Pos; // Position of last non blank character char Return_char; // Character to return to caller. // -------------------- Executable code section ---------------------- Pos = find_last_not_of(" "); if (Pos > length()) Return_char = 0; else Return_char = get_at(Pos); return Return_char; } // ******************************************************************* void GString::Strip(StripType s, char c) { // ******************************************************************* // Short description: // Strip away unwanted chars from string. // Notes: // Changes: // DPH 14/12/94 // Calls: // Internal variables size_t Pos; // Position in string // -------------------- Executable code section ---------------------- if (length() > 0) { if (s == string::Both || s == string::Leading) { Pos = find_first_not_of(c); if (Pos == NPOS) Pos = length(); remove(0, Pos); } } if (length() > 0) { if (s == string::Both || s == string::Trailing) { Pos = find_last_not_of(c); if (Pos < length() - 1) remove(Pos + 1); } } } // ******************************************************************* ipstream& operator >> (ipstream& is, String_array& Obj) { // ******************************************************************* // Short description: // Read a string array from an ipstream. // Notes: // Changes: // DPH 21/9/95 // Calls: // Internal variables int Num_elements; // Number of elements to add to list. GString Str; // String read from stream. // -------------------- Executable code section ---------------------- Obj.Flush(); is >> Num_elements; for (int Element = 0; Element < Num_elements; Element++) { is >> Str; Obj.Add(Str); } return is; } // ******************************************************************* opstream& operator << (opstream& os, const String_array& Obj) { // ******************************************************************* // Short description: // Write a string array to an opstream. // Notes: // Changes: // DPH 21/9/95 // Calls: // Internal variables // -------------------- Executable code section ---------------------- os << Obj.GetItemsInContainer(); for (int Element = 0; Element < Obj.GetItemsInContainer(); Element++) { os << Obj[Element]; } return os; } // ******************************************************************* bool GString::Is_numerical(void) { // ******************************************************************* // Short description: // returns TRUE if string is numerical // Notes: // Changes: // DPH 14/12/94 // Calls: // Internal variables char *End_char; // -------------------- Executable code section ---------------------- strtod(c_str(), &End_char); return !(*End_char != NULL && *End_char != ' '); }
[ "hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8" ]
hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8
bfc5408e8962bd74cb7f4e9308ce872e31fe2785
13a28512d570eabb27d40362bce194805f4ab266
/Lab3/Src/Application/myMesh.h
6960defe1b12ee7156f3064d38a10b25a96b1ed0
[]
no_license
hmpbmp/CGLabs
c5116f04a7f84cba56f3f20e537cfb2b9d157ec3
f7ccaa556cf3dba3c217444e392786a9b1b3be7a
refs/heads/master
2020-05-20T03:53:42.042286
2014-12-19T22:00:02
2014-12-19T22:00:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
866
h
#ifndef MY_MESH_INCLUDED #define MY_MESH_INCLUDED /** @file myMesh.h @brief User-defined mesh class definition @date Created on 13/10/2014 @project D3DBase @author Semyon Kozyrev */ // ******************************************************************* // includes #include <windows.h> #include <windowsx.h> #include <d3dx9.h> #include <stdlib.h> // ******************************************************************* // defines & constants // ******************************************************************* // classes class MyMesh { public: //Loading mesh from file void load(char *filename, IDirect3DDevice9 *device); //Rendering void render(IDirect3DDevice9 *device); //Release mesh and materials void release(); private: ID3DXMesh *mesh; D3DMATERIAL9 *materials; DWORD matNum = 0; HRESULT meshLoadResult; }; #endif
[ "ck-47@mail.ru" ]
ck-47@mail.ru
02547823300519c88356eb0c0a03472751f74aef
6fcdbb23b52acbd3c1f32c55308801f1067a6ac6
/ProgramForClient/NewOnlineInstall/DUILIB/Demos/duidemo/SkinManager.h
77f4ee8a21713ffdfb3886f25a8274728d34118e
[]
no_license
jyqiu1216/Rino
e507b70a2796cb356cd7ce90578981802ee5008c
eb8c110e7a551ee9bd736792a957a544c5ffdeb5
refs/heads/master
2020-04-13T21:41:26.474356
2017-05-19T07:39:42
2017-05-19T07:39:42
86,565,153
3
2
null
null
null
null
UTF-8
C++
false
false
1,066
h
#ifndef __SKIN_MANAGER_H__ #define __SKIN_MANAGER_H__ #include "..\..\DuiLib\UIlib.h" struct SkinChangedParam { bool bColor; DWORD bkcolor; CDuiString bgimage; }; typedef class ObserverImpl<BOOL, SkinChangedParam> SkinChangedObserver; typedef class ReceiverImpl<BOOL, SkinChangedParam> SkinChangedReceiver; class CSkinManager { public: static CSkinManager* GetSkinManager() { if (m_pSkinManager == NULL) { m_pSkinManager = new CSkinManager(); } return m_pSkinManager; } public: void AddReceiver(ReceiverImpl<BOOL, SkinChangedParam>* receiver) { m_SkinChangeObserver.AddReceiver(receiver); } void RemoveReceiver(ReceiverImpl<BOOL, SkinChangedParam>* receiver) { m_SkinChangeObserver.RemoveReceiver(receiver); } void Broadcast(SkinChangedParam param) { m_SkinChangeObserver.Broadcast(param); } void Notify(SkinChangedParam param) { m_SkinChangeObserver.Notify(param); } private: CSkinManager(){} private: SkinChangedObserver m_SkinChangeObserver; static CSkinManager* m_pSkinManager; }; #endif // __SKIN_MANAGER_H__
[ "qiujy" ]
qiujy
e636d8b443b7ab336f2de789fc6756534ba050ba
30f1c38a36d1c2730cd0feb50d6e8399506df53c
/src/scenes/heatherMolnarScene/heatherMolnarScene.h
35f0eac9f6ea4e482426ac1998e55f1e2a913f18
[ "MIT" ]
permissive
ffeng271/recoded
1832032b847b5a261fd0d4ff4af2c57972862174
934e1184c7502d192435c406e56b8a2106e9b6b4
refs/heads/master
2020-03-29T22:38:14.124047
2017-11-15T17:22:45
2017-11-15T17:22:45
150,431,859
1
0
MIT
2018-09-26T13:34:12
2018-09-26T13:34:12
null
UTF-8
C++
false
false
600
h
#pragma once #include "ofMain.h" #include "baseScene.h" class heatherMolnarScene : public baseScene { public: void setup(); void update(); void draw(); ofPoint calculateStartCoordinates(int columnPosition, int rowPosition); int calculateAngleRangeForColumn(int distanceFromEdge); void drawLineWithAngleAndThickness(ofPoint startingPoint, int angle, int distance); int columns, rows, offset, cellSize; float midPoint, possibleAngleVariation; ofParameter<int> thickness; ofParameter<int> minAngle; ofParameter<int> maxMidpointAngle; };
[ "moore.hj@gmail.com" ]
moore.hj@gmail.com
9dfc09288a8176e22aaa5cdfc53bce5bfc72071b
9a3ec3eb5371a0e719b50bbf832a732e829b1ce4
/GameOps/IslandPortal7.h
eb5b4cb6a04a2c1070d4273c764f11a38fcb9109
[]
no_license
elestranobaron/T4C-Serveur-Multiplateformes
5cb4dac8b8bd79bfd2bbd2be2da6914992fa7364
f4a5ed21db1cd21415825cc0e72ddb57beee053e
refs/heads/master
2022-10-01T20:13:36.217655
2022-09-22T02:43:33
2022-09-22T02:43:33
96,352,559
12
8
null
null
null
null
UTF-8
C++
false
false
331
h
#include <NPCStructure.h> #ifndef __ISLANDPORTAL7_H #define __ISLANDPORTAL7_H class IslandPortal7 : public NPCstructure{ public: IslandPortal7(); ~IslandPortal7(); void Create( void ); void OnTalk( UNIT_FUNC_PROTOTYPE ); void OnAttacked( UNIT_FUNC_PROTOTYPE ); void OnInitialise( UNIT_FUNC_PROTOTYPE ); }; #endif
[ "lloancythomas@hotmail.co" ]
lloancythomas@hotmail.co
e3fcc856a282ec2a76ed85615796015f117baee3
72c4ecebf49a1239ab015e9b15a80319a0c27448
/shooting/Object/Player.h
10627cac41bf92afb0cb016562d1c753dd433681
[]
no_license
NakagawaTenmaa/on-line_shooting
256ddad54b95fc3fccff89d1c721e8a245b88a87
b39534c511c8872ce7ba1eca6b567b40d3e257a8
refs/heads/master
2021-10-08T12:29:56.169844
2018-12-12T01:25:36
2018-12-12T01:25:36
160,271,683
0
0
null
2018-12-12T00:52:36
2018-12-04T00:22:34
C++
UTF-8
C++
false
false
486
h
#pragma once #include <vector> #include "Object.h" #include "Bullet.h" /// <summary> /// プレイヤークラス /// </summary> class Player : public Object { public: // コンストラクタ Player(); // デストラクタ ~Player(); // 更新 bool Update(); // 描画 void Render(); // 力 int GetPower(); private: // 弾の管理 std::vector<Bullet*> m_bullet; static const int BULLET_SIZE; int m_timer; int m_power; // 画像の状態 byte m_imageState; };
[ "tenko1177@gmail.com" ]
tenko1177@gmail.com
16a2e2b98ffcb53921571a5d7146d8041c1b4fdd
ee37acbe7a5a4e7e5bda93ca236240f9d03943b7
/src/ofApp.cpp
1a057ff1ad79e8e4a6f36350bbead6e26153acc0
[]
no_license
noseshape/dda_pubSubOsc_wekinator
c1a23e25b242cc948b2555c592b1eefb34264f0d
e3f1b3be44050747eaf286fac8554320f72201a9
refs/heads/master
2021-06-26T00:00:14.691187
2017-09-10T15:03:11
2017-09-10T15:03:11
103,038,381
0
0
null
null
null
null
UTF-8
C++
false
false
4,596
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetFrameRate(60); ofSetWindowShape(800, 600); ofBackground(255, 255, 255); //graph col[0] = ofColor(255, 0, 0); col[1] = ofColor(0, 255, 0); col[2] = ofColor(0, 0, 255); col[3] = ofColor(255, 255, 0); pos = ofVec2f(700, 450); graphScale = 300.0; //gui gui.setup(); gui.add(max.setup("Max", 1.00, 0.00, 1.50)); gui.add(min.setup("min", -0.10, -0.50, 1.00)); gui.add(bSerial.setup("serial", false)); gui.add(servoMin.setup("servoMin", 169, 0, 360)); gui.add(servoMax.setup("servoMax", 145, 0, 360)); angle = 0; //arduino serial serial.setup("/dev/cu.usbmodem1411",9600); //receiver receiver.setup(12000); } //-------------------------------------------------------------- void ofApp::update(){ ofSetWindowTitle(ofToString(ofGetFrameRate())); //receiver while(receiver.hasWaitingMessages()){ ofxOscMessage p; receiver.getNextMessage(p); for(int i=0;i<3;i++){ wekv[i]=p.getArgAsFloat(i); cout<<ofToString(i)+": "+ofToString(wekv[i])<<endl; } } //serial value adjusting if(wekv[1] > min && wekv[1] < max){ angle = ofMap(wekv[1], min, max, servoMin, servoMax); } //serial value if(bSerial && ofGetFrameNum()%12 == 0){ if(bSerial!=bbSerial){ serial.writeByte(255); }else{ serial.writeByte(angle); } bbSerial = bSerial; } } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(255, 255, 255); //scale ofSetColor(0, 0, 0); ofDrawBitmapString("dda_valueControler", 10, 10); //graph ofPushMatrix(); ofTranslate(pos); ofPushMatrix(); ofScale(ofVec2f(-1, -1)); //x:右→左, y:下→上 ofSetLineWidth(2); for(int n = 0; n < stateNum; n++){ for(int i = 60*5-1; i > 0; i--){ pastValue[n][i] = pastValue[n][i-1]; } pastValue[n][0] = wekv[n]; ofPolyline line; for(int i = 0; i < 60*5; i++){ line.addVertex(ofVec2f(i, pastValue[n][i] * graphScale)); } ofSetColor(col[n]); line.draw(); } ofSetColor(255, 120, 150); ofDrawLine(0, max * graphScale, 60 * 5, max * graphScale); ofSetColor(120, 255, 255); ofDrawLine(0, min * graphScale, 60 * 5, min * graphScale); ofSetColor(0, 0, 0); ofSetLineWidth(1); ofNoFill(); ofDrawRectangle(0, 0, 60*5, graphScale); for(int i = 0; i <= 5; i++){ ofDrawLine(60*i, 0, 60*i, graphScale); ofDrawBitmapString(ofToString(i) + 's', 60*i, -15); } ofPopMatrix(); ofPopMatrix(); //gui gui.draw(); //receive ofDrawBitmapString("receive", 10, 185); for(int i = 0; i < stateNum; i++){ string log_state = "state" + ofToString(i) + ": " + ofToString(wekv[i]); ofDrawBitmapString(log_state, 10, 200 + 30*i); } //send ofDrawBitmapString("send", 10, 390); ofDrawBitmapString("angle: " + ofToString(angle), 10, 400); if(ofGetFrameNum() % 12 == 0){ } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "noseshape@gmail.com" ]
noseshape@gmail.com
43f3e829d5aa84f8e7cd2421ff564273a646ea6d
f252f75a66ff3ff35b6eaa5a4a28248eb54840ee
/external/opencore/oscl/oscl/config/android/osclconfig.h
616cfe6eb66cd74ad70ec17eb4d3efa4aa20f7ff
[ "MIT", "LicenseRef-scancode-other-permissive", "Artistic-2.0", "LicenseRef-scancode-philippe-de-muyter", "Apache-2.0", "LicenseRef-scancode-mpeg-iso", "LicenseRef-scancode-unknown-license-reference" ]
permissive
abgoyal-archive/OT_4010A
201b246c6f685cf35632c9a1e1bf2b38011ff196
300ee9f800824658acfeb9447f46419b8c6e0d1c
refs/heads/master
2022-04-12T23:17:32.814816
2015-02-06T12:15:20
2015-02-06T12:15:20
30,410,715
0
1
null
2020-03-07T00:35:22
2015-02-06T12:14:16
C
UTF-8
C++
false
false
1,849
h
// -*- c++ -*- // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // O S C L C O N F I G ( P L A T F O R M C O N F I G I N F O ) // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = #ifndef OSCLCONFIG_H_INCLUDED #define OSCLCONFIG_H_INCLUDED // system includes for dynamic registry #include <dirent.h> #include <dlfcn.h> #define OSCL_HAS_ANDROID_SUPPORT 1 #define OSCL_HAS_ANDROID_FILE_IO_SUPPORT 1 #define OSCL_EXPORT_REF __attribute__ ((visibility("default"))) #define OSCL_IMPORT_REF __attribute__ ((visibility("default"))) // include common include for determining sizes from limits.h #include "osclconfig_limits_typedefs.h" //This switch turns off some profiling and debug settings #ifdef NDEBUG #define OSCL_RELEASE_BUILD 1 #else #define OSCL_RELEASE_BUILD 0 #endif // include common unix definitions #include "osclconfig_unix_android.h" // define the suffix for unsigned constants #define OSCL_UNSIGNED_CONST(x) x##u // override the common definition for #undef OSCL_NATIVE_UINT64_TYPE #define OSCL_NATIVE_UINT64_TYPE u_int64_t // include the definitions for the processor #include "osclconfig_ix86.h" // the syntax for explicitly calling the destructor varies on some platforms // below is the default syntax as defined by another ARM project #define OSCL_TEMPLATED_DESTRUCTOR_CALL(type,simple_type) ~type () #define __TFS__ <> #define OSCL_BEGIN_PACKED #define OSCL_PACKED_VAR(x) x __attribute__((packed)) #define OSCL_PACKED_STRUCT_BEGIN #define OSCL_PACKED_STRUCT_END __attribute__((packed)) #define OSCL_END_PACKED #define PVLOGGER_INST_LEVEL 0 #define PVLOGGER_ANDROIDLOG_LEVEL 0 //set this to 1 to enable OSCL_ASSERT in release builds. #define OSCL_ASSERT_ALWAYS 0 // check all osclconfig required macros are defined #include "osclconfig_check.h" #endif
[ "abgoyal@gmail.com" ]
abgoyal@gmail.com
daf1417011111be6b2a039f0b99f0ba7f9433720
d03d052c0ca220d06ec17d170e2b272f4e935a0c
/clang_x86/gen/mojo/public/interfaces/application/application_connector.mojom-common.h
e84aa0ab6f48de62010f3d876be6b8df74e738ec
[ "Apache-2.0" ]
permissive
amplab/ray-artifacts
f7ae0298fee371d9b33a40c00dae05c4442dc211
6954850f8ef581927df94be90313c1e783cd2e81
refs/heads/master
2023-07-07T20:45:43.526694
2016-08-06T19:53:55
2016-08-06T19:53:55
65,099,400
0
2
null
null
null
null
UTF-8
C++
false
false
8,858
h
// NOTE: This file was generated by the Mojo bindings generator. #ifndef MOJO_PUBLIC_INTERFACES_APPLICATION_APPLICATION_CONNECTOR_MOJOM_COMMON_H_ #define MOJO_PUBLIC_INTERFACES_APPLICATION_APPLICATION_CONNECTOR_MOJOM_COMMON_H_ #include <stdint.h> #include <iosfwd> #include "mojo/public/cpp/bindings/array.h" #include "mojo/public/cpp/bindings/callback.h" #include "mojo/public/cpp/bindings/interface_handle.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/map.h" #include "mojo/public/cpp/bindings/message_validator.h" #include "mojo/public/cpp/bindings/string.h" #include "mojo/public/cpp/bindings/struct_ptr.h" #include "mojo/public/cpp/system/buffer.h" #include "mojo/public/cpp/system/data_pipe.h" #include "mojo/public/cpp/system/handle.h" #include "mojo/public/cpp/system/message_pipe.h" #include "mojo/public/interfaces/application/application_connector.mojom-internal.h" #include "mojo/public/interfaces/application/service_provider.mojom-common.h" namespace mojo { // --- Interface Forward Declarations --- class ApplicationConnector; class ApplicationConnectorRequestValidator; class ApplicationConnector_Synchronous; // --- Struct Forward Declarations --- // --- Union Forward Declarations --- // --- Enums Declarations --- // --- Constants --- // --- Interface declarations --- namespace internal { class ApplicationConnector_Base { public: static const uint32_t Version_ = 0; using RequestValidator_ = ApplicationConnectorRequestValidator; using ResponseValidator_ = mojo::internal::PassThroughValidator; using Synchronous_ = ApplicationConnector_Synchronous; enum class MessageOrdinals : uint32_t { ConnectToApplication = 0, Duplicate = 1, }; virtual ~ApplicationConnector_Base() {} }; } // namespace internal // Async interface declaration class ApplicationConnectorProxy; class ApplicationConnectorStub; class ApplicationConnector_Synchronous; class ApplicationConnectorRequestValidator; class ApplicationConnector : public internal::ApplicationConnector_Base { public: virtual ~ApplicationConnector() override {} using Proxy_ = ApplicationConnectorProxy; using Stub_ = ApplicationConnectorStub; virtual void ConnectToApplication(const mojo::String& application_url, mojo::InterfaceRequest<mojo::ServiceProvider> services) = 0; virtual void Duplicate(mojo::InterfaceRequest<ApplicationConnector> application_connector_request) = 0; }; } // namespace mojo // --- Internal Template Specializations --- namespace mojo { namespace internal { } // internal } // mojo namespace mojo { // --- Interface Request Validators --- class ApplicationConnectorRequestValidator : public mojo::internal::MessageValidator { public: mojo::internal::ValidationError Validate(const mojo::Message* message, std::string* err) override; }; // --- Interface Response Validators --- // --- Interface enum operators --- // --- Unions --- // Unions must be declared first because they can be members of structs. // --- Inlined structs --- // --- Non-inlined structs --- // --- Struct serialization helpers --- // --- Union serialization helpers --- // --- Request and response parameter structs for Interface methods --- class ApplicationConnector_ConnectToApplication_Params; using ApplicationConnector_ConnectToApplication_ParamsPtr = mojo::StructPtr<ApplicationConnector_ConnectToApplication_Params>; size_t GetSerializedSize_(const ApplicationConnector_ConnectToApplication_Params& input); mojo::internal::ValidationError Serialize_( ApplicationConnector_ConnectToApplication_Params* input, mojo::internal::Buffer* buffer, internal::ApplicationConnector_ConnectToApplication_Params_Data** output); void Deserialize_(internal::ApplicationConnector_ConnectToApplication_Params_Data* input, ApplicationConnector_ConnectToApplication_Params* output); class ApplicationConnector_ConnectToApplication_Params { public: using Data_ = internal::ApplicationConnector_ConnectToApplication_Params_Data; static ApplicationConnector_ConnectToApplication_ParamsPtr New(); template <typename U> static ApplicationConnector_ConnectToApplication_ParamsPtr From(const U& u) { return mojo::TypeConverter<ApplicationConnector_ConnectToApplication_ParamsPtr, U>::Convert(u); } template <typename U> U To() const { return mojo::TypeConverter<U, ApplicationConnector_ConnectToApplication_Params>::Convert(*this); } ApplicationConnector_ConnectToApplication_Params(); ~ApplicationConnector_ConnectToApplication_Params(); // Returns the number of bytes it would take to serialize this struct's data. size_t GetSerializedSize() const; // Returns true on successful serialization. On failure, part of the data may // be serialized, until the point of failure. This API does not support // serializing handles. If not null, |bytes_written| is set to the number of // bytes written to |buf|, even if this function return false. // // TODO(vardhan): For now, we return true for success. Should we define a // public error type for serialization? Should we open up // internal::ValidationError? bool Serialize(void* buf, size_t buf_size, size_t* bytes_written = nullptr); // Deserializes the given |buf| of size |buf_size| representing a serialized // version of this struct. The buffer is validated before it is deserialized. // Returns true on successful deserialization. // TODO(vardhan): Recover the validation error if there is one? bool Deserialize(void* buf, size_t buf_size); // Deserializes the given |buf| representing a serialized version of this // struct. The buffer is NOT validated before it is deserialized, so the user // must be confident of its validity and that |buf| points to enough data to // finish deserializing. void DeserializeWithoutValidation(void* buf); bool Equals(const ApplicationConnector_ConnectToApplication_Params& other) const; mojo::String application_url; mojo::InterfaceRequest<mojo::ServiceProvider> services; }; class ApplicationConnector_Duplicate_Params; using ApplicationConnector_Duplicate_ParamsPtr = mojo::StructPtr<ApplicationConnector_Duplicate_Params>; size_t GetSerializedSize_(const ApplicationConnector_Duplicate_Params& input); mojo::internal::ValidationError Serialize_( ApplicationConnector_Duplicate_Params* input, mojo::internal::Buffer* buffer, internal::ApplicationConnector_Duplicate_Params_Data** output); void Deserialize_(internal::ApplicationConnector_Duplicate_Params_Data* input, ApplicationConnector_Duplicate_Params* output); class ApplicationConnector_Duplicate_Params { public: using Data_ = internal::ApplicationConnector_Duplicate_Params_Data; static ApplicationConnector_Duplicate_ParamsPtr New(); template <typename U> static ApplicationConnector_Duplicate_ParamsPtr From(const U& u) { return mojo::TypeConverter<ApplicationConnector_Duplicate_ParamsPtr, U>::Convert(u); } template <typename U> U To() const { return mojo::TypeConverter<U, ApplicationConnector_Duplicate_Params>::Convert(*this); } ApplicationConnector_Duplicate_Params(); ~ApplicationConnector_Duplicate_Params(); // Returns the number of bytes it would take to serialize this struct's data. size_t GetSerializedSize() const; // Returns true on successful serialization. On failure, part of the data may // be serialized, until the point of failure. This API does not support // serializing handles. If not null, |bytes_written| is set to the number of // bytes written to |buf|, even if this function return false. // // TODO(vardhan): For now, we return true for success. Should we define a // public error type for serialization? Should we open up // internal::ValidationError? bool Serialize(void* buf, size_t buf_size, size_t* bytes_written = nullptr); // Deserializes the given |buf| of size |buf_size| representing a serialized // version of this struct. The buffer is validated before it is deserialized. // Returns true on successful deserialization. // TODO(vardhan): Recover the validation error if there is one? bool Deserialize(void* buf, size_t buf_size); // Deserializes the given |buf| representing a serialized version of this // struct. The buffer is NOT validated before it is deserialized, so the user // must be confident of its validity and that |buf| points to enough data to // finish deserializing. void DeserializeWithoutValidation(void* buf); bool Equals(const ApplicationConnector_Duplicate_Params& other) const; mojo::InterfaceRequest<ApplicationConnector> application_connector_request; }; } // namespace mojo #endif // MOJO_PUBLIC_INTERFACES_APPLICATION_APPLICATION_CONNECTOR_MOJOM_COMMON_H_
[ "pcmoritz@gmail.com" ]
pcmoritz@gmail.com
1808c4ee11d3a8ed6c6c80c8a8babf18a9fbe968
3ad968797a01a4e4b9a87e2200eeb3fb47bf269a
/Ultimate TCP-IP/Security/Examples/Server/Echo/StdAfx.cpp
dbf537794d9fd92b4bad8962e53c976256a51ad4
[]
no_license
LittleDrogon/MFC-Examples
403641a1ae9b90e67fe242da3af6d9285698f10b
1d8b5d19033409cd89da3aba3ec1695802c89a7a
refs/heads/main
2023-03-20T22:53:02.590825
2020-12-31T09:56:37
2020-12-31T09:56:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
// stdafx.cpp : source file that includes just the standard includes // EchoServer.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "pkedpekr@gmail.com" ]
pkedpekr@gmail.com
de584f340dc73e14c0a831dad9ae96d3c30518b7
9df1684efcd7618f1dd46780274caacc1908433a
/infer/tests/codetoanalyze/cpp/nullable/example.cpp
91e05a3614473f3f3899242915d1f8074498b7a7
[ "MIT", "GPL-1.0-or-later" ]
permissive
Abd-Elrazek/infer
a9f02c971c0c80e1d419bf51665e9570f6716174
be4c5aaa0fc7cb2e259f1ad683c04c8cfa11875c
refs/heads/master
2020-04-15T05:08:20.331302
2019-01-07T08:01:29
2019-01-07T08:04:32
164,410,091
1
0
MIT
2019-05-25T17:09:51
2019-01-07T09:38:22
OCaml
UTF-8
C++
false
false
1,395
cpp
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ class T { private: int* unnanotated_field; int* _Nullable nullable_field; int* _Nonnull nonnull_field; public: void assign_nullable_field_to_null_okay() { nullable_field = nullptr; } public: void assign_unnanotated_field_to_null_bad() { unnanotated_field = nullptr; } public: void assign_nonnull_field_to_null_bad() { nonnull_field = nullptr; } public: void test_nullable_field_for_null_okay() { if (nullable_field == nullptr) { } } public: void test_unnanotated_field_for_null_bad() { if (unnanotated_field == nullptr) { } } public: void test_nonnull_field_for_null_bad() { if (nonnull_field == nullptr) { } } public: void dereference_unnanotated_field_okay() { *unnanotated_field = 42; } public: void dereference_nonnull_field_okay() { *nonnull_field = 42; } public: void dereference_nullable_field_bad() { *nullable_field = 42; } public: void dereference_unnanotated_field_after_test_for_null_bad() { if (unnanotated_field == nullptr) { *unnanotated_field = 42; } } public: void FP_dereference_nonnull_field_after_test_for_null_okay() { if (nonnull_field == nullptr) { *nonnull_field = 42; } } };
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
0db65adad7df12a718f3b6a687228d4206f03fab
813284b9dac4477f4893cb6b30ffafab8e181cc4
/src/qt/guiutil.h
86da5e103545252cdfef249ce1c222c65e25a708
[ "MIT" ]
permissive
phoenixkonsole/xbtx
609809c29c32e2c4373a26204480a0e2a9f0922e
2f9db3d0ca34103e315a5bc9ef2fa2d42cb71810
refs/heads/master
2023-05-11T17:37:28.762478
2023-05-03T09:54:14
2023-05-03T09:54:14
243,993,348
3
11
MIT
2023-05-03T09:54:15
2020-02-29T15:30:47
C++
UTF-8
C++
false
false
9,818
h
// Copyright (c) 2011-2016 The Bitcoin Core developers // Copyright (c) 2017 The BitcoinSubsidium Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BitcoinSubsidium_QT_GUIUTIL_H #define BitcoinSubsidium_QT_GUIUTIL_H #include "amount.h" #include "fs.h" #include <QEvent> #include <QHeaderView> #include <QMessageBox> #include <QObject> #include <QProgressBar> #include <QString> #include <QTableView> #include <QLabel> class QValidatedLineEdit; class SendCoinsRecipient; QT_BEGIN_NAMESPACE class QAbstractItemView; class QDateTime; class QFont; class QLineEdit; class QUrl; class QWidget; class QGraphicsDropShadowEffect; QT_END_NAMESPACE /** Utility functions used by the BitcoinSubsidium Qt UI. */ namespace GUIUtil { // Get the font for the sub labels QFont getSubLabelFont(); QFont getSubLabelFontBolded(); // Get the font for the main labels QFont getTopLabelFont(); QFont getTopLabelFontBolded(); QFont getTopLabelFont(int weight, int pxsize); QGraphicsDropShadowEffect* getShadowEffect(); // Create human-readable string from date QString dateTimeStr(const QDateTime &datetime); QString dateTimeStr(qint64 nTime); // Return a monospace font QFont fixedPitchFont(); // Set up widgets for address and amounts void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent); void setupAmountWidget(QLineEdit *widget, QWidget *parent); // Parse "BitcoinSubsidium:" URI into recipient object, return true on successful parsing bool parseBitcoinSubsidiumURI(const QUrl &uri, SendCoinsRecipient *out); bool parseBitcoinSubsidiumURI(QString uri, SendCoinsRecipient *out); QString formatBitcoinSubsidiumURI(const SendCoinsRecipient &info); // Returns true if given address+amount meets "dust" definition bool isDust(const QString& address, const CAmount& amount); // HTML escaping for rich text controls QString HtmlEscape(const QString& str, bool fMultiLine=false); QString HtmlEscape(const std::string& str, bool fMultiLine=false); /** Copy a field of the currently selected entry of a view to the clipboard. Does nothing if nothing is selected. @param[in] column Data column to extract from the model @param[in] role Data role to extract from the model @see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress */ void copyEntryData(QAbstractItemView *view, int column, int role=Qt::EditRole); /** Return a field of the currently selected entry as a QString. Does nothing if nothing is selected. @param[in] column Data column to extract from the model @see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress */ QList<QModelIndex> getEntryData(QAbstractItemView *view, int column); void setClipboard(const QString& str); /** Get save filename, mimics QFileDialog::getSaveFileName, except that it appends a default suffix when no suffix is provided by the user. @param[in] parent Parent window (or 0) @param[in] caption Window caption (or empty, for default) @param[in] dir Starting directory (or empty, to default to documents directory) @param[in] filter Filter specification such as "Comma Separated Files (*.csv)" @param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0). Can be useful when choosing the save file format based on suffix. */ QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut); /** Get open filename, convenience wrapper for QFileDialog::getOpenFileName. @param[in] parent Parent window (or 0) @param[in] caption Window caption (or empty, for default) @param[in] dir Starting directory (or empty, to default to documents directory) @param[in] filter Filter specification such as "Comma Separated Files (*.csv)" @param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0). Can be useful when choosing the save file format based on suffix. */ QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut); /** Get connection type to call object slot in GUI thread with invokeMethod. The call will be blocking. @returns If called from the GUI thread, return a Qt::DirectConnection. If called from another thread, return a Qt::BlockingQueuedConnection. */ Qt::ConnectionType blockingGUIThreadConnection(); // Determine whether a widget is hidden behind other windows bool isObscured(QWidget *w); // Open debug.log void openDebugLogfile(); // Open the config file bool openBitcoinSubsidiumConf(); // Replace invalid default fonts with known good ones void SubstituteFonts(const QString& language); // Concatenate a string given the painter, static text width, left side of rect, and right side of rect // and which side the concatenated string is on (default left) void concatenate(QPainter* painter, QString& strToCon, int static_width, int left_side, int right_size); /** Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text representation if needed. This assures that Qt can word-wrap long tooltip messages. Tooltips longer than the provided size threshold (in characters) are wrapped. */ class ToolTipToRichTextFilter : public QObject { Q_OBJECT public: explicit ToolTipToRichTextFilter(int size_threshold, QObject *parent = 0); protected: bool eventFilter(QObject *obj, QEvent *evt); private: int size_threshold; }; /** * Makes a QTableView last column feel as if it was being resized from its left border. * Also makes sure the column widths are never larger than the table's viewport. * In Qt, all columns are resizable from the right, but it's not intuitive resizing the last column from the right. * Usually our second to last columns behave as if stretched, and when on strech mode, columns aren't resizable * interactively or programmatically. * * This helper object takes care of this issue. * */ class TableViewLastColumnResizingFixer: public QObject { Q_OBJECT public: TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent); void stretchColumnWidth(int column); private: QTableView* tableView; int lastColumnMinimumWidth; int allColumnsMinimumWidth; int lastColumnIndex; int columnCount; int secondToLastColumnIndex; void adjustTableColumnsWidth(); int getAvailableWidthForColumn(int column); int getColumnsWidth(); void connectViewHeadersSignals(); void disconnectViewHeadersSignals(); void setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode); void resizeColumn(int nColumnIndex, int width); private Q_SLOTS: void on_sectionResized(int logicalIndex, int oldSize, int newSize); void on_geometriesChanged(); }; bool GetStartOnSystemStartup(); bool SetStartOnSystemStartup(bool fAutoStart); /* Convert QString to OS specific boost path through UTF-8 */ fs::path qstringToBoostPath(const QString &path); /* Convert OS specific boost path to QString through UTF-8 */ QString boostPathToQString(const fs::path &path); /* Convert seconds into a QString with days, hours, mins, secs */ QString formatDurationStr(int secs); /* Format CNodeStats.nServices bitmask into a user-readable string */ QString formatServicesStr(quint64 mask); /* Format a CNodeCombinedStats.dPingTime into a user-readable string or display N/A, if 0*/ QString formatPingTime(double dPingTime); /* Format a CNodeCombinedStats.nTimeOffset into a user-readable string. */ QString formatTimeOffset(int64_t nTimeOffset); QString formatNiceTimeOffset(qint64 secs); QString formatBytes(uint64_t bytes); class ClickableLabel : public QLabel { Q_OBJECT Q_SIGNALS: /** Emitted when the label is clicked. The relative mouse coordinates of the click are * passed to the signal. */ void clicked(const QPoint& point); protected: void mouseReleaseEvent(QMouseEvent *event); }; class ClickableProgressBar : public QProgressBar { Q_OBJECT Q_SIGNALS: /** Emitted when the progressbar is clicked. The relative mouse coordinates of the click are * passed to the signal. */ void clicked(const QPoint& point); protected: void mouseReleaseEvent(QMouseEvent *event); }; #if defined(Q_OS_MAC) && QT_VERSION >= 0x050000 // workaround for Qt OSX Bug: // https://bugreports.qt-project.org/browse/QTBUG-15631 // QProgressBar uses around 10% CPU even when app is in background class ProgressBar : public ClickableProgressBar { bool event(QEvent *e) { return (e->type() != QEvent::StyleAnimationUpdate) ? QProgressBar::event(e) : false; } }; #else typedef ClickableProgressBar ProgressBar; #endif } // namespace GUIUtil #endif // BitcoinSubsidium_QT_GUIUTIL_H
[ "william.kibbler@googlemail.com" ]
william.kibbler@googlemail.com
5be211fd74576b7e73e66a860297b44757c22e53
4b3dee7793db94fcb5eedca5f0b39b4bc4364017
/engine/FontRenderer.cpp
36a0aaa660959570b010155585ca9da5679a88c6
[]
no_license
shenchi/code_blank
33917d1d3b19ca506accfd58fe3443bc6cf56eed
74d775b557f268f84ea1bf75301aa5b5612aa661
refs/heads/master
2021-09-14T02:13:21.562526
2018-05-04T20:34:40
2018-05-04T20:34:40
115,167,180
0
1
null
2017-12-30T11:40:07
2017-12-23T03:20:51
C++
UTF-8
C++
false
false
6,565
cpp
#include "FontRenderer.h" #include "Renderer.h" #include "MemoryAllocator.h" #include <cstring> #include "TofuMath.h" extern "C" { #include <fontstash.h> } namespace { using namespace tofu; int TofuRenderCreate(void* userPtr, int width, int height) { FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr); CreateTextureParams* params = MemoryAllocator::FrameAlloc<CreateTextureParams>(); params->InitAsTexture2D(ctx->tex, width, height, kFormatR8Unorm); ctx->cmdBuf->Add(RendererCommand::kCommandCreateTexture, params); ctx->width = width; ctx->height = height; return 1; } int TofuRenderResize(void* userPtr, int width, int height) { FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr); ctx->cmdBuf->Add(RendererCommand::kCommandDestroyTexture, &(ctx->tex)); if (1 != TofuRenderCreate(userPtr, width, height)) { return 0; } ctx->updateRectX = 0; ctx->updateRectY = 0; ctx->updateRectW = ctx->width; ctx->updateRectH = ctx->height; return 1; } void TofuRenderUpdate(void* userPtr, int* rect, const unsigned char* data) { FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr); int w = rect[2] - rect[0]; int h = rect[3] - rect[1]; if (!ctx->tex) return; ctx->texData = data; if (ctx->updateRectW == 0 || ctx->updateRectH == 0) { ctx->updateRectX = rect[0]; ctx->updateRectY = rect[1]; ctx->updateRectW = w; ctx->updateRectH = h; } else { int left = ctx->updateRectX; int top = ctx->updateRectY; int right = ctx->updateRectX + ctx->updateRectW; int bottom = ctx->updateRectY + ctx->updateRectH; left = math::min(left, rect[0]); top = math::min(top, rect[1]); right = math::max(right, rect[2]); bottom = math::max(bottom, rect[3]); ctx->updateRectX = left; ctx->updateRectY = top; ctx->updateRectW = right - left; ctx->updateRectH = bottom - top; } } void TofuRenderDraw(void* userPtr, const float* verts, const float* tcoords, const unsigned int* colors, int nverts) { FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr); if (ctx->numVerts + nverts > ctx->maxVerts) return; for (uint32_t i = 0; i < nverts; i++) { uint16_t vid = uint16_t(ctx->numVerts + i); float* vert = ctx->vertices + (vid * 9); *(vert + 0) = verts[i * 2 + 0]; *(vert + 1) = verts[i * 2 + 1]; *(vert + 2) = 0.0f; *(vert + 3) = 1.0f; *(vert + 4) = 1.0f; *(vert + 5) = 1.0f; *(vert + 6) = 1.0f; *(vert + 7) = tcoords[i * 2 + 0]; *(vert + 8) = tcoords[i * 2 + 1]; } ctx->numVerts += nverts; } void TofuRenderDelete(void* userPtr) { FontRendererContext* ctx = reinterpret_cast<FontRendererContext*>(userPtr); ctx->cmdBuf->Add(RendererCommand::kCommandDestroyTexture, &(ctx->tex)); } } namespace tofu { int32_t FontRenderer::Setup(PipelineStateHandle pso, TextureHandle tex, SamplerHandle samp, BufferHandle vb, BufferHandle cb, uint32_t maxVertices) { this->pso = pso; context.tex = tex; this->samp = samp; this->vb = vb; this->cb = cb; context.maxVerts = maxVertices; return kOK; } int32_t FontRenderer::Init() { FONSparams params = {}; params.width = 1024; params.height = 1024; params.flags = FONS_ZERO_TOPLEFT; params.userPtr = &context; params.renderCreate = TofuRenderCreate; params.renderResize = TofuRenderResize; params.renderUpdate = TofuRenderUpdate; params.renderDraw = TofuRenderDraw; params.renderDelete = TofuRenderDelete; fonsContext = fonsCreateInternal(&params); if (nullptr == fonsContext) return kErrUnknown; font = fonsAddFont(fonsContext, "Conthrax Sb", "assets/conthrax-sb.ttf"); //font = fonsAddFont(fonsContext, "Arial Regular", "C:\\Windows\\Fonts\\arial.ttf"); //font = fonsAddFont(fonsContext, "sans", "D:\\DroidSerif-Regular.ttf"); if (font == FONS_INVALID) { return kErrUnknown; } return kOK; } int32_t FontRenderer::Shutdown() { fonsDeleteInternal(fonsContext); return kOK; } int32_t FontRenderer::Reset(RendererCommandBuffer* cmdBuf) { //if (nullptr == fonsContext) return kOK; context.cmdBuf = cmdBuf; context.vertices = reinterpret_cast<float*>( MemoryAllocator::FrameAlloc(context.maxVerts * sizeof(float) * 9u) ); context.numVerts = 0; context.texData = nullptr; context.updateRectX = 0; context.updateRectY = 0; context.updateRectW = 0; context.updateRectH = 0; return kOK; } int32_t FontRenderer::Render(const char * text, float x, float y) { float lh = 0; fonsClearState(fonsContext); fonsSetSize(fonsContext, 18.0f); fonsSetFont(fonsContext, font); fonsVertMetrics(fonsContext, nullptr, nullptr, &lh); fonsSetColor(fonsContext, 0xffffffffu); x = fonsDrawText(fonsContext, x, y + lh, text, nullptr); return kOK; } int32_t FontRenderer::UploadTexture() { if (nullptr != context.texData && context.updateRectW > 0 && context.updateRectH > 0) { uint8_t* ptr = const_cast<uint8_t*>(context.texData); ptr += context.updateRectX + context.updateRectY * context.width; UpdateTextureParams* params = MemoryAllocator::FrameAlloc<UpdateTextureParams>(); params->handle = context.tex; params->data = ptr; params->pitch = context.width; params->left = context.updateRectX; params->top = context.updateRectY; params->right = context.updateRectX + context.updateRectW; params->bottom = context.updateRectY + context.updateRectH; params->front = 0; params->back = 1; context.cmdBuf->Add(RendererCommand::kCommandUpdateTexture, params); context.texData = nullptr; context.updateRectX = 0; context.updateRectY = 0; context.updateRectW = 0; context.updateRectH = 0; } return kOK; } int32_t FontRenderer::Submit() { if (context.numVerts == 0) return kOK; { UpdateBufferParams* params = MemoryAllocator::FrameAlloc<UpdateBufferParams>(); params->handle = vb; params->data = context.vertices; params->size = context.numVerts * sizeof(float) * 9u; context.cmdBuf->Add(RendererCommand::kCommandUpdateBuffer, params); } { DrawParams* params = MemoryAllocator::FrameAlloc<DrawParams>(); params->pipelineState = pso; params->vertexBuffer = vb; params->indexBuffer = BufferHandle(); params->vsConstantBuffers[0] = { cb, 0, 0 }; params->psShaderResources[0] = context.tex; params->psSamplers[0] = samp; params->indexCount = context.numVerts; context.cmdBuf->Add(RendererCommand::kCommandDraw, params); } return kOK; } }
[ "shenchi710@gmail.com" ]
shenchi710@gmail.com
7419442508a500f232d865e2c1b51b43542b2203
2fd1b8e948e3afb85534c4e3ec73939cfc93b51c
/Analyzer/PPCoincMap.h
85a6588e94a17f5d57f9a460ec8f6ed693b25cd5
[]
no_license
jrtomps/phdwork
0b6f7f7cccbbd0cffd969a9a445339f69528ae16
7fa546aa65e631c1a1922c143bcae43c9f4bff1c
refs/heads/master
2020-12-24T07:35:31.384799
2016-10-29T02:15:05
2016-10-29T02:15:05
56,644,636
0
0
null
null
null
null
UTF-8
C++
false
false
3,912
h
// PPCoincMap.h // // Author : Jeromy Tompkins // Date : 7/13/2010 // // Purpose: To implement a version of plot.C that runs PROOF #ifndef PPCoincMap_h #define PPCoincMap_h #include <iostream> #include <vector> #include <utility> #include "TH1.h" #include "TH2.h" #include "TCutG.h" #include "ConfigManager.h" #include "ConfigEntry.h" #include "TBranch.h" #include "TLine.h" #include "TChain.h" #include "TSelector.h" /* class PPCoincMap; */ class PPCoincMap : public TSelector { public: std::vector<Float_t> fPed; std::vector<Float_t> fThresh; std::vector<Float_t> fLowCut; std::vector<Float_t> fHighCut; std::vector<Float_t> fLowCut2; std::vector<Float_t> fHighCut2; std::vector<Float_t> fLowCut3; std::vector<Float_t> fHighCut3; std::vector<Float_t> fLowTOFCut; std::vector<Float_t> fHighTOFCut; std::vector<Float_t> fPedThresh; TTree *fChain; //!pointer to the analyzed TTree or TChain Int_t runcount; Int_t nentries; ConfigManager cm; ConfigEntry *pce; Double_t bpmval; Double_t tdcval; Double_t bpm_calib; Double_t desired_max_ph; TH2D* coinc_map_aa; TH2D* coinc_map_ff; TH2D* coinc_map_fa; TH2D* coinc_map_mult_a; TH2D* coinc_map_mult_f; TH1D* coinc_map_anota; TH1D* coinc_map_fnota; TH1D* coinc_mult_a; TH1D* coinc_mult_f; std::vector<Bool_t> adc_vals_a; std::vector<Bool_t> adc_vals_f; std::vector<Int_t> runnumber; std::vector<Int_t> starttime; std::vector<Int_t> endtime; std::vector<Int_t> n_phys_events; std::vector<Int_t> max_clock; std::vector<Float_t> adc_edge; // Declaration of leaf types Int_t nt_evtype; Double_t nt_bpm; Int_t nt_evnum; Int_t nt_run; Double_t nt_trigger; Double_t nt_clock; Double_t VetoClock; Double_t FinalClock; Double_t FinalVetoClock; std::vector<Double_t> nt_tdc; std::vector<Double_t> nt_adc; // Declaration of branches TBranch* b_evnum; //! TBranch* b_run; //! TBranch* b_start; //! TBranch* b_end; //! TBranch* b_nphyev; //! TBranch* b_evtype; //! TBranch* b_latch; //! TBranch* b_bpm; //! TBranch* b_trigger; //! std::vector<TBranch*> b_tdc; std::vector<TBranch*> b_adc; std::vector<TBranch*> b_tac; PPCoincMap(ConfigEntry* ce, bool save=true); PPCoincMap(PPCoincMap const& obj); virtual ~PPCoincMap(); virtual Int_t Version() const { return 3;} virtual void Begin(TTree *tree); virtual void SlaveBegin(TTree *tree); virtual void Init(TTree *tree); virtual Bool_t Notify() { #ifdef DEBUG std::cout << "notify" << std::endl; #endif return kTRUE; } virtual Bool_t Process(Long64_t entry); virtual Int_t GetEntry(Long64_t entry, Int_t getall = 0) { return fChain ? fChain->GetTree()->GetEntry(entry, getall) : 0; } virtual void SetOption(const char *option) { fOption = option; } virtual void SetObject(TObject *obj) { fObject = obj; } virtual void SetInputList(TList *input) { fInput = input; } virtual TList* GetOutputList() const { return fOutput; } virtual void SlaveTerminate(); virtual void Terminate(); void LoadSettings(ConfigEntry *dbentry); UInt_t FindNonZeroBin(std::vector<Bool_t>& vec); void SafeDeleteTH2D(TH2D* h); void SafeDeleteTH1D(TH1D* h); protected: static const Char_t* outfname_base; Bool_t willSave; Int_t ndet; Int_t nadc_ch; Int_t ntdc_ch; Int_t incr; Int_t incr1; UInt_t multiplicity_a; UInt_t multiplicity_f; UInt_t mult_mismatch; private: ClassDef(PPCoincMap,0); }; #endif
[ "tompkins@nscl.msu.edu" ]
tompkins@nscl.msu.edu
a0125e07ce2e3323a4e762db9f8b98c7e1794aad
e30253dd5b8e508d37c680b34740add366f16c73
/Libraries/xcassets/Sources/StickerDurationType.cpp
bc6a4851c46ea115bd1464e8baefb8c27fb0944d
[ "LicenseRef-scancode-philippe-de-muyter", "BSD-3-Clause", "NCSA", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
darlinghq/xcbuild
e77e8d88ed42f1922afd7abad2a4508c18255a88
a903c6952fc5617816113cbb7b551ac701dba2ff
refs/heads/master
2023-08-03T03:18:18.383673
2023-07-26T18:15:17
2023-07-26T18:15:17
131,655,910
10
2
null
2018-04-30T23:15:55
2018-04-30T23:15:54
null
UTF-8
C++
false
false
1,089
cpp
/** Copyright (c) 2015-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #include <xcassets/StickerDurationType.h> #include <cstdlib> using xcassets::StickerDurationType; using xcassets::StickerDurationTypes; ext::optional<StickerDurationType> StickerDurationTypes:: Parse(std::string const &value) { if (value == "fixed") { return StickerDurationType::Fixed; } else if (value == "fps") { return StickerDurationType::FPS; } else { fprintf(stderr, "warning: unknown sticker duration type %s\n", value.c_str()); return ext::nullopt; } } std::string StickerDurationTypes:: String(StickerDurationType stickerDurationType) { switch (stickerDurationType) { case StickerDurationType::Fixed: return "fixed"; case StickerDurationType::FPS: return "fps"; } abort(); }
[ "github@grantpaul.com" ]
github@grantpaul.com
aaac4873959d0b3cee5a483ab3bb0139f7c746ab
485d20ffb43ddced64d6508ea770c874325ed2ad
/current/sceneManager/src/testApp.h
5dcda885439c680d309be7a1da94d86406cae0fa
[]
no_license
firmread/aynir
16af463e26ad72e313814260b0accd1ff475df03
d625f1a8b6785daee49951521cc192dc14311678
refs/heads/master
2021-01-24T23:36:00.262194
2013-05-13T01:49:38
2013-05-13T01:49:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
921
h
#define SCENE_NUMBER 5 #pragma once #include "ofMain.h" #include "ofxiPhone.h" #include "ofxiPhoneExtras.h" #include "baseScene.h" #include "openingScene.h" #include "springScene.h" //example scenes #include "circleScene.h" #include "squareScene.h" #include "imageScene.h" class testApp : public ofxiPhoneApp{ public: void setup(); void update(); void draw(); void exit(); void touchDown(ofTouchEventArgs & touch); void touchMoved(ofTouchEventArgs & touch); void touchUp(ofTouchEventArgs & touch); void touchDoubleTap(ofTouchEventArgs & touch); void touchCancelled(ofTouchEventArgs & touch); void lostFocus(); void gotFocus(); void gotMemoryWarning(); void deviceOrientationChanged(int newOrientation); baseScene * scenes[SCENE_NUMBER]; int currentScene; };
[ "litchirhythm@gmail.com" ]
litchirhythm@gmail.com
cae3a82e1c8b4a288e2b6e0d45dedd981bd9a457
6b8fff0eeb75ad266af0ec2b9e9aaf28462c2a73
/Sapi_Dataset/Data/user13/labor9/feladat1/Worker.h
aef6e50fcc31bf87eecbfa24635428636aad4991
[]
no_license
kotunde/SourceFileAnalyzer_featureSearch_and_classification
030ab8e39dd79bcc029b38d68760c6366d425df5
9a3467e6aae5455142bc7a5805787f9b17112d17
refs/heads/master
2020-09-22T04:04:41.722623
2019-12-07T11:59:06
2019-12-07T11:59:06
225,040,703
0
1
null
null
null
null
UTF-8
C++
false
false
300
h
#pragma once #ifndef WORKER_H #define WORKER_H #include <iostream> #include <string> #include "Szemely.h" using namespace std; class Worker:public Person { protected: string job; public: Worker(string fisrt,string last,int bDate,string job); void print(ostream& out); }; #endif
[ "tundekoncsard3566@gmail.com" ]
tundekoncsard3566@gmail.com
88087f95de061577d20c091a403a36e25439d0ec
3300d25038f1441eda24c902c28703f8f11469f3
/asg4/code/protocol.h
b96785cd04fcbfba359dd1c4c5ab6a359161132f
[]
no_license
RishabJain27/Advanced-Programming
129490108edaa70bce8890ff778bf65b164b6bd8
dee76e68e5af0c92f4b5a199cfc658caaba6568e
refs/heads/master
2020-09-20T02:38:24.436044
2019-11-27T06:22:52
2019-11-27T06:22:52
224,359,002
0
0
null
null
null
null
UTF-8
C++
false
false
921
h
//Rhea Lingaiah rlingaia //Rishab Jain rjain9 #ifndef __PROTOCOL__H__ #define __PROTOCOL__H__ #include <cstdint> #include <cstring> #include <iostream> using namespace std; #include "sockets.h" enum class cix_command : uint8_t { ERROR = 0, EXIT, GET, HELP, LS, PUT, RM, FILEOUT, LSOUT, ACK, NAK, }; constexpr size_t FILENAME_SIZE = 59; constexpr size_t HEADER_SIZE = 64; struct cix_header { uint32_t nbytes {}; cix_command command {cix_command::ERROR}; char filename[FILENAME_SIZE] {}; }; void send_packet (base_socket& socket, const void* buffer, size_t bufsize); void recv_packet (base_socket& socket, void* buffer, size_t bufsize); ostream& operator<< (ostream& out, const cix_header& header); string get_cix_server_host (const vector<string>& args, size_t index); in_port_t get_cix_server_port (const vector<string>& args, size_t index); #endif
[ "rjain9@ucsc.edu" ]
rjain9@ucsc.edu
003e7987e97b70b0f8113b92779af6b2e1710172
46ecae56f6d7e37b00fe2a9e676d62928fff343e
/code/log.cpp
1d1207f80f3194873970016ff05b47a31d8f8e95
[]
no_license
chuckrector/vccnow
5da617ad5392b1f5b85bf604c4cc1471439e98b9
659568dcf08f1730268c3e9d5ee2d8f6d1d78da2
refs/heads/master
2022-11-11T08:07:12.167187
2020-06-28T19:10:33
2020-06-28T19:10:33
262,224,045
0
1
null
2020-06-28T19:10:35
2020-05-08T04:08:37
C++
UTF-8
C++
false
false
524
cpp
#include "log.hpp" #include "types.hpp" #include <stdarg.h> void Fail(char *Format, ...) { printf("FAIL\n"); va_list Args; va_start(Args, Format); vprintf(Format, Args); va_end(Args); *(int *)0 = 0; // exit(-1); } void Log(char *Format, ...) { va_list Args; va_start(Args, Format); vprintf(Format, Args); va_end(Args); } void DebugLog(DebugLevel_e Level, char *Format, ...) { if (Level > DebugLevel) return; va_list Args; va_start(Args, Format); vprintf(Format, Args); va_end(Args); }
[ "choosetheforce@gmail.com" ]
choosetheforce@gmail.com
7734e933e1d53b4df824c9485dea02fc78fe6368
0033659a033b4afac9b93c0ac80b8918a5ff9779
/game/server/hl2/hl2_player.cpp
0418912d710f678c8d6b94b9e83dcda5e07f28fc
[]
no_license
jonnyboy0719/situation-outbreak-two
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
50037e27e738ff78115faea84e235f865c61a68f
refs/heads/master
2021-01-10T09:59:39.214171
2011-01-11T01:15:33
2011-01-11T01:15:33
53,858,955
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
114,976
cpp
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Player for HL2. // //=============================================================================// #include "cbase.h" #include "hl2_player.h" #include "globalstate.h" #include "game.h" #include "gamerules.h" #include "trains.h" #include "basehlcombatweapon_shared.h" #include "vcollide_parse.h" #include "in_buttons.h" #include "ai_interactions.h" #include "ai_squad.h" #include "igamemovement.h" #include "ai_hull.h" #include "hl2_shareddefs.h" #include "info_camera_link.h" #include "point_camera.h" #include "engine/IEngineSound.h" #include "ndebugoverlay.h" #include "iservervehicle.h" #include "IVehicle.h" #include "globals.h" #include "collisionutils.h" #include "coordsize.h" #include "effect_color_tables.h" #include "vphysics/player_controller.h" #include "player_pickup.h" #include "weapon_physcannon.h" #include "script_intro.h" #include "effect_dispatch_data.h" #include "te_effect_dispatch.h" #include "ai_basenpc.h" #include "AI_Criteria.h" #include "npc_barnacle.h" #include "entitylist.h" #include "env_zoom.h" #include "hl2_gamerules.h" #include "prop_combine_ball.h" #include "datacache/imdlcache.h" #include "eventqueue.h" #include "GameStats.h" #include "filters.h" #include "tier0/icommandline.h" #ifdef HL2_EPISODIC #include "npc_alyx_episodic.h" #endif ///// // SO2 - James // Do not allow players to fire weapons while sprinting // Base each player's speed on their health #include "so_player.h" ///// // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern ConVar weapon_showproficiency; extern ConVar autoaim_max_dist; // Do not touch with without seeing me, please! (sjb) // For consistency's sake, enemy gunfire is traced against a scaled down // version of the player's hull, not the hitboxes for the player's model // because the player isn't aware of his model, and can't do anything about // preventing headshots and other such things. Also, game difficulty will // not change if the model changes. This is the value by which to scale // the X/Y of the player's hull to get the volume to trace bullets against. #define PLAYER_HULL_REDUCTION 0.70 // This switches between the single primary weapon, and multiple weapons with buckets approach (jdw) #define HL2_SINGLE_PRIMARY_WEAPON_MODE 0 #define TIME_IGNORE_FALL_DAMAGE 10.0 extern int gEvilImpulse101; ConVar sv_autojump( "sv_autojump", "0" ); ConVar hl2_walkspeed( "hl2_walkspeed", "150" ); ConVar hl2_normspeed( "hl2_normspeed", "190" ); ConVar hl2_sprintspeed( "hl2_sprintspeed", "320" ); ConVar hl2_darkness_flashlight_factor ( "hl2_darkness_flashlight_factor", "1" ); #ifdef HL2MP ///// // SO2 - James // Base each player's speed on their health /*#define HL2_WALK_SPEED 150 #define HL2_NORM_SPEED 190 #define HL2_SPRINT_SPEED 320*/ #define HL2_WALK_SPEED SO_WALK_SPEED #define HL2_NORM_SPEED SO_NORM_SPEED #define HL2_SPRINT_SPEED SO_SPRINT_SPEED ///// #else #define HL2_WALK_SPEED hl2_walkspeed.GetFloat() #define HL2_NORM_SPEED hl2_normspeed.GetFloat() #define HL2_SPRINT_SPEED hl2_sprintspeed.GetFloat() #endif ConVar player_showpredictedposition( "player_showpredictedposition", "0" ); ConVar player_showpredictedposition_timestep( "player_showpredictedposition_timestep", "1.0" ); ConVar player_squad_transient_commands( "player_squad_transient_commands", "1", FCVAR_REPLICATED ); ConVar player_squad_double_tap_time( "player_squad_double_tap_time", "0.25" ); ConVar sv_infinite_aux_power( "sv_infinite_aux_power", "0", FCVAR_CHEAT ); ConVar autoaim_unlock_target( "autoaim_unlock_target", "0.8666" ); ConVar sv_stickysprint("sv_stickysprint", "0", FCVAR_ARCHIVE | FCVAR_ARCHIVE_XBOX); #define FLASH_DRAIN_TIME 1.1111 // 100 units / 90 secs #define FLASH_CHARGE_TIME 50.0f // 100 units / 2 secs //============================================================================================== // CAPPED PLAYER PHYSICS DAMAGE TABLE //============================================================================================== static impactentry_t cappedPlayerLinearTable[] = { { 150*150, 5 }, { 250*250, 10 }, { 450*450, 20 }, { 550*550, 30 }, //{ 700*700, 100 }, //{ 1000*1000, 500 }, }; static impactentry_t cappedPlayerAngularTable[] = { { 100*100, 10 }, { 150*150, 20 }, { 200*200, 30 }, //{ 300*300, 500 }, }; static impactdamagetable_t gCappedPlayerImpactDamageTable = { cappedPlayerLinearTable, cappedPlayerAngularTable, ARRAYSIZE(cappedPlayerLinearTable), ARRAYSIZE(cappedPlayerAngularTable), 24*24.0f, // minimum linear speed 360*360.0f, // minimum angular speed 2.0f, // can't take damage from anything under 2kg 5.0f, // anything less than 5kg is "small" 5.0f, // never take more than 5 pts of damage from anything under 5kg 36*36.0f, // <5kg objects must go faster than 36 in/s to do damage 0.0f, // large mass in kg (no large mass effects) 1.0f, // large mass scale 2.0f, // large mass falling scale 320.0f, // min velocity for player speed to cause damage }; // Flashlight utility bool g_bCacheLegacyFlashlightStatus = true; bool g_bUseLegacyFlashlight; bool Flashlight_UseLegacyVersion( void ) { // If this is the first run through, cache off what the answer should be (cannot change during a session) if ( g_bCacheLegacyFlashlightStatus ) { char modDir[MAX_PATH]; if ( UTIL_GetModDir( modDir, sizeof(modDir) ) == false ) return false; g_bUseLegacyFlashlight = ( !Q_strcmp( modDir, "hl2" ) || !Q_strcmp( modDir, "episodic" ) ); g_bCacheLegacyFlashlightStatus = false; } // Return the results return g_bUseLegacyFlashlight; } //----------------------------------------------------------------------------- // Purpose: Used to relay outputs/inputs from the player to the world and viceversa //----------------------------------------------------------------------------- class CLogicPlayerProxy : public CLogicalEntity { DECLARE_CLASS( CLogicPlayerProxy, CLogicalEntity ); private: DECLARE_DATADESC(); public: COutputEvent m_OnFlashlightOn; COutputEvent m_OnFlashlightOff; COutputEvent m_PlayerHasAmmo; COutputEvent m_PlayerHasNoAmmo; COutputEvent m_PlayerDied; COutputEvent m_PlayerMissedAR2AltFire; // Player fired a combine ball which did not dissolve any enemies. COutputInt m_RequestedPlayerHealth; void InputRequestPlayerHealth( inputdata_t &inputdata ); void InputSetFlashlightSlowDrain( inputdata_t &inputdata ); void InputSetFlashlightNormalDrain( inputdata_t &inputdata ); void InputSetPlayerHealth( inputdata_t &inputdata ); void InputRequestAmmoState( inputdata_t &inputdata ); void InputLowerWeapon( inputdata_t &inputdata ); void InputEnableCappedPhysicsDamage( inputdata_t &inputdata ); void InputDisableCappedPhysicsDamage( inputdata_t &inputdata ); void InputSetLocatorTargetEntity( inputdata_t &inputdata ); void Activate ( void ); bool PassesDamageFilter( const CTakeDamageInfo &info ); EHANDLE m_hPlayer; }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CC_ToggleZoom( void ) { CBasePlayer* pPlayer = UTIL_GetCommandClient(); if( pPlayer ) { CHL2_Player *pHL2Player = dynamic_cast<CHL2_Player*>(pPlayer); if( pHL2Player && pHL2Player->IsSuitEquipped() ) { pHL2Player->ToggleZoom(); } } } static ConCommand toggle_zoom("toggle_zoom", CC_ToggleZoom, "Toggles zoom display" ); // ConVar cl_forwardspeed( "cl_forwardspeed", "400", FCVAR_CHEAT ); // Links us to the client's version ConVar xc_crouch_range( "xc_crouch_range", "0.85", FCVAR_ARCHIVE, "Percentarge [1..0] of joystick range to allow ducking within" ); // Only 1/2 of the range is used ConVar xc_use_crouch_limiter( "xc_use_crouch_limiter", "0", FCVAR_ARCHIVE, "Use the crouch limiting logic on the controller" ); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CC_ToggleDuck( void ) { CBasePlayer* pPlayer = UTIL_GetCommandClient(); if ( pPlayer == NULL ) return; // Cannot be frozen if ( pPlayer->GetFlags() & FL_FROZEN ) return; static bool bChecked = false; static ConVar *pCVcl_forwardspeed = NULL; if ( !bChecked ) { bChecked = true; pCVcl_forwardspeed = ( ConVar * )cvar->FindVar( "cl_forwardspeed" ); } // If we're not ducked, do extra checking if ( xc_use_crouch_limiter.GetBool() ) { if ( pPlayer->GetToggledDuckState() == false ) { float flForwardSpeed = 400.0f; if ( pCVcl_forwardspeed ) { flForwardSpeed = pCVcl_forwardspeed->GetFloat(); } flForwardSpeed = max( 1.0f, flForwardSpeed ); // Make sure we're not in the blindspot on the crouch detection float flStickDistPerc = ( pPlayer->GetStickDist() / flForwardSpeed ); // Speed is the magnitude if ( flStickDistPerc > xc_crouch_range.GetFloat() ) return; } } // Toggle the duck pPlayer->ToggleDuck(); } static ConCommand toggle_duck("toggle_duck", CC_ToggleDuck, "Toggles duck" ); #ifndef HL2MP #ifndef PORTAL LINK_ENTITY_TO_CLASS( player, CHL2_Player ); #endif #endif PRECACHE_REGISTER(player); CBaseEntity *FindEntityForward( CBasePlayer *pMe, bool fHull ); BEGIN_SIMPLE_DATADESC( LadderMove_t ) DEFINE_FIELD( m_bForceLadderMove, FIELD_BOOLEAN ), DEFINE_FIELD( m_bForceMount, FIELD_BOOLEAN ), DEFINE_FIELD( m_flStartTime, FIELD_TIME ), DEFINE_FIELD( m_flArrivalTime, FIELD_TIME ), DEFINE_FIELD( m_vecGoalPosition, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecStartPosition, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_hForceLadder, FIELD_EHANDLE ), DEFINE_FIELD( m_hReservedSpot, FIELD_EHANDLE ), END_DATADESC() // Global Savedata for HL2 player BEGIN_DATADESC( CHL2_Player ) DEFINE_FIELD( m_nControlClass, FIELD_INTEGER ), DEFINE_EMBEDDED( m_HL2Local ), DEFINE_FIELD( m_bSprintEnabled, FIELD_BOOLEAN ), DEFINE_FIELD( m_flTimeAllSuitDevicesOff, FIELD_TIME ), DEFINE_FIELD( m_fIsSprinting, FIELD_BOOLEAN ), DEFINE_FIELD( m_fIsWalking, FIELD_BOOLEAN ), /* // These are initialized every time the player calls Activate() DEFINE_FIELD( m_bIsAutoSprinting, FIELD_BOOLEAN ), DEFINE_FIELD( m_fAutoSprintMinTime, FIELD_TIME ), */ // Field is used within a single tick, no need to save restore // DEFINE_FIELD( m_bPlayUseDenySound, FIELD_BOOLEAN ), // m_pPlayerAISquad reacquired on load DEFINE_AUTO_ARRAY( m_vecMissPositions, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_nNumMissPositions, FIELD_INTEGER ), // m_pPlayerAISquad DEFINE_EMBEDDED( m_CommanderUpdateTimer ), // m_RealTimeLastSquadCommand DEFINE_FIELD( m_QueuedCommand, FIELD_INTEGER ), DEFINE_FIELD( m_flTimeIgnoreFallDamage, FIELD_TIME ), DEFINE_FIELD( m_bIgnoreFallDamageResetAfterImpact, FIELD_BOOLEAN ), // Suit power fields DEFINE_FIELD( m_flSuitPowerLoad, FIELD_FLOAT ), DEFINE_FIELD( m_flIdleTime, FIELD_TIME ), DEFINE_FIELD( m_flMoveTime, FIELD_TIME ), DEFINE_FIELD( m_flLastDamageTime, FIELD_TIME ), DEFINE_FIELD( m_flTargetFindTime, FIELD_TIME ), DEFINE_FIELD( m_flAdmireGlovesAnimTime, FIELD_TIME ), DEFINE_FIELD( m_flNextFlashlightCheckTime, FIELD_TIME ), DEFINE_FIELD( m_flFlashlightPowerDrainScale, FIELD_FLOAT ), DEFINE_FIELD( m_bFlashlightDisabled, FIELD_BOOLEAN ), DEFINE_FIELD( m_bUseCappedPhysicsDamageTable, FIELD_BOOLEAN ), DEFINE_FIELD( m_hLockedAutoAimEntity, FIELD_EHANDLE ), DEFINE_EMBEDDED( m_LowerWeaponTimer ), DEFINE_EMBEDDED( m_AutoaimTimer ), DEFINE_INPUTFUNC( FIELD_FLOAT, "IgnoreFallDamage", InputIgnoreFallDamage ), DEFINE_INPUTFUNC( FIELD_FLOAT, "IgnoreFallDamageWithoutReset", InputIgnoreFallDamageWithoutReset ), DEFINE_INPUTFUNC( FIELD_VOID, "OnSquadMemberKilled", OnSquadMemberKilled ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableFlashlight", InputDisableFlashlight ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableFlashlight", InputEnableFlashlight ), DEFINE_INPUTFUNC( FIELD_VOID, "ForceDropPhysObjects", InputForceDropPhysObjects ), DEFINE_SOUNDPATCH( m_sndLeeches ), DEFINE_SOUNDPATCH( m_sndWaterSplashes ), DEFINE_FIELD( m_flArmorReductionTime, FIELD_TIME ), DEFINE_FIELD( m_iArmorReductionFrom, FIELD_INTEGER ), DEFINE_FIELD( m_flTimeUseSuspended, FIELD_TIME ), DEFINE_FIELD( m_hLocatorTargetEntity, FIELD_EHANDLE ), DEFINE_FIELD( m_flTimeNextLadderHint, FIELD_TIME ), //DEFINE_FIELD( m_hPlayerProxy, FIELD_EHANDLE ), //Shut up class check! END_DATADESC() CHL2_Player::CHL2_Player() { m_nNumMissPositions = 0; m_pPlayerAISquad = 0; m_bSprintEnabled = true; m_flArmorReductionTime = 0.0f; m_iArmorReductionFrom = 0; } // // SUIT POWER DEVICES // ///// // SO2 - James // Change how quickly suit power (stamina) recharges //#define SUITPOWER_CHARGE_RATE 12.5 // 100 units in 8 seconds #define SUITPOWER_CHARGE_RATE 6.25 // 100 units in 16 seconds ///// #ifdef HL2MP CSuitPowerDevice SuitDeviceSprint( bits_SUIT_DEVICE_SPRINT, 25.0f ); // 100 units in 4 seconds #else CSuitPowerDevice SuitDeviceSprint( bits_SUIT_DEVICE_SPRINT, 12.5f ); // 100 units in 8 seconds #endif #ifdef HL2_EPISODIC CSuitPowerDevice SuitDeviceFlashlight( bits_SUIT_DEVICE_FLASHLIGHT, 1.111 ); // 100 units in 90 second #else CSuitPowerDevice SuitDeviceFlashlight( bits_SUIT_DEVICE_FLASHLIGHT, 2.222 ); // 100 units in 45 second #endif CSuitPowerDevice SuitDeviceBreather( bits_SUIT_DEVICE_BREATHER, 6.7f ); // 100 units in 15 seconds (plus three padded seconds) IMPLEMENT_SERVERCLASS_ST(CHL2_Player, DT_HL2_Player) SendPropDataTable(SENDINFO_DT(m_HL2Local), &REFERENCE_SEND_TABLE(DT_HL2Local), SendProxy_SendLocalDataTable), SendPropBool( SENDINFO(m_fIsSprinting) ), END_SEND_TABLE() void CHL2_Player::Precache( void ) { BaseClass::Precache(); PrecacheScriptSound( "HL2Player.SprintNoPower" ); PrecacheScriptSound( "HL2Player.SprintStart" ); PrecacheScriptSound( "HL2Player.UseDeny" ); PrecacheScriptSound( "HL2Player.FlashLightOn" ); PrecacheScriptSound( "HL2Player.FlashLightOff" ); PrecacheScriptSound( "HL2Player.PickupWeapon" ); PrecacheScriptSound( "HL2Player.TrainUse" ); PrecacheScriptSound( "HL2Player.Use" ); PrecacheScriptSound( "HL2Player.BurnPain" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::CheckSuitZoom( void ) { //#ifndef _XBOX //Adrian - No zooming without a suit! if ( IsSuitEquipped() ) { if ( m_afButtonReleased & IN_ZOOM ) { StopZooming(); } else if ( m_afButtonPressed & IN_ZOOM ) { StartZooming(); } } //#endif//_XBOX } void CHL2_Player::EquipSuit( bool bPlayEffects ) { MDLCACHE_CRITICAL_SECTION(); BaseClass::EquipSuit(); m_HL2Local.m_bDisplayReticle = true; if ( bPlayEffects == true ) { StartAdmireGlovesAnimation(); } } void CHL2_Player::RemoveSuit( void ) { BaseClass::RemoveSuit(); m_HL2Local.m_bDisplayReticle = false; } void CHL2_Player::HandleSpeedChanges( void ) { int buttonsChanged = m_afButtonPressed | m_afButtonReleased; bool bCanSprint = CanSprint(); bool bIsSprinting = IsSprinting(); bool bWantSprint = ( bCanSprint && IsSuitEquipped() && (m_nButtons & IN_SPEED) ); if ( bIsSprinting != bWantSprint && (buttonsChanged & IN_SPEED) ) { // If someone wants to sprint, make sure they've pressed the button to do so. We want to prevent the // case where a player can hold down the sprint key and burn tiny bursts of sprint as the suit recharges // We want a full debounce of the key to resume sprinting after the suit is completely drained if ( bWantSprint ) { if ( sv_stickysprint.GetBool() ) { StartAutoSprint(); } else { StartSprinting(); } } else { if ( !sv_stickysprint.GetBool() ) { StopSprinting(); } // Reset key, so it will be activated post whatever is suppressing it. m_nButtons &= ~IN_SPEED; } } bool bIsWalking = IsWalking(); // have suit, pressing button, not sprinting or ducking bool bWantWalking; if( IsSuitEquipped() ) { bWantWalking = (m_nButtons & IN_WALK) && !IsSprinting() && !(m_nButtons & IN_DUCK); } else { bWantWalking = true; } if( bIsWalking != bWantWalking ) { if ( bWantWalking ) { StartWalking(); } else { StopWalking(); } } } //----------------------------------------------------------------------------- // This happens when we powerdown from the mega physcannon to the regular one //----------------------------------------------------------------------------- void CHL2_Player::HandleArmorReduction( void ) { if ( m_flArmorReductionTime < gpGlobals->curtime ) return; if ( ArmorValue() <= 0 ) return; float flPercent = 1.0f - (( m_flArmorReductionTime - gpGlobals->curtime ) / ARMOR_DECAY_TIME ); int iArmor = Lerp( flPercent, m_iArmorReductionFrom, 0 ); SetArmorValue( iArmor ); } //----------------------------------------------------------------------------- // Purpose: Allow pre-frame adjustments on the player //----------------------------------------------------------------------------- void CHL2_Player::PreThink(void) { if ( player_showpredictedposition.GetBool() ) { Vector predPos; UTIL_PredictedPosition( this, player_showpredictedposition_timestep.GetFloat(), &predPos ); NDebugOverlay::Box( predPos, NAI_Hull::Mins( GetHullType() ), NAI_Hull::Maxs( GetHullType() ), 0, 255, 0, 0, 0.01f ); NDebugOverlay::Line( GetAbsOrigin(), predPos, 0, 255, 0, 0, 0.01f ); } #ifdef HL2_EPISODIC if( m_hLocatorTargetEntity != NULL ) { // Keep track of the entity here, the client will pick up the rest of the work m_HL2Local.m_vecLocatorOrigin = m_hLocatorTargetEntity->WorldSpaceCenter(); } else { m_HL2Local.m_vecLocatorOrigin = vec3_invalid; // This tells the client we have no locator target. } #endif//HL2_EPISODIC // Riding a vehicle? if ( IsInAVehicle() ) { VPROF( "CHL2_Player::PreThink-Vehicle" ); // make sure we update the client, check for timed damage and update suit even if we are in a vehicle UpdateClientData(); CheckTimeBasedDamage(); // Allow the suit to recharge when in the vehicle. SuitPower_Update(); CheckSuitUpdate(); CheckSuitZoom(); WaterMove(); return; } // This is an experiment of mine- autojumping! // only affects you if sv_autojump is nonzero. if( (GetFlags() & FL_ONGROUND) && sv_autojump.GetFloat() != 0 ) { VPROF( "CHL2_Player::PreThink-Autojump" ); // check autojump Vector vecCheckDir; vecCheckDir = GetAbsVelocity(); float flVelocity = VectorNormalize( vecCheckDir ); if( flVelocity > 200 ) { // Going fast enough to autojump vecCheckDir = WorldSpaceCenter() + vecCheckDir * 34 - Vector( 0, 0, 16 ); trace_t tr; UTIL_TraceHull( WorldSpaceCenter() - Vector( 0, 0, 16 ), vecCheckDir, NAI_Hull::Mins(HULL_TINY_CENTERED),NAI_Hull::Maxs(HULL_TINY_CENTERED), MASK_PLAYERSOLID, this, COLLISION_GROUP_PLAYER, &tr ); //NDebugOverlay::Line( tr.startpos, tr.endpos, 0,255,0, true, 10 ); if( tr.fraction == 1.0 && !tr.startsolid ) { // Now trace down! UTIL_TraceLine( vecCheckDir, vecCheckDir - Vector( 0, 0, 64 ), MASK_PLAYERSOLID, this, COLLISION_GROUP_NONE, &tr ); //NDebugOverlay::Line( tr.startpos, tr.endpos, 0,255,0, true, 10 ); if( tr.fraction == 1.0 && !tr.startsolid ) { // !!!HACKHACK // I KNOW, I KNOW, this is definitely not the right way to do this, // but I'm prototyping! (sjb) Vector vecNewVelocity = GetAbsVelocity(); vecNewVelocity.z += 250; SetAbsVelocity( vecNewVelocity ); } } } } VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-Speed" ); HandleSpeedChanges(); #ifdef HL2_EPISODIC HandleArmorReduction(); #endif if( sv_stickysprint.GetBool() && m_bIsAutoSprinting ) { // If we're ducked and not in the air if( IsDucked() && GetGroundEntity() != NULL ) { StopSprinting(); } // Stop sprinting if the player lets off the stick for a moment. else if( GetStickDist() == 0.0f ) { if( gpGlobals->curtime > m_fAutoSprintMinTime ) { StopSprinting(); } } else { // Stop sprinting one half second after the player stops inputting with the move stick. m_fAutoSprintMinTime = gpGlobals->curtime + 0.5f; } } else if ( IsSprinting() ) { // Disable sprint while ducked unless we're in the air (jumping) if ( IsDucked() && ( GetGroundEntity() != NULL ) ) { StopSprinting(); } } VPROF_SCOPE_END(); if ( g_fGameOver || IsPlayerLockedInPlace() ) return; // finale VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-ItemPreFrame" ); ItemPreFrame( ); VPROF_SCOPE_END(); VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-WaterMove" ); WaterMove(); VPROF_SCOPE_END(); if ( g_pGameRules && g_pGameRules->FAllowFlashlight() ) m_Local.m_iHideHUD &= ~HIDEHUD_FLASHLIGHT; else m_Local.m_iHideHUD |= HIDEHUD_FLASHLIGHT; VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CommanderUpdate" ); CommanderUpdate(); VPROF_SCOPE_END(); // Operate suit accessories and manage power consumption/charge VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-SuitPower_Update" ); SuitPower_Update(); VPROF_SCOPE_END(); // checks if new client data (for HUD and view control) needs to be sent to the client VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-UpdateClientData" ); UpdateClientData(); VPROF_SCOPE_END(); VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckTimeBasedDamage" ); CheckTimeBasedDamage(); VPROF_SCOPE_END(); VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckSuitUpdate" ); CheckSuitUpdate(); VPROF_SCOPE_END(); VPROF_SCOPE_BEGIN( "CHL2_Player::PreThink-CheckSuitZoom" ); CheckSuitZoom(); VPROF_SCOPE_END(); if (m_lifeState >= LIFE_DYING) { PlayerDeathThink(); return; } #ifdef HL2_EPISODIC CheckFlashlight(); #endif // HL2_EPISODIC // So the correct flags get sent to client asap. // if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE ) AddFlag( FL_ONTRAIN ); else RemoveFlag( FL_ONTRAIN ); // Train speed control if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE ) { CBaseEntity *pTrain = GetGroundEntity(); float vel; if ( pTrain ) { if ( !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) ) pTrain = NULL; } if ( !pTrain ) { if ( GetActiveWeapon() && (GetActiveWeapon()->ObjectCaps() & FCAP_DIRECTIONAL_USE) ) { m_iTrain = TRAIN_ACTIVE | TRAIN_NEW; if ( m_nButtons & IN_FORWARD ) { m_iTrain |= TRAIN_FAST; } else if ( m_nButtons & IN_BACK ) { m_iTrain |= TRAIN_BACK; } else { m_iTrain |= TRAIN_NEUTRAL; } return; } else { trace_t trainTrace; // Maybe this is on the other side of a level transition UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + Vector(0,0,-38), MASK_PLAYERSOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &trainTrace ); if ( trainTrace.fraction != 1.0 && trainTrace.m_pEnt ) pTrain = trainTrace.m_pEnt; if ( !pTrain || !(pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) || !pTrain->OnControls(this) ) { // Warning( "In train mode with no train!\n" ); m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE; m_iTrain = TRAIN_NEW|TRAIN_OFF; return; } } } else if ( !( GetFlags() & FL_ONGROUND ) || pTrain->HasSpawnFlags( SF_TRACKTRAIN_NOCONTROL ) || (m_nButtons & (IN_MOVELEFT|IN_MOVERIGHT) ) ) { // Turn off the train if you jump, strafe, or the train controls go dead m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE; m_iTrain = TRAIN_NEW|TRAIN_OFF; return; } SetAbsVelocity( vec3_origin ); vel = 0; if ( m_afButtonPressed & IN_FORWARD ) { vel = 1; pTrain->Use( this, this, USE_SET, (float)vel ); } else if ( m_afButtonPressed & IN_BACK ) { vel = -1; pTrain->Use( this, this, USE_SET, (float)vel ); } if (vel) { m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed()); m_iTrain |= TRAIN_ACTIVE|TRAIN_NEW; } } else if (m_iTrain & TRAIN_ACTIVE) { m_iTrain = TRAIN_NEW; // turn off train } // // If we're not on the ground, we're falling. Update our falling velocity. // if ( !( GetFlags() & FL_ONGROUND ) ) { m_Local.m_flFallVelocity = -GetAbsVelocity().z; } if ( m_afPhysicsFlags & PFLAG_ONBARNACLE ) { bool bOnBarnacle = false; CNPC_Barnacle *pBarnacle = NULL; do { // FIXME: Not a good or fast solution, but maybe it will catch the bug! pBarnacle = (CNPC_Barnacle*)gEntList.FindEntityByClassname( pBarnacle, "npc_barnacle" ); if ( pBarnacle ) { if ( pBarnacle->GetEnemy() == this ) { bOnBarnacle = true; } } } while ( pBarnacle ); if ( !bOnBarnacle ) { Warning( "Attached to barnacle?\n" ); Assert( 0 ); m_afPhysicsFlags &= ~PFLAG_ONBARNACLE; } else { SetAbsVelocity( vec3_origin ); } } // StudioFrameAdvance( );//!!!HACKHACK!!! Can't be hit by traceline when not animating? // Update weapon's ready status UpdateWeaponPosture(); ///// // SO2 - James // Disable suit zooming functionality /*// Disallow shooting while zooming if ( IsX360() ) { if ( IsZooming() ) { if( GetActiveWeapon() && !GetActiveWeapon()->IsWeaponZoomed() ) { // If not zoomed because of the weapon itself, do not attack. m_nButtons &= ~(IN_ATTACK|IN_ATTACK2); } } } else { if ( m_nButtons & IN_ZOOM ) { //FIXME: Held weapons like the grenade get sad when this happens #ifdef HL2_EPISODIC // Episodic allows players to zoom while using a func_tank CBaseCombatWeapon* pWep = GetActiveWeapon(); if ( !m_hUseEntity || ( pWep && pWep->IsWeaponVisible() ) ) #endif m_nButtons &= ~(IN_ATTACK|IN_ATTACK2); } }*/ ///// } void CHL2_Player::PostThink( void ) { BaseClass::PostThink(); if ( !g_fGameOver && !IsPlayerLockedInPlace() && IsAlive() ) { HandleAdmireGlovesAnimation(); } } void CHL2_Player::StartAdmireGlovesAnimation( void ) { MDLCACHE_CRITICAL_SECTION(); CBaseViewModel *vm = GetViewModel( 0 ); if ( vm && !GetActiveWeapon() ) { vm->SetWeaponModel( "models/weapons/v_hands.mdl", NULL ); ShowViewModel( true ); int idealSequence = vm->SelectWeightedSequence( ACT_VM_IDLE ); if ( idealSequence >= 0 ) { vm->SendViewModelMatchingSequence( idealSequence ); m_flAdmireGlovesAnimTime = gpGlobals->curtime + vm->SequenceDuration( idealSequence ); } } } void CHL2_Player::HandleAdmireGlovesAnimation( void ) { CBaseViewModel *pVM = GetViewModel(); if ( pVM && pVM->GetOwningWeapon() == NULL ) { if ( m_flAdmireGlovesAnimTime != 0.0 ) { if ( m_flAdmireGlovesAnimTime > gpGlobals->curtime ) { pVM->m_flPlaybackRate = 1.0f; pVM->StudioFrameAdvance( ); } else if ( m_flAdmireGlovesAnimTime < gpGlobals->curtime ) { m_flAdmireGlovesAnimTime = 0.0f; pVM->SetWeaponModel( NULL, NULL ); } } } else m_flAdmireGlovesAnimTime = 0.0f; } #define HL2PLAYER_RELOADGAME_ATTACK_DELAY 1.0f void CHL2_Player::Activate( void ) { BaseClass::Activate(); InitSprinting(); #ifdef HL2_EPISODIC // Delay attacks by 1 second after loading a game. if ( GetActiveWeapon() ) { float flRemaining = GetActiveWeapon()->m_flNextPrimaryAttack - gpGlobals->curtime; if ( flRemaining < HL2PLAYER_RELOADGAME_ATTACK_DELAY ) { GetActiveWeapon()->m_flNextPrimaryAttack = gpGlobals->curtime + HL2PLAYER_RELOADGAME_ATTACK_DELAY; } flRemaining = GetActiveWeapon()->m_flNextSecondaryAttack - gpGlobals->curtime; if ( flRemaining < HL2PLAYER_RELOADGAME_ATTACK_DELAY ) { GetActiveWeapon()->m_flNextSecondaryAttack = gpGlobals->curtime + HL2PLAYER_RELOADGAME_ATTACK_DELAY; } } #endif GetPlayerProxy(); } //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ Class_T CHL2_Player::Classify ( void ) { // If player controlling another entity? If so, return this class if (m_nControlClass != CLASS_NONE) { return m_nControlClass; } else { if(IsInAVehicle()) { IServerVehicle *pVehicle = GetVehicle(); return pVehicle->ClassifyPassenger( this, CLASS_PLAYER ); } else { return CLASS_PLAYER; } } } //----------------------------------------------------------------------------- // Purpose: This is a generic function (to be implemented by sub-classes) to // handle specific interactions between different types of characters // (For example the barnacle grabbing an NPC) // Input : Constant for the type of interaction // Output : true - if sub-class has a response for the interaction // false - if sub-class has no response //----------------------------------------------------------------------------- bool CHL2_Player::HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt) { if ( interactionType == g_interactionBarnacleVictimDangle ) return false; if (interactionType == g_interactionBarnacleVictimReleased) { m_afPhysicsFlags &= ~PFLAG_ONBARNACLE; SetMoveType( MOVETYPE_WALK ); return true; } else if (interactionType == g_interactionBarnacleVictimGrab) { #ifdef HL2_EPISODIC CNPC_Alyx *pAlyx = CNPC_Alyx::GetAlyx(); if ( pAlyx ) { // Make Alyx totally hate this barnacle so that she saves the player. int priority; priority = pAlyx->IRelationPriority(sourceEnt); pAlyx->AddEntityRelationship( sourceEnt, D_HT, priority + 5 ); } #endif//HL2_EPISODIC m_afPhysicsFlags |= PFLAG_ONBARNACLE; ClearUseEntity(); return true; } return false; } void CHL2_Player::PlayerRunCommand(CUserCmd *ucmd, IMoveHelper *moveHelper) { // Handle FL_FROZEN. if ( m_afPhysicsFlags & PFLAG_ONBARNACLE ) { ucmd->forwardmove = 0; ucmd->sidemove = 0; ucmd->upmove = 0; ucmd->buttons &= ~IN_USE; } // Can't use stuff while dead if ( IsDead() ) { ucmd->buttons &= ~IN_USE; } //Update our movement information if ( ( ucmd->forwardmove != 0 ) || ( ucmd->sidemove != 0 ) || ( ucmd->upmove != 0 ) ) { m_flIdleTime -= TICK_INTERVAL * 2.0f; if ( m_flIdleTime < 0.0f ) { m_flIdleTime = 0.0f; } m_flMoveTime += TICK_INTERVAL; if ( m_flMoveTime > 4.0f ) { m_flMoveTime = 4.0f; } } else { m_flIdleTime += TICK_INTERVAL; if ( m_flIdleTime > 4.0f ) { m_flIdleTime = 4.0f; } m_flMoveTime -= TICK_INTERVAL * 2.0f; if ( m_flMoveTime < 0.0f ) { m_flMoveTime = 0.0f; } } //Msg("Player time: [ACTIVE: %f]\t[IDLE: %f]\n", m_flMoveTime, m_flIdleTime ); BaseClass::PlayerRunCommand( ucmd, moveHelper ); } //----------------------------------------------------------------------------- // Purpose: Sets HL2 specific defaults. //----------------------------------------------------------------------------- void CHL2_Player::Spawn(void) { #ifndef HL2MP #ifndef PORTAL SetModel( "models/player.mdl" ); #endif #endif BaseClass::Spawn(); // // Our player movement speed is set once here. This will override the cl_xxxx // cvars unless they are set to be lower than this. // //m_flMaxspeed = 320; if ( !IsSuitEquipped() ) StartWalking(); SuitPower_SetCharge( 100 ); m_Local.m_iHideHUD |= HIDEHUD_CHAT; m_pPlayerAISquad = g_AI_SquadManager.FindCreateSquad(AllocPooledString(PLAYER_SQUADNAME)); InitSprinting(); // Setup our flashlight values #ifdef HL2_EPISODIC m_HL2Local.m_flFlashBattery = 100.0f; #endif GetPlayerProxy(); SetFlashlightPowerDrainScale( 1.0f ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::UpdateLocatorPosition( const Vector &vecPosition ) { #ifdef HL2_EPISODIC m_HL2Local.m_vecLocatorOrigin = vecPosition; #endif//HL2_EPISODIC } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::InitSprinting( void ) { StopSprinting(); } //----------------------------------------------------------------------------- // Purpose: Returns whether or not we are allowed to sprint now. //----------------------------------------------------------------------------- bool CHL2_Player::CanSprint() { return ( m_bSprintEnabled && // Only if sprint is enabled !IsWalking() && // Not if we're walking !( m_Local.m_bDucked && !m_Local.m_bDucking ) && // Nor if we're ducking (GetWaterLevel() != 3) && // Certainly not underwater (GlobalEntity_GetState("suit_no_sprint") != GLOBAL_ON) ); // Out of the question without the sprint module } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StartAutoSprint() { if( IsSprinting() ) { StopSprinting(); } else { StartSprinting(); m_bIsAutoSprinting = true; m_fAutoSprintMinTime = gpGlobals->curtime + 1.5f; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StartSprinting( void ) { if( m_HL2Local.m_flSuitPower < 10 ) { // Don't sprint unless there's a reasonable // amount of suit power. // debounce the button for sound playing if ( m_afButtonPressed & IN_SPEED ) { CPASAttenuationFilter filter( this ); filter.UsePredictionRules(); EmitSound( filter, entindex(), "HL2Player.SprintNoPower" ); } return; } if( !SuitPower_AddDevice( SuitDeviceSprint ) ) return; CPASAttenuationFilter filter( this ); filter.UsePredictionRules(); EmitSound( filter, entindex(), "HL2Player.SprintStart" ); ///// // SO2 - James // Do not allow players to fire weapons while sprinting CSO_Player *pSOPlayer = ToSOPlayer( this ); if ( pSOPlayer ) { pSOPlayer->SetHolsteredWeapon( pSOPlayer->GetActiveWeapon() ); CBaseCombatWeapon *pHolsteredWeapon = pSOPlayer->GetHolsteredWeapon(); if ( pHolsteredWeapon ) pHolsteredWeapon->Holster(); } ///// SetMaxSpeed( HL2_SPRINT_SPEED ); m_fIsSprinting = true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StopSprinting( void ) { if ( m_HL2Local.m_bitsActiveDevices & SuitDeviceSprint.GetDeviceID() ) { SuitPower_RemoveDevice( SuitDeviceSprint ); } ///// // SO2 - James // Do not allow players to fire weapons while sprinting CSO_Player *pSOPlayer = ToSOPlayer( this ); if ( pSOPlayer ) { CBaseCombatWeapon *pHolsteredWeapon = pSOPlayer->GetHolsteredWeapon(); if ( pHolsteredWeapon ) { pHolsteredWeapon->Deploy(); pSOPlayer->SetHolsteredWeapon( NULL ); // weapon is no longer holstered; reset variable } } ///// if( IsSuitEquipped() ) { SetMaxSpeed( HL2_NORM_SPEED ); } else { SetMaxSpeed( HL2_WALK_SPEED ); } m_fIsSprinting = false; if ( sv_stickysprint.GetBool() ) { m_bIsAutoSprinting = false; m_fAutoSprintMinTime = 0.0f; } } //----------------------------------------------------------------------------- // Purpose: Called to disable and enable sprint due to temporary circumstances: // - Carrying a heavy object with the physcannon //----------------------------------------------------------------------------- void CHL2_Player::EnableSprint( bool bEnable ) { if ( !bEnable && IsSprinting() ) { StopSprinting(); } m_bSprintEnabled = bEnable; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StartWalking( void ) { SetMaxSpeed( HL2_WALK_SPEED ); m_fIsWalking = true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::StopWalking( void ) { SetMaxSpeed( HL2_NORM_SPEED ); m_fIsWalking = false; } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::CanZoom( CBaseEntity *pRequester ) { if ( IsZooming() ) return false; //Check our weapon return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::ToggleZoom(void) { if( IsZooming() ) { StopZooming(); } else { StartZooming(); } } //----------------------------------------------------------------------------- // Purpose: +zoom suit zoom //----------------------------------------------------------------------------- void CHL2_Player::StartZooming( void ) { ///// // SO2 - James // Disable suit zooming functionality /*int iFOV = 25; if ( SetFOV( this, iFOV, 0.4f ) ) { m_HL2Local.m_bZooming = true; }*/ ///// } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::StopZooming( void ) { ///// // SO2 - James // Disable suit zooming functionality /*int iFOV = GetZoomOwnerDesiredFOV( m_hZoomOwner ); if ( SetFOV( this, iFOV, 0.2f ) ) { m_HL2Local.m_bZooming = false; }*/ ///// } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::IsZooming( void ) { if ( m_hZoomOwner != NULL ) return true; return false; } class CPhysicsPlayerCallback : public IPhysicsPlayerControllerEvent { public: int ShouldMoveTo( IPhysicsObject *pObject, const Vector &position ) { CHL2_Player *pPlayer = (CHL2_Player *)pObject->GetGameData(); if ( pPlayer ) { if ( pPlayer->TouchedPhysics() ) { return 0; } } return 1; } }; static CPhysicsPlayerCallback playerCallback; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::InitVCollision( const Vector &vecAbsOrigin, const Vector &vecAbsVelocity ) { BaseClass::InitVCollision( vecAbsOrigin, vecAbsVelocity ); // Setup the HL2 specific callback. IPhysicsPlayerController *pPlayerController = GetPhysicsController(); if ( pPlayerController ) { pPlayerController->SetEventHandler( &playerCallback ); } } CHL2_Player::~CHL2_Player( void ) { } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::CommanderFindGoal( commandgoal_t *pGoal ) { CAI_BaseNPC *pAllyNpc; trace_t tr; Vector vecTarget; Vector forward; EyeVectors( &forward ); //--------------------------------- // MASK_SHOT on purpose! So that you don't hit the invisible hulls of the NPCs. CTraceFilterSkipTwoEntities filter( this, PhysCannonGetHeldEntity( GetActiveWeapon() ), COLLISION_GROUP_INTERACTIVE_DEBRIS ); UTIL_TraceLine( EyePosition(), EyePosition() + forward * MAX_COORD_RANGE, MASK_SHOT, &filter, &tr ); if( !tr.DidHitWorld() ) { CUtlVector<CAI_BaseNPC *> Allies; AISquadIter_t iter; for ( pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandable() ) Allies.AddToTail( pAllyNpc ); } for( int i = 0 ; i < Allies.Count() ; i++ ) { if( Allies[ i ]->IsValidCommandTarget( tr.m_pEnt ) ) { pGoal->m_pGoalEntity = tr.m_pEnt; return true; } } } if( tr.fraction == 1.0 || (tr.surface.flags & SURF_SKY) ) { // Move commands invalid against skybox. pGoal->m_vecGoalLocation = tr.endpos; return false; } if ( tr.m_pEnt->IsNPC() && ((CAI_BaseNPC *)(tr.m_pEnt))->IsCommandable() ) { pGoal->m_vecGoalLocation = tr.m_pEnt->GetAbsOrigin(); } else { vecTarget = tr.endpos; Vector mins( -16, -16, 0 ); Vector maxs( 16, 16, 0 ); // Back up from whatever we hit so that there's enough space at the // target location for a bounding box. // Now trace down. //UTIL_TraceLine( vecTarget, vecTarget - Vector( 0, 0, 8192 ), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr ); UTIL_TraceHull( vecTarget + tr.plane.normal * 24, vecTarget - Vector( 0, 0, 8192 ), mins, maxs, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &tr ); if ( !tr.startsolid ) pGoal->m_vecGoalLocation = tr.endpos; else pGoal->m_vecGoalLocation = vecTarget; } pAllyNpc = GetSquadCommandRepresentative(); if ( !pAllyNpc ) return false; vecTarget = pGoal->m_vecGoalLocation; if ( !pAllyNpc->FindNearestValidGoalPos( vecTarget, &pGoal->m_vecGoalLocation ) ) return false; return ( ( vecTarget - pGoal->m_vecGoalLocation ).LengthSqr() < Square( 15*12 ) ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- CAI_BaseNPC *CHL2_Player::GetSquadCommandRepresentative() { if ( m_pPlayerAISquad != NULL ) { CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(); if ( pAllyNpc ) { return pAllyNpc->GetSquadCommandRepresentative(); } } return NULL; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CHL2_Player::GetNumSquadCommandables() { AISquadIter_t iter; int c = 0; for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandable() ) c++; } return c; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CHL2_Player::GetNumSquadCommandableMedics() { AISquadIter_t iter; int c = 0; for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandable() && pAllyNpc->IsMedic() ) c++; } return c; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::CommanderUpdate() { CAI_BaseNPC *pCommandRepresentative = GetSquadCommandRepresentative(); bool bFollowMode = false; if ( pCommandRepresentative ) { bFollowMode = ( pCommandRepresentative->GetCommandGoal() == vec3_invalid ); // set the variables for network transmission (to show on the hud) m_HL2Local.m_iSquadMemberCount = GetNumSquadCommandables(); m_HL2Local.m_iSquadMedicCount = GetNumSquadCommandableMedics(); m_HL2Local.m_fSquadInFollowMode = bFollowMode; // debugging code for displaying extra squad indicators /* char *pszMoving = ""; AISquadIter_t iter; for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandMoving() ) { pszMoving = "<-"; break; } } NDebugOverlay::ScreenText( 0.932, 0.919, CFmtStr( "%d|%c%s", GetNumSquadCommandables(), ( bFollowMode ) ? 'F' : 'S', pszMoving ), 255, 128, 0, 128, 0 ); */ } else { m_HL2Local.m_iSquadMemberCount = 0; m_HL2Local.m_iSquadMedicCount = 0; m_HL2Local.m_fSquadInFollowMode = true; } if ( m_QueuedCommand != CC_NONE && ( m_QueuedCommand == CC_FOLLOW || gpGlobals->realtime - m_RealTimeLastSquadCommand >= player_squad_double_tap_time.GetFloat() ) ) { CommanderExecute( m_QueuedCommand ); m_QueuedCommand = CC_NONE; } else if ( !bFollowMode && pCommandRepresentative && m_CommanderUpdateTimer.Expired() && player_squad_transient_commands.GetBool() ) { m_CommanderUpdateTimer.Set(2.5); if ( pCommandRepresentative->ShouldAutoSummon() ) CommanderExecute( CC_FOLLOW ); } } //----------------------------------------------------------------------------- // Purpose: // // bHandled - indicates whether to continue delivering this order to // all allies. Allows us to stop delivering certain types of orders once we find // a suitable candidate. (like picking up a single weapon. We don't wish for // all allies to respond and try to pick up one weapon). //----------------------------------------------------------------------------- bool CHL2_Player::CommanderExecuteOne( CAI_BaseNPC *pNpc, const commandgoal_t &goal, CAI_BaseNPC **Allies, int numAllies ) { if ( goal.m_pGoalEntity ) { return pNpc->TargetOrder( goal.m_pGoalEntity, Allies, numAllies ); } else if ( pNpc->IsInPlayerSquad() ) { pNpc->MoveOrder( goal.m_vecGoalLocation, Allies, numAllies ); } return true; } //--------------------------------------------------------- //--------------------------------------------------------- void CHL2_Player::CommanderExecute( CommanderCommand_t command ) { CAI_BaseNPC *pPlayerSquadLeader = GetSquadCommandRepresentative(); if ( !pPlayerSquadLeader ) { EmitSound( "HL2Player.UseDeny" ); return; } int i; CUtlVector<CAI_BaseNPC *> Allies; commandgoal_t goal; if ( command == CC_TOGGLE ) { if ( pPlayerSquadLeader->GetCommandGoal() != vec3_invalid ) command = CC_FOLLOW; else command = CC_SEND; } else { if ( command == CC_FOLLOW && pPlayerSquadLeader->GetCommandGoal() == vec3_invalid ) return; } if ( command == CC_FOLLOW ) { goal.m_pGoalEntity = this; goal.m_vecGoalLocation = vec3_invalid; } else { goal.m_pGoalEntity = NULL; goal.m_vecGoalLocation = vec3_invalid; // Find a goal for ourselves. if( !CommanderFindGoal( &goal ) ) { EmitSound( "HL2Player.UseDeny" ); return; // just keep following } } #ifdef _DEBUG if( goal.m_pGoalEntity == NULL && goal.m_vecGoalLocation == vec3_invalid ) { DevMsg( 1, "**ERROR: Someone sent an invalid goal to CommanderExecute!\n" ); } #endif // _DEBUG AISquadIter_t iter; for ( CAI_BaseNPC *pAllyNpc = m_pPlayerAISquad->GetFirstMember(&iter); pAllyNpc; pAllyNpc = m_pPlayerAISquad->GetNextMember(&iter) ) { if ( pAllyNpc->IsCommandable() ) Allies.AddToTail( pAllyNpc ); } //--------------------------------- // If the trace hits an NPC, send all ally NPCs a "target" order. Always // goes to targeted one first #ifdef DEBUG int nAIs = g_AI_Manager.NumAIs(); #endif CAI_BaseNPC * pTargetNpc = (goal.m_pGoalEntity) ? goal.m_pGoalEntity->MyNPCPointer() : NULL; bool bHandled = false; if( pTargetNpc ) { bHandled = !CommanderExecuteOne( pTargetNpc, goal, Allies.Base(), Allies.Count() ); } for ( i = 0; !bHandled && i < Allies.Count(); i++ ) { if ( Allies[i] != pTargetNpc && Allies[i]->IsPlayerAlly() ) { bHandled = !CommanderExecuteOne( Allies[i], goal, Allies.Base(), Allies.Count() ); } Assert( nAIs == g_AI_Manager.NumAIs() ); // not coded to support mutating set of NPCs } } //----------------------------------------------------------------------------- // Enter/exit commander mode, manage ally selection. //----------------------------------------------------------------------------- void CHL2_Player::CommanderMode() { float commandInterval = gpGlobals->realtime - m_RealTimeLastSquadCommand; m_RealTimeLastSquadCommand = gpGlobals->realtime; if ( commandInterval < player_squad_double_tap_time.GetFloat() ) { m_QueuedCommand = CC_FOLLOW; } else { m_QueuedCommand = (player_squad_transient_commands.GetBool()) ? CC_SEND : CC_TOGGLE; } } //----------------------------------------------------------------------------- // Purpose: // Input : iImpulse - //----------------------------------------------------------------------------- void CHL2_Player::CheatImpulseCommands( int iImpulse ) { switch( iImpulse ) { case 50: { CommanderMode(); break; } case 51: { // Cheat to create a dynamic resupply item Vector vecForward; AngleVectors( EyeAngles(), &vecForward ); CBaseEntity *pItem = (CBaseEntity *)CreateEntityByName( "item_dynamic_resupply" ); if ( pItem ) { Vector vecOrigin = GetAbsOrigin() + vecForward * 256 + Vector(0,0,64); QAngle vecAngles( 0, GetAbsAngles().y - 90, 0 ); pItem->SetAbsOrigin( vecOrigin ); pItem->SetAbsAngles( vecAngles ); pItem->KeyValue( "targetname", "resupply" ); pItem->Spawn(); pItem->Activate(); } break; } case 52: { // Rangefinder trace_t tr; UTIL_TraceLine( EyePosition(), EyePosition() + EyeDirection3D() * MAX_COORD_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); if( tr.fraction != 1.0 ) { float flDist = (tr.startpos - tr.endpos).Length(); float flDist2D = (tr.startpos - tr.endpos).Length2D(); DevMsg( 1,"\nStartPos: %.4f %.4f %.4f --- EndPos: %.4f %.4f %.4f\n", tr.startpos.x,tr.startpos.y,tr.startpos.z,tr.endpos.x,tr.endpos.y,tr.endpos.z ); DevMsg( 1,"3D Distance: %.4f units (%.2f feet) --- 2D Distance: %.4f units (%.2f feet)\n", flDist, flDist / 12.0, flDist2D, flDist2D / 12.0 ); } break; } default: BaseClass::CheatImpulseCommands( iImpulse ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::SetupVisibility( CBaseEntity *pViewEntity, unsigned char *pvs, int pvssize ) { BaseClass::SetupVisibility( pViewEntity, pvs, pvssize ); int area = pViewEntity ? pViewEntity->NetworkProp()->AreaNum() : NetworkProp()->AreaNum(); PointCameraSetupVisibility( this, area, pvs, pvssize ); // If the intro script is playing, we want to get it's visibility points if ( g_hIntroScript ) { Vector vecOrigin; CBaseEntity *pCamera; if ( g_hIntroScript->GetIncludedPVSOrigin( &vecOrigin, &pCamera ) ) { // If it's a point camera, turn it on CPointCamera *pPointCamera = dynamic_cast< CPointCamera* >(pCamera); if ( pPointCamera ) { pPointCamera->SetActive( true ); } engine->AddOriginToPVS( vecOrigin ); } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::SuitPower_Update( void ) { if( SuitPower_ShouldRecharge() ) { SuitPower_Charge( SUITPOWER_CHARGE_RATE * gpGlobals->frametime ); } else if( m_HL2Local.m_bitsActiveDevices ) { float flPowerLoad = m_flSuitPowerLoad; //Since stickysprint quickly shuts off sprint if it isn't being used, this isn't an issue. if ( !sv_stickysprint.GetBool() ) { if( SuitPower_IsDeviceActive(SuitDeviceSprint) ) { if( !fabs(GetAbsVelocity().x) && !fabs(GetAbsVelocity().y) ) { // If player's not moving, don't drain sprint juice. flPowerLoad -= SuitDeviceSprint.GetDeviceDrainRate(); } } } if( SuitPower_IsDeviceActive(SuitDeviceFlashlight) ) { float factor; factor = 1.0f / m_flFlashlightPowerDrainScale; flPowerLoad -= ( SuitDeviceFlashlight.GetDeviceDrainRate() * (1.0f - factor) ); } if( !SuitPower_Drain( flPowerLoad * gpGlobals->frametime ) ) { // TURN OFF ALL DEVICES!! if( IsSprinting() ) { StopSprinting(); } if ( Flashlight_UseLegacyVersion() ) { if( FlashlightIsOn() ) { #ifndef HL2MP FlashlightTurnOff(); #endif } } } if ( Flashlight_UseLegacyVersion() ) { // turn off flashlight a little bit after it hits below one aux power notch (5%) if( m_HL2Local.m_flSuitPower < 4.8f && FlashlightIsOn() ) { #ifndef HL2MP FlashlightTurnOff(); #endif } } } } //----------------------------------------------------------------------------- // Charge battery fully, turn off all devices. //----------------------------------------------------------------------------- void CHL2_Player::SuitPower_Initialize( void ) { m_HL2Local.m_bitsActiveDevices = 0x00000000; m_HL2Local.m_flSuitPower = 100.0; m_flSuitPowerLoad = 0.0; } //----------------------------------------------------------------------------- // Purpose: Interface to drain power from the suit's power supply. // Input: Amount of charge to remove (expressed as percentage of full charge) // Output: Returns TRUE if successful, FALSE if not enough power available. //----------------------------------------------------------------------------- bool CHL2_Player::SuitPower_Drain( float flPower ) { // Suitpower cheat on? if ( sv_infinite_aux_power.GetBool() ) return true; m_HL2Local.m_flSuitPower -= flPower; if( m_HL2Local.m_flSuitPower < 0.0 ) { // Power is depleted! // Clamp and fail m_HL2Local.m_flSuitPower = 0.0; return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Interface to add power to the suit's power supply // Input: Amount of charge to add //----------------------------------------------------------------------------- void CHL2_Player::SuitPower_Charge( float flPower ) { m_HL2Local.m_flSuitPower += flPower; if( m_HL2Local.m_flSuitPower > 100.0 ) { // Full charge, clamp. m_HL2Local.m_flSuitPower = 100.0; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::SuitPower_IsDeviceActive( const CSuitPowerDevice &device ) { return (m_HL2Local.m_bitsActiveDevices & device.GetDeviceID()) != 0; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::SuitPower_AddDevice( const CSuitPowerDevice &device ) { // Make sure this device is NOT active!! if( m_HL2Local.m_bitsActiveDevices & device.GetDeviceID() ) return false; if( !IsSuitEquipped() ) return false; m_HL2Local.m_bitsActiveDevices |= device.GetDeviceID(); m_flSuitPowerLoad += device.GetDeviceDrainRate(); return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::SuitPower_RemoveDevice( const CSuitPowerDevice &device ) { // Make sure this device is active!! if( ! (m_HL2Local.m_bitsActiveDevices & device.GetDeviceID()) ) return false; if( !IsSuitEquipped() ) return false; // Take a little bit of suit power when you disable a device. If the device is shutting off // because the battery is drained, no harm done, the battery charge cannot go below 0. // This code in combination with the delay before the suit can start recharging are a defense // against exploits where the player could rapidly tap sprint and never run out of power. SuitPower_Drain( device.GetDeviceDrainRate() * 0.1f ); m_HL2Local.m_bitsActiveDevices &= ~device.GetDeviceID(); m_flSuitPowerLoad -= device.GetDeviceDrainRate(); if( m_HL2Local.m_bitsActiveDevices == 0x00000000 ) { // With this device turned off, we can set this timer which tells us when the // suit power system entered a no-load state. m_flTimeAllSuitDevicesOff = gpGlobals->curtime; } return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #define SUITPOWER_BEGIN_RECHARGE_DELAY 0.5f bool CHL2_Player::SuitPower_ShouldRecharge( void ) { // Make sure all devices are off. if( m_HL2Local.m_bitsActiveDevices != 0x00000000 ) return false; // Is the system fully charged? if( m_HL2Local.m_flSuitPower >= 100.0f ) return false; // Has the system been in a no-load state for long enough // to begin recharging? if( gpGlobals->curtime < m_flTimeAllSuitDevicesOff + SUITPOWER_BEGIN_RECHARGE_DELAY ) return false; return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- ConVar sk_battery( "sk_battery","0" ); bool CHL2_Player::ApplyBattery( float powerMultiplier ) { const float MAX_NORMAL_BATTERY = 100; if ((ArmorValue() < MAX_NORMAL_BATTERY) && IsSuitEquipped()) { int pct; char szcharge[64]; IncrementArmorValue( sk_battery.GetFloat() * powerMultiplier, MAX_NORMAL_BATTERY ); CPASAttenuationFilter filter( this, "ItemBattery.Touch" ); EmitSound( filter, entindex(), "ItemBattery.Touch" ); CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "ItemPickup" ); WRITE_STRING( "item_battery" ); MessageEnd(); // Suit reports new power level // For some reason this wasn't working in release build -- round it. pct = (int)( (float)(ArmorValue() * 100.0) * (1.0/MAX_NORMAL_BATTERY) + 0.5); pct = (pct / 5); if (pct > 0) pct--; Q_snprintf( szcharge,sizeof(szcharge),"!HEV_%1dP", pct ); //UTIL_EmitSoundSuit(edict(), szcharge); //SetSuitUpdate(szcharge, FALSE, SUIT_NEXT_IN_30SEC); return true; } return false; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CHL2_Player::FlashlightIsOn( void ) { return IsEffectActive( EF_DIMLIGHT ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::FlashlightTurnOn( void ) { if( m_bFlashlightDisabled ) return; if ( Flashlight_UseLegacyVersion() ) { if( !SuitPower_AddDevice( SuitDeviceFlashlight ) ) return; } #ifdef HL2_DLL if( !IsSuitEquipped() ) return; #endif AddEffects( EF_DIMLIGHT ); EmitSound( "HL2Player.FlashLightOn" ); variant_t flashlighton; flashlighton.SetFloat( m_HL2Local.m_flSuitPower / 100.0f ); FirePlayerProxyOutput( "OnFlashlightOn", flashlighton, this, this ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::FlashlightTurnOff( void ) { if ( Flashlight_UseLegacyVersion() ) { if( !SuitPower_RemoveDevice( SuitDeviceFlashlight ) ) return; } RemoveEffects( EF_DIMLIGHT ); EmitSound( "HL2Player.FlashLightOff" ); variant_t flashlightoff; flashlightoff.SetFloat( m_HL2Local.m_flSuitPower / 100.0f ); FirePlayerProxyOutput( "OnFlashlightOff", flashlightoff, this, this ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #define FLASHLIGHT_RANGE Square(600) bool CHL2_Player::IsIlluminatedByFlashlight( CBaseEntity *pEntity, float *flReturnDot ) { if( !FlashlightIsOn() ) return false; if( pEntity->Classify() == CLASS_BARNACLE && pEntity->GetEnemy() == this ) { // As long as my flashlight is on, the barnacle that's pulling me in is considered illuminated. // This is because players often shine their flashlights at Alyx when they are in a barnacle's // grasp, and wonder why Alyx isn't helping. Alyx isn't helping because the light isn't pointed // at the barnacle. This will allow Alyx to see the barnacle no matter which way the light is pointed. return true; } // Within 50 feet? float flDistSqr = GetAbsOrigin().DistToSqr(pEntity->GetAbsOrigin()); if( flDistSqr > FLASHLIGHT_RANGE ) return false; // Within 45 degrees? Vector vecSpot = pEntity->WorldSpaceCenter(); Vector los; // If the eyeposition is too close, move it back. Solves problems // caused by the player being too close the target. if ( flDistSqr < (128 * 128) ) { Vector vecForward; EyeVectors( &vecForward ); Vector vecMovedEyePos = EyePosition() - (vecForward * 128); los = ( vecSpot - vecMovedEyePos ); } else { los = ( vecSpot - EyePosition() ); } VectorNormalize( los ); Vector facingDir = EyeDirection3D( ); float flDot = DotProduct( los, facingDir ); if ( flReturnDot ) { *flReturnDot = flDot; } if ( flDot < 0.92387f ) return false; if( !FVisible(pEntity) ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: Let NPCs know when the flashlight is trained on them //----------------------------------------------------------------------------- void CHL2_Player::CheckFlashlight( void ) { if ( !FlashlightIsOn() ) return; if ( m_flNextFlashlightCheckTime > gpGlobals->curtime ) return; m_flNextFlashlightCheckTime = gpGlobals->curtime + FLASHLIGHT_NPC_CHECK_INTERVAL; // Loop through NPCs looking for illuminated ones for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ ) { CAI_BaseNPC *pNPC = g_AI_Manager.AccessAIs()[i]; float flDot; if ( IsIlluminatedByFlashlight( pNPC, &flDot ) ) { pNPC->PlayerHasIlluminatedNPC( this, flDot ); } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::SetPlayerUnderwater( bool state ) { if ( state ) { SuitPower_AddDevice( SuitDeviceBreather ); } else { SuitPower_RemoveDevice( SuitDeviceBreather ); } BaseClass::SetPlayerUnderwater( state ); } //----------------------------------------------------------------------------- bool CHL2_Player::PassesDamageFilter( const CTakeDamageInfo &info ) { CBaseEntity *pAttacker = info.GetAttacker(); if( pAttacker && pAttacker->MyNPCPointer() && pAttacker->MyNPCPointer()->IsPlayerAlly() ) { return false; } if( m_hPlayerProxy && !m_hPlayerProxy->PassesDamageFilter( info ) ) { return false; } return BaseClass::PassesDamageFilter( info ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::SetFlashlightEnabled( bool bState ) { m_bFlashlightDisabled = !bState; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::InputDisableFlashlight( inputdata_t &inputdata ) { if( FlashlightIsOn() ) FlashlightTurnOff(); SetFlashlightEnabled( false ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::InputEnableFlashlight( inputdata_t &inputdata ) { SetFlashlightEnabled( true ); } //----------------------------------------------------------------------------- // Purpose: Prevent the player from taking fall damage for [n] seconds, but // reset back to taking fall damage after the first impact (so players will be // hurt if they bounce off what they hit). This is the original behavior. //----------------------------------------------------------------------------- void CHL2_Player::InputIgnoreFallDamage( inputdata_t &inputdata ) { float timeToIgnore = inputdata.value.Float(); if ( timeToIgnore <= 0.0 ) timeToIgnore = TIME_IGNORE_FALL_DAMAGE; m_flTimeIgnoreFallDamage = gpGlobals->curtime + timeToIgnore; m_bIgnoreFallDamageResetAfterImpact = true; } //----------------------------------------------------------------------------- // Purpose: Absolutely prevent the player from taking fall damage for [n] seconds. //----------------------------------------------------------------------------- void CHL2_Player::InputIgnoreFallDamageWithoutReset( inputdata_t &inputdata ) { float timeToIgnore = inputdata.value.Float(); if ( timeToIgnore <= 0.0 ) timeToIgnore = TIME_IGNORE_FALL_DAMAGE; m_flTimeIgnoreFallDamage = gpGlobals->curtime + timeToIgnore; m_bIgnoreFallDamageResetAfterImpact = false; } //----------------------------------------------------------------------------- // Purpose: Notification of a player's npc ally in the players squad being killed //----------------------------------------------------------------------------- void CHL2_Player::OnSquadMemberKilled( inputdata_t &data ) { // send a message to the client, to notify the hud of the loss CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "SquadMemberDied" ); MessageEnd(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::NotifyFriendsOfDamage( CBaseEntity *pAttackerEntity ) { CAI_BaseNPC *pAttacker = pAttackerEntity->MyNPCPointer(); if ( pAttacker ) { const Vector &origin = GetAbsOrigin(); for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ ) { const float NEAR_Z = 12*12; const float NEAR_XY_SQ = Square( 50*12 ); CAI_BaseNPC *pNpc = g_AI_Manager.AccessAIs()[i]; if ( pNpc->IsPlayerAlly() ) { const Vector &originNpc = pNpc->GetAbsOrigin(); if ( fabsf( originNpc.z - origin.z ) < NEAR_Z ) { if ( (originNpc.AsVector2D() - origin.AsVector2D()).LengthSqr() < NEAR_XY_SQ ) { pNpc->OnFriendDamaged( this, pAttacker ); } } } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- ConVar test_massive_dmg("test_massive_dmg", "30" ); ConVar test_massive_dmg_clip("test_massive_dmg_clip", "0.5" ); int CHL2_Player::OnTakeDamage( const CTakeDamageInfo &info ) { if ( GlobalEntity_GetState( "gordon_invulnerable" ) == GLOBAL_ON ) return 0; // ignore fall damage if instructed to do so by input if ( ( info.GetDamageType() & DMG_FALL ) && m_flTimeIgnoreFallDamage > gpGlobals->curtime ) { // usually, we will reset the input flag after the first impact. However there is another input that // prevents this behavior. if ( m_bIgnoreFallDamageResetAfterImpact ) { m_flTimeIgnoreFallDamage = 0; } return 0; } if( info.GetDamageType() & DMG_BLAST_SURFACE ) { if( GetWaterLevel() > 2 ) { // Don't take blast damage from anything above the surface. if( info.GetInflictor()->GetWaterLevel() == 0 ) { return 0; } } } if ( info.GetDamage() > 0.0f ) { m_flLastDamageTime = gpGlobals->curtime; if ( info.GetAttacker() ) NotifyFriendsOfDamage( info.GetAttacker() ); } // Modify the amount of damage the player takes, based on skill. CTakeDamageInfo playerDamage = info; // Should we run this damage through the skill level adjustment? bool bAdjustForSkillLevel = true; if( info.GetDamageType() == DMG_GENERIC && info.GetAttacker() == this && info.GetInflictor() == this ) { // Only do a skill level adjustment if the player isn't his own attacker AND inflictor. // This prevents damage from SetHealth() inputs from being adjusted for skill level. bAdjustForSkillLevel = false; } if ( GetVehicleEntity() != NULL && GlobalEntity_GetState("gordon_protect_driver") == GLOBAL_ON ) { if( playerDamage.GetDamage() > test_massive_dmg.GetFloat() && playerDamage.GetInflictor() == GetVehicleEntity() && (playerDamage.GetDamageType() & DMG_CRUSH) ) { playerDamage.ScaleDamage( test_massive_dmg_clip.GetFloat() / playerDamage.GetDamage() ); } } if( bAdjustForSkillLevel ) { playerDamage.AdjustPlayerDamageTakenForSkillLevel(); } gamestats->Event_PlayerDamage( this, info ); return BaseClass::OnTakeDamage( playerDamage ); } //----------------------------------------------------------------------------- // Purpose: // Input : &info - //----------------------------------------------------------------------------- int CHL2_Player::OnTakeDamage_Alive( const CTakeDamageInfo &info ) { // Drown if( info.GetDamageType() & DMG_DROWN ) { if( m_idrowndmg == m_idrownrestored ) { EmitSound( "Player.DrownStart" ); } else { EmitSound( "Player.DrownContinue" ); } } // Burnt if ( info.GetDamageType() & DMG_BURN ) { EmitSound( "HL2Player.BurnPain" ); } if( (info.GetDamageType() & DMG_SLASH) && hl2_episodic.GetBool() ) { if( m_afPhysicsFlags & PFLAG_USING ) { // Stop the player using a rotating button for a short time if hit by a creature's melee attack. // This is for the antlion burrow-corking training in EP1 (sjb). SuspendUse( 0.5f ); } } // Call the base class implementation return BaseClass::OnTakeDamage_Alive( info ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::OnDamagedByExplosion( const CTakeDamageInfo &info ) { if ( info.GetInflictor() && info.GetInflictor()->ClassMatches( "mortarshell" ) ) { // No ear ringing for mortar UTIL_ScreenShake( info.GetInflictor()->GetAbsOrigin(), 4.0, 1.0, 0.5, 1000, SHAKE_START, false ); return; } BaseClass::OnDamagedByExplosion( info ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::ShouldShootMissTarget( CBaseCombatCharacter *pAttacker ) { if( gpGlobals->curtime > m_flTargetFindTime ) { // Put this off into the future again. m_flTargetFindTime = gpGlobals->curtime + random->RandomFloat( 3, 5 ); return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Notifies Alyx that player has put a combine ball into a socket so she can comment on it. // Input : pCombineBall - ball the was socketed //----------------------------------------------------------------------------- void CHL2_Player::CombineBallSocketed( CPropCombineBall *pCombineBall ) { #ifdef HL2_EPISODIC CNPC_Alyx *pAlyx = CNPC_Alyx::GetAlyx(); if ( pAlyx ) { pAlyx->CombineBallSocketed( pCombineBall->NumBounces() ); } #endif } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::Event_KilledOther( CBaseEntity *pVictim, const CTakeDamageInfo &info ) { BaseClass::Event_KilledOther( pVictim, info ); #ifdef HL2_EPISODIC CAI_BaseNPC **ppAIs = g_AI_Manager.AccessAIs(); for ( int i = 0; i < g_AI_Manager.NumAIs(); i++ ) { if ( ppAIs[i] && ppAIs[i]->IRelationType(this) == D_LI ) { ppAIs[i]->OnPlayerKilledOther( pVictim, info ); } } #endif } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::Event_Killed( const CTakeDamageInfo &info ) { BaseClass::Event_Killed( info ); FirePlayerProxyOutput( "PlayerDied", variant_t(), this, this ); NotifyScriptsOfDeath(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::NotifyScriptsOfDeath( void ) { CBaseEntity *pEnt = gEntList.FindEntityByClassname( NULL, "scripted_sequence" ); while( pEnt ) { variant_t emptyVariant; pEnt->AcceptInput( "ScriptPlayerDeath", NULL, NULL, emptyVariant, 0 ); pEnt = gEntList.FindEntityByClassname( pEnt, "scripted_sequence" ); } pEnt = gEntList.FindEntityByClassname( NULL, "logic_choreographed_scene" ); while( pEnt ) { variant_t emptyVariant; pEnt->AcceptInput( "ScriptPlayerDeath", NULL, NULL, emptyVariant, 0 ); pEnt = gEntList.FindEntityByClassname( pEnt, "logic_choreographed_scene" ); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CHL2_Player::GetAutoaimVector( autoaim_params_t &params ) { BaseClass::GetAutoaimVector( params ); if ( IsX360() ) { if( IsInAVehicle() ) { if( m_hLockedAutoAimEntity && m_hLockedAutoAimEntity->IsAlive() && ShouldKeepLockedAutoaimTarget(m_hLockedAutoAimEntity) ) { if( params.m_hAutoAimEntity && params.m_hAutoAimEntity != m_hLockedAutoAimEntity ) { // Autoaim has picked a new target. Switch. m_hLockedAutoAimEntity = params.m_hAutoAimEntity; } // Ignore autoaim and just keep aiming at this target. params.m_hAutoAimEntity = m_hLockedAutoAimEntity; Vector vecTarget = m_hLockedAutoAimEntity->BodyTarget( EyePosition(), false ); Vector vecDir = vecTarget - EyePosition(); VectorNormalize( vecDir ); params.m_vecAutoAimDir = vecDir; params.m_vecAutoAimPoint = vecTarget; return; } else { m_hLockedAutoAimEntity = NULL; } } // If the player manually gets his crosshair onto a target, make that target sticky if( params.m_fScale != AUTOAIM_SCALE_DIRECT_ONLY ) { // Only affect this for 'real' queries //if( params.m_hAutoAimEntity && params.m_bOnTargetNatural ) if( params.m_hAutoAimEntity ) { // Turn on sticky. m_HL2Local.m_bStickyAutoAim = true; if( IsInAVehicle() ) { m_hLockedAutoAimEntity = params.m_hAutoAimEntity; } } else if( !params.m_hAutoAimEntity ) { // Turn off sticky only if there's no target at all. m_HL2Local.m_bStickyAutoAim = false; m_hLockedAutoAimEntity = NULL; } } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::ShouldKeepLockedAutoaimTarget( EHANDLE hLockedTarget ) { Vector vecLooking; Vector vecToTarget; vecToTarget = hLockedTarget->WorldSpaceCenter() - EyePosition(); float flDist = vecToTarget.Length2D(); VectorNormalize( vecToTarget ); if( flDist > autoaim_max_dist.GetFloat() ) return false; float flDot; vecLooking = EyeDirection3D(); flDot = DotProduct( vecLooking, vecToTarget ); if( flDot < autoaim_unlock_target.GetFloat() ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: // Input : iCount - // iAmmoIndex - // bSuppressSound - // Output : int //----------------------------------------------------------------------------- int CHL2_Player::GiveAmmo( int nCount, int nAmmoIndex, bool bSuppressSound) { // Don't try to give the player invalid ammo indices. if (nAmmoIndex < 0) return 0; bool bCheckAutoSwitch = false; if (!HasAnyAmmoOfType(nAmmoIndex)) { bCheckAutoSwitch = true; } int nAdd = BaseClass::GiveAmmo(nCount, nAmmoIndex, bSuppressSound); if ( nCount > 0 && nAdd == 0 ) { // we've been denied the pickup, display a hud icon to show that CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "AmmoDenied" ); WRITE_SHORT( nAmmoIndex ); MessageEnd(); } // // If I was dry on ammo for my best weapon and justed picked up ammo for it, // autoswitch to my best weapon now. // if (bCheckAutoSwitch) { CBaseCombatWeapon *pWeapon = g_pGameRules->GetNextBestWeapon(this, GetActiveWeapon()); if ( pWeapon && pWeapon->GetPrimaryAmmoType() == nAmmoIndex ) { SwitchToNextBestWeapon(GetActiveWeapon()); } } return nAdd; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CHL2_Player::Weapon_CanUse( CBaseCombatWeapon *pWeapon ) { #ifndef HL2MP if ( pWeapon->ClassMatches( "weapon_stunstick" ) ) { if ( ApplyBattery( 0.5 ) ) UTIL_Remove( pWeapon ); return false; } #endif return BaseClass::Weapon_CanUse( pWeapon ); } //----------------------------------------------------------------------------- // Purpose: // Input : *pWeapon - //----------------------------------------------------------------------------- void CHL2_Player::Weapon_Equip( CBaseCombatWeapon *pWeapon ) { #if HL2_SINGLE_PRIMARY_WEAPON_MODE if ( pWeapon->GetSlot() == WEAPON_PRIMARY_SLOT ) { Weapon_DropSlot( WEAPON_PRIMARY_SLOT ); } #endif if( GetActiveWeapon() == NULL ) { m_HL2Local.m_bWeaponLowered = false; } BaseClass::Weapon_Equip( pWeapon ); } //----------------------------------------------------------------------------- // Purpose: Player reacts to bumping a weapon. // Input : pWeapon - the weapon that the player bumped into. // Output : Returns true if player picked up the weapon //----------------------------------------------------------------------------- bool CHL2_Player::BumpWeapon( CBaseCombatWeapon *pWeapon ) { #if HL2_SINGLE_PRIMARY_WEAPON_MODE CBaseCombatCharacter *pOwner = pWeapon->GetOwner(); // Can I have this weapon type? if ( pOwner || !Weapon_CanUse( pWeapon ) || !g_pGameRules->CanHavePlayerItem( this, pWeapon ) ) { if ( gEvilImpulse101 ) { UTIL_Remove( pWeapon ); } return false; } // ---------------------------------------- // If I already have it just take the ammo // ---------------------------------------- if (Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType())) { //Only remove the weapon if we attained ammo from it if ( Weapon_EquipAmmoOnly( pWeapon ) == false ) return false; // Only remove me if I have no ammo left // Can't just check HasAnyAmmo because if I don't use clips, I want to be removed, if ( pWeapon->UsesClipsForAmmo1() && pWeapon->HasPrimaryAmmo() ) return false; UTIL_Remove( pWeapon ); return false; } // ------------------------- // Otherwise take the weapon // ------------------------- else { //Make sure we're not trying to take a new weapon type we already have if ( Weapon_SlotOccupied( pWeapon ) ) { CBaseCombatWeapon *pActiveWeapon = Weapon_GetSlot( WEAPON_PRIMARY_SLOT ); if ( pActiveWeapon != NULL && pActiveWeapon->HasAnyAmmo() == false && Weapon_CanSwitchTo( pWeapon ) ) { Weapon_Equip( pWeapon ); return true; } //Attempt to take ammo if this is the gun we're holding already if ( Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ) ) { Weapon_EquipAmmoOnly( pWeapon ); } return false; } pWeapon->CheckRespawn(); pWeapon->AddSolidFlags( FSOLID_NOT_SOLID ); pWeapon->AddEffects( EF_NODRAW ); Weapon_Equip( pWeapon ); EmitSound( "HL2Player.PickupWeapon" ); return true; } #else return BaseClass::BumpWeapon( pWeapon ); #endif } //----------------------------------------------------------------------------- // Purpose: // Input : *cmd - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::ClientCommand( const CCommand &args ) { #if HL2_SINGLE_PRIMARY_WEAPON_MODE //Drop primary weapon if ( !Q_stricmp( args[0], "DropPrimary" ) ) { Weapon_DropSlot( WEAPON_PRIMARY_SLOT ); return true; } #endif if ( !Q_stricmp( args[0], "emit" ) ) { CSingleUserRecipientFilter filter( this ); if ( args.ArgC() > 1 ) { EmitSound( filter, entindex(), args[ 1 ] ); } else { EmitSound( filter, entindex(), "Test.Sound" ); } return true; } return BaseClass::ClientCommand( args ); } //----------------------------------------------------------------------------- // Purpose: // Output : void CBasePlayer::PlayerUse //----------------------------------------------------------------------------- void CHL2_Player::PlayerUse ( void ) { // Was use pressed or released? if ( ! ((m_nButtons | m_afButtonPressed | m_afButtonReleased) & IN_USE) ) return; if ( m_afButtonPressed & IN_USE ) { // Currently using a latched entity? if ( ClearUseEntity() ) { return; } else { if ( m_afPhysicsFlags & PFLAG_DIROVERRIDE ) { m_afPhysicsFlags &= ~PFLAG_DIROVERRIDE; m_iTrain = TRAIN_NEW|TRAIN_OFF; return; } else { // Start controlling the train! CBaseEntity *pTrain = GetGroundEntity(); if ( pTrain && !(m_nButtons & IN_JUMP) && (GetFlags() & FL_ONGROUND) && (pTrain->ObjectCaps() & FCAP_DIRECTIONAL_USE) && pTrain->OnControls(this) ) { m_afPhysicsFlags |= PFLAG_DIROVERRIDE; m_iTrain = TrainSpeed(pTrain->m_flSpeed, ((CFuncTrackTrain*)pTrain)->GetMaxSpeed()); m_iTrain |= TRAIN_NEW; EmitSound( "HL2Player.TrainUse" ); return; } } } // Tracker 3926: We can't +USE something if we're climbing a ladder if ( GetMoveType() == MOVETYPE_LADDER ) { return; } } if( m_flTimeUseSuspended > gpGlobals->curtime ) { // Something has temporarily stopped us being able to USE things. // Obviously, this should be used very carefully.(sjb) return; } CBaseEntity *pUseEntity = FindUseEntity(); bool usedSomething = false; // Found an object if ( pUseEntity ) { //!!!UNDONE: traceline here to prevent +USEing buttons through walls int caps = pUseEntity->ObjectCaps(); variant_t emptyVariant; if ( m_afButtonPressed & IN_USE ) { // Robin: Don't play sounds for NPCs, because NPCs will allow respond with speech. if ( !pUseEntity->MyNPCPointer() ) { EmitSound( "HL2Player.Use" ); } } if ( ( (m_nButtons & IN_USE) && (caps & FCAP_CONTINUOUS_USE) ) || ( (m_afButtonPressed & IN_USE) && (caps & (FCAP_IMPULSE_USE|FCAP_ONOFF_USE)) ) ) { if ( caps & FCAP_CONTINUOUS_USE ) m_afPhysicsFlags |= PFLAG_USING; pUseEntity->AcceptInput( "Use", this, this, emptyVariant, USE_TOGGLE ); usedSomething = true; } // UNDONE: Send different USE codes for ON/OFF. Cache last ONOFF_USE object to send 'off' if you turn away else if ( (m_afButtonReleased & IN_USE) && (pUseEntity->ObjectCaps() & FCAP_ONOFF_USE) ) // BUGBUG This is an "off" use { pUseEntity->AcceptInput( "Use", this, this, emptyVariant, USE_TOGGLE ); usedSomething = true; } #if HL2_SINGLE_PRIMARY_WEAPON_MODE //Check for weapon pick-up if ( m_afButtonPressed & IN_USE ) { CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(pUseEntity); if ( ( pWeapon != NULL ) && ( Weapon_CanSwitchTo( pWeapon ) ) ) { //Try to take ammo or swap the weapon if ( Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType() ) ) { Weapon_EquipAmmoOnly( pWeapon ); } else { Weapon_DropSlot( pWeapon->GetSlot() ); Weapon_Equip( pWeapon ); } usedSomething = true; } } #endif } else if ( m_afButtonPressed & IN_USE ) { // Signal that we want to play the deny sound, unless the user is +USEing on a ladder! // The sound is emitted in ItemPostFrame, since that occurs after GameMovement::ProcessMove which // lets the ladder code unset this flag. m_bPlayUseDenySound = true; } // Debounce the use key if ( usedSomething && pUseEntity ) { m_Local.m_nOldButtons |= IN_USE; m_afButtonPressed &= ~IN_USE; } } ConVar sv_show_crosshair_target( "sv_show_crosshair_target", "0" ); //----------------------------------------------------------------------------- // Purpose: Updates the posture of the weapon from lowered to ready //----------------------------------------------------------------------------- void CHL2_Player::UpdateWeaponPosture( void ) { CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon()); if ( pWeapon && m_LowerWeaponTimer.Expired() && pWeapon->CanLower() ) { m_LowerWeaponTimer.Set( .3 ); VPROF( "CHL2_Player::UpdateWeaponPosture-CheckLower" ); Vector vecAim = BaseClass::GetAutoaimVector( AUTOAIM_SCALE_DIRECT_ONLY ); const float CHECK_FRIENDLY_RANGE = 50 * 12; trace_t tr; UTIL_TraceLine( EyePosition(), EyePosition() + vecAim * CHECK_FRIENDLY_RANGE, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); CBaseEntity *aimTarget = tr.m_pEnt; //If we're over something if ( aimTarget && !tr.DidHitWorld() ) { if ( !aimTarget->IsNPC() || aimTarget->MyNPCPointer()->GetState() != NPC_STATE_COMBAT ) { Disposition_t dis = IRelationType( aimTarget ); //Debug info for seeing what an object "cons" as if ( sv_show_crosshair_target.GetBool() ) { int text_offset = BaseClass::DrawDebugTextOverlays(); char tempstr[255]; switch ( dis ) { case D_LI: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Like" ); break; case D_HT: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Hate" ); break; case D_FR: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Fear" ); break; case D_NU: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: Neutral" ); break; default: case D_ER: Q_snprintf( tempstr, sizeof(tempstr), "Disposition: !!!ERROR!!!" ); break; } //Draw the text NDebugOverlay::EntityText( aimTarget->entindex(), text_offset, tempstr, 0 ); } //See if we hates it if ( dis == D_LI ) { //We're over a friendly, drop our weapon if ( Weapon_Lower() == false ) { //FIXME: We couldn't lower our weapon! } return; } } } if ( Weapon_Ready() == false ) { //FIXME: We couldn't raise our weapon! } } if( g_pGameRules->GetAutoAimMode() != AUTOAIM_NONE ) { if( !pWeapon ) { // This tells the client to draw no crosshair m_HL2Local.m_bWeaponLowered = true; return; } else { if( !pWeapon->CanLower() && m_HL2Local.m_bWeaponLowered ) m_HL2Local.m_bWeaponLowered = false; } if( !m_AutoaimTimer.Expired() ) return; m_AutoaimTimer.Set( .1 ); VPROF( "hl2_x360_aiming" ); // Call the autoaim code to update the local player data, which allows the client to update. autoaim_params_t params; params.m_vecAutoAimPoint.Init(); params.m_vecAutoAimDir.Init(); params.m_fScale = AUTOAIM_SCALE_DEFAULT; params.m_fMaxDist = autoaim_max_dist.GetFloat(); GetAutoaimVector( params ); m_HL2Local.m_hAutoAimTarget.Set( params.m_hAutoAimEntity ); m_HL2Local.m_vecAutoAimPoint.Set( params.m_vecAutoAimPoint ); m_HL2Local.m_bAutoAimTarget = ( params.m_bAutoAimAssisting || params.m_bOnTargetNatural ); return; } else { // Make sure there's no residual autoaim target if the user changes the xbox_aiming convar on the fly. m_HL2Local.m_hAutoAimTarget.Set(NULL); } } //----------------------------------------------------------------------------- // Purpose: Lowers the weapon posture (for hovering over friendlies) // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::Weapon_Lower( void ) { VPROF( "CHL2_Player::Weapon_Lower" ); // Already lowered? if ( m_HL2Local.m_bWeaponLowered ) return true; m_HL2Local.m_bWeaponLowered = true; CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon()); if ( pWeapon == NULL ) return false; return pWeapon->Lower(); } //----------------------------------------------------------------------------- // Purpose: Returns the weapon posture to normal // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CHL2_Player::Weapon_Ready( void ) { VPROF( "CHL2_Player::Weapon_Ready" ); // Already ready? if ( m_HL2Local.m_bWeaponLowered == false ) return true; m_HL2Local.m_bWeaponLowered = false; CBaseCombatWeapon *pWeapon = dynamic_cast<CBaseCombatWeapon *>(GetActiveWeapon()); if ( pWeapon == NULL ) return false; return pWeapon->Ready(); } //----------------------------------------------------------------------------- // Purpose: Returns whether or not we can switch to the given weapon. // Input : pWeapon - //----------------------------------------------------------------------------- bool CHL2_Player::Weapon_CanSwitchTo( CBaseCombatWeapon *pWeapon ) { CBasePlayer *pPlayer = (CBasePlayer *)this; #if !defined( CLIENT_DLL ) IServerVehicle *pVehicle = pPlayer->GetVehicle(); #else IClientVehicle *pVehicle = pPlayer->GetVehicle(); #endif if (pVehicle && !pPlayer->UsingStandardWeaponsInVehicle()) return false; ///// // SO2 - James // Allow players to switch to weapons that do not have any ammo /*if ( !pWeapon->HasAnyAmmo() && !GetAmmoCount( pWeapon->m_iPrimaryAmmoType ) ) return false;*/ ///// if ( !pWeapon->CanDeploy() ) return false; if ( GetActiveWeapon() ) { if ( PhysCannonGetHeldEntity( GetActiveWeapon() ) == pWeapon && Weapon_OwnsThisType( pWeapon->GetClassname(), pWeapon->GetSubType()) ) { return true; } if ( !GetActiveWeapon()->CanHolster() ) return false; } return true; } void CHL2_Player::PickupObject( CBaseEntity *pObject, bool bLimitMassAndSize ) { // can't pick up what you're standing on if ( GetGroundEntity() == pObject ) return; if ( bLimitMassAndSize == true ) { if ( CBasePlayer::CanPickupObject( pObject, 35, 128 ) == false ) return; } // Can't be picked up if NPCs are on me if ( pObject->HasNPCsOnIt() ) return; PlayerPickupObject( this, pObject ); } //----------------------------------------------------------------------------- // Purpose: // Output : CBaseEntity //----------------------------------------------------------------------------- bool CHL2_Player::IsHoldingEntity( CBaseEntity *pEnt ) { return PlayerPickupControllerIsHoldingEntity( m_hUseEntity, pEnt ); } float CHL2_Player::GetHeldObjectMass( IPhysicsObject *pHeldObject ) { float mass = PlayerPickupGetHeldObjectMass( m_hUseEntity, pHeldObject ); if ( mass == 0.0f ) { mass = PhysCannonGetHeldObjectMass( GetActiveWeapon(), pHeldObject ); } return mass; } CBaseEntity *CHL2_Player::GetHeldObject( void ) { return PhysCannonGetHeldEntity( GetActiveWeapon() ); } //----------------------------------------------------------------------------- // Purpose: Force the player to drop any physics objects he's carrying //----------------------------------------------------------------------------- void CHL2_Player::ForceDropOfCarriedPhysObjects( CBaseEntity *pOnlyIfHoldingThis ) { if ( PhysIsInCallback() ) { variant_t value; g_EventQueue.AddEvent( this, "ForceDropPhysObjects", value, 0.01f, pOnlyIfHoldingThis, this ); return; } #ifdef HL2_EPISODIC if ( hl2_episodic.GetBool() ) { CBaseEntity *pHeldEntity = PhysCannonGetHeldEntity( GetActiveWeapon() ); if( pHeldEntity && pHeldEntity->ClassMatches( "grenade_helicopter" ) ) { return; } } #endif // Drop any objects being handheld. ClearUseEntity(); // Then force the physcannon to drop anything it's holding, if it's our active weapon PhysCannonForceDrop( GetActiveWeapon(), NULL ); } void CHL2_Player::InputForceDropPhysObjects( inputdata_t &data ) { ForceDropOfCarriedPhysObjects( data.pActivator ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2_Player::UpdateClientData( void ) { if (m_DmgTake || m_DmgSave || m_bitsHUDDamage != m_bitsDamageType) { // Comes from inside me if not set Vector damageOrigin = GetLocalOrigin(); // send "damage" message // causes screen to flash, and pain compass to show direction of damage damageOrigin = m_DmgOrigin; // only send down damage type that have hud art int iShowHudDamage = g_pGameRules->Damage_GetShowOnHud(); int visibleDamageBits = m_bitsDamageType & iShowHudDamage; m_DmgTake = clamp( m_DmgTake, 0, 255 ); m_DmgSave = clamp( m_DmgSave, 0, 255 ); // If we're poisoned, but it wasn't this frame, don't send the indicator // Without this check, any damage that occured to the player while they were // recovering from a poison bite would register as poisonous as well and flash // the whole screen! -- jdw if ( visibleDamageBits & DMG_POISON ) { float flLastPoisonedDelta = gpGlobals->curtime - m_tbdPrev; if ( flLastPoisonedDelta > 0.1f ) { visibleDamageBits &= ~DMG_POISON; } } CSingleUserRecipientFilter user( this ); user.MakeReliable(); UserMessageBegin( user, "Damage" ); WRITE_BYTE( m_DmgSave ); WRITE_BYTE( m_DmgTake ); WRITE_LONG( visibleDamageBits ); WRITE_FLOAT( damageOrigin.x ); //BUG: Should be fixed point (to hud) not floats WRITE_FLOAT( damageOrigin.y ); //BUG: However, the HUD does _not_ implement bitfield messages (yet) WRITE_FLOAT( damageOrigin.z ); //BUG: We use WRITE_VEC3COORD for everything else MessageEnd(); m_DmgTake = 0; m_DmgSave = 0; m_bitsHUDDamage = m_bitsDamageType; // Clear off non-time-based damage indicators int iTimeBasedDamage = g_pGameRules->Damage_GetTimeBased(); m_bitsDamageType &= iTimeBasedDamage; } // Update Flashlight #ifdef HL2_EPISODIC if ( Flashlight_UseLegacyVersion() == false ) { if ( FlashlightIsOn() && sv_infinite_aux_power.GetBool() == false ) { m_HL2Local.m_flFlashBattery -= FLASH_DRAIN_TIME * gpGlobals->frametime; if ( m_HL2Local.m_flFlashBattery < 0.0f ) { FlashlightTurnOff(); m_HL2Local.m_flFlashBattery = 0.0f; } } else { m_HL2Local.m_flFlashBattery += FLASH_CHARGE_TIME * gpGlobals->frametime; if ( m_HL2Local.m_flFlashBattery > 100.0f ) { m_HL2Local.m_flFlashBattery = 100.0f; } } } else { m_HL2Local.m_flFlashBattery = -1.0f; } #endif // HL2_EPISODIC BaseClass::UpdateClientData(); } //--------------------------------------------------------- //--------------------------------------------------------- void CHL2_Player::OnRestore() { BaseClass::OnRestore(); m_pPlayerAISquad = g_AI_SquadManager.FindCreateSquad(AllocPooledString(PLAYER_SQUADNAME)); } //--------------------------------------------------------- //--------------------------------------------------------- Vector CHL2_Player::EyeDirection2D( void ) { Vector vecReturn = EyeDirection3D(); vecReturn.z = 0; vecReturn.AsVector2D().NormalizeInPlace(); return vecReturn; } //--------------------------------------------------------- //--------------------------------------------------------- Vector CHL2_Player::EyeDirection3D( void ) { Vector vecForward; // Return the vehicle angles if we request them if ( GetVehicle() != NULL ) { CacheVehicleView(); EyeVectors( &vecForward ); return vecForward; } AngleVectors( EyeAngles(), &vecForward ); return vecForward; } //--------------------------------------------------------- //--------------------------------------------------------- bool CHL2_Player::Weapon_Switch( CBaseCombatWeapon *pWeapon, int viewmodelindex ) { MDLCACHE_CRITICAL_SECTION(); // Recalculate proficiency! SetCurrentWeaponProficiency( CalcWeaponProficiency( pWeapon ) ); // Come out of suit zoom mode if ( IsZooming() ) { StopZooming(); } return BaseClass::Weapon_Switch( pWeapon, viewmodelindex ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- WeaponProficiency_t CHL2_Player::CalcWeaponProficiency( CBaseCombatWeapon *pWeapon ) { WeaponProficiency_t proficiency; proficiency = WEAPON_PROFICIENCY_PERFECT; if( weapon_showproficiency.GetBool() != 0 ) { Msg("Player switched to %s, proficiency is %s\n", pWeapon->GetClassname(), GetWeaponProficiencyName( proficiency ) ); } return proficiency; } //----------------------------------------------------------------------------- // Purpose: override how single player rays hit the player //----------------------------------------------------------------------------- bool LineCircleIntersection( const Vector2D &center, const float radius, const Vector2D &vLinePt, const Vector2D &vLineDir, float *fIntersection1, float *fIntersection2) { // Line = P + Vt // Sphere = r (assume we've translated to origin) // (P + Vt)^2 = r^2 // VVt^2 + 2PVt + (PP - r^2) // Solve as quadratic: (-b +/- sqrt(b^2 - 4ac)) / 2a // If (b^2 - 4ac) is < 0 there is no solution. // If (b^2 - 4ac) is = 0 there is one solution (a case this function doesn't support). // If (b^2 - 4ac) is > 0 there are two solutions. Vector2D P; float a, b, c, sqr, insideSqr; // Translate circle to origin. P[0] = vLinePt[0] - center[0]; P[1] = vLinePt[1] - center[1]; a = vLineDir.Dot(vLineDir); b = 2.0f * P.Dot(vLineDir); c = P.Dot(P) - (radius * radius); insideSqr = b*b - 4*a*c; if(insideSqr <= 0.000001f) return false; // Ok, two solutions. sqr = (float)FastSqrt(insideSqr); float denom = 1.0 / (2.0f * a); *fIntersection1 = (-b - sqr) * denom; *fIntersection2 = (-b + sqr) * denom; return true; } static void Collision_ClearTrace( const Vector &vecRayStart, const Vector &vecRayDelta, CBaseTrace *pTrace ) { pTrace->startpos = vecRayStart; pTrace->endpos = vecRayStart; pTrace->endpos += vecRayDelta; pTrace->startsolid = false; pTrace->allsolid = false; pTrace->fraction = 1.0f; pTrace->contents = 0; } bool IntersectRayWithAACylinder( const Ray_t &ray, const Vector &center, float radius, float height, CBaseTrace *pTrace ) { Assert( ray.m_IsRay ); Collision_ClearTrace( ray.m_Start, ray.m_Delta, pTrace ); // First intersect the ray with the top + bottom planes float halfHeight = height * 0.5; // Handle parallel case Vector vStart = ray.m_Start - center; Vector vEnd = vStart + ray.m_Delta; float flEnterFrac, flLeaveFrac; if (FloatMakePositive(ray.m_Delta.z) < 1e-8) { if ( (vStart.z < -halfHeight) || (vStart.z > halfHeight) ) { return false; // no hit } flEnterFrac = 0.0f; flLeaveFrac = 1.0f; } else { // Clip the ray to the top and bottom of box flEnterFrac = IntersectRayWithAAPlane( vStart, vEnd, 2, 1, halfHeight); flLeaveFrac = IntersectRayWithAAPlane( vStart, vEnd, 2, 1, -halfHeight); if ( flLeaveFrac < flEnterFrac ) { float temp = flLeaveFrac; flLeaveFrac = flEnterFrac; flEnterFrac = temp; } if ( flLeaveFrac < 0 || flEnterFrac > 1) { return false; } } // Intersect with circle float flCircleEnterFrac, flCircleLeaveFrac; if ( !LineCircleIntersection( vec3_origin.AsVector2D(), radius, vStart.AsVector2D(), ray.m_Delta.AsVector2D(), &flCircleEnterFrac, &flCircleLeaveFrac ) ) { return false; // no hit } Assert( flCircleEnterFrac <= flCircleLeaveFrac ); if ( flCircleLeaveFrac < 0 || flCircleEnterFrac > 1) { return false; } if ( flEnterFrac < flCircleEnterFrac ) flEnterFrac = flCircleEnterFrac; if ( flLeaveFrac > flCircleLeaveFrac ) flLeaveFrac = flCircleLeaveFrac; if ( flLeaveFrac < flEnterFrac ) return false; VectorMA( ray.m_Start, flEnterFrac , ray.m_Delta, pTrace->endpos ); pTrace->fraction = flEnterFrac; pTrace->contents = CONTENTS_SOLID; // Calculate the point on our center line where we're nearest the intersection point Vector collisionCenter; CalcClosestPointOnLineSegment( pTrace->endpos, center + Vector( 0, 0, halfHeight ), center - Vector( 0, 0, halfHeight ), collisionCenter ); // Our normal is the direction from that center point to the intersection point pTrace->plane.normal = pTrace->endpos - collisionCenter; VectorNormalize( pTrace->plane.normal ); return true; } bool CHL2_Player::TestHitboxes( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr ) { if( g_pGameRules->IsMultiplayer() ) { return BaseClass::TestHitboxes( ray, fContentsMask, tr ); } else { Assert( ray.m_IsRay ); Vector mins, maxs; mins = WorldAlignMins(); maxs = WorldAlignMaxs(); if ( IntersectRayWithAACylinder( ray, WorldSpaceCenter(), maxs.x * PLAYER_HULL_REDUCTION, maxs.z - mins.z, &tr ) ) { tr.hitbox = 0; CStudioHdr *pStudioHdr = GetModelPtr( ); if (!pStudioHdr) return false; mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( m_nHitboxSet ); if ( !set || !set->numhitboxes ) return false; mstudiobbox_t *pbox = set->pHitbox( tr.hitbox ); mstudiobone_t *pBone = pStudioHdr->pBone(pbox->bone); tr.surface.name = "**studio**"; tr.surface.flags = SURF_HITBOX; tr.surface.surfaceProps = physprops->GetSurfaceIndex( pBone->pszSurfaceProp() ); } return true; } } //--------------------------------------------------------- // Show the player's scaled down bbox that we use for // bullet impacts. //--------------------------------------------------------- void CHL2_Player::DrawDebugGeometryOverlays(void) { BaseClass::DrawDebugGeometryOverlays(); if (m_debugOverlays & OVERLAY_BBOX_BIT) { Vector mins, maxs; mins = WorldAlignMins(); maxs = WorldAlignMaxs(); mins.x *= PLAYER_HULL_REDUCTION; mins.y *= PLAYER_HULL_REDUCTION; maxs.x *= PLAYER_HULL_REDUCTION; maxs.y *= PLAYER_HULL_REDUCTION; NDebugOverlay::Box( GetAbsOrigin(), mins, maxs, 255, 0, 0, 100, 0 ); } } //----------------------------------------------------------------------------- // Purpose: Helper to remove from ladder //----------------------------------------------------------------------------- void CHL2_Player::ExitLadder() { if ( MOVETYPE_LADDER != GetMoveType() ) return; SetMoveType( MOVETYPE_WALK ); SetMoveCollide( MOVECOLLIDE_DEFAULT ); // Remove from ladder m_HL2Local.m_hLadder.Set( NULL ); } surfacedata_t *CHL2_Player::GetLadderSurface( const Vector &origin ) { extern const char *FuncLadder_GetSurfaceprops(CBaseEntity *pLadderEntity); CBaseEntity *pLadder = m_HL2Local.m_hLadder.Get(); if ( pLadder ) { const char *pSurfaceprops = FuncLadder_GetSurfaceprops(pLadder); // get ladder material from func_ladder return physprops->GetSurfaceData( physprops->GetSurfaceIndex( pSurfaceprops ) ); } return BaseClass::GetLadderSurface(origin); } //----------------------------------------------------------------------------- // Purpose: Queues up a use deny sound, played in ItemPostFrame. //----------------------------------------------------------------------------- void CHL2_Player::PlayUseDenySound() { m_bPlayUseDenySound = true; } void CHL2_Player::ItemPostFrame() { BaseClass::ItemPostFrame(); if ( m_bPlayUseDenySound ) { m_bPlayUseDenySound = false; EmitSound( "HL2Player.UseDeny" ); } } void CHL2_Player::StartWaterDeathSounds( void ) { CPASAttenuationFilter filter( this ); if ( m_sndLeeches == NULL ) { m_sndLeeches = (CSoundEnvelopeController::GetController()).SoundCreate( filter, entindex(), CHAN_STATIC, "coast.leech_bites_loop" , ATTN_NORM ); } if ( m_sndLeeches ) { (CSoundEnvelopeController::GetController()).Play( m_sndLeeches, 1.0f, 100 ); } if ( m_sndWaterSplashes == NULL ) { m_sndWaterSplashes = (CSoundEnvelopeController::GetController()).SoundCreate( filter, entindex(), CHAN_STATIC, "coast.leech_water_churn_loop" , ATTN_NORM ); } if ( m_sndWaterSplashes ) { (CSoundEnvelopeController::GetController()).Play( m_sndWaterSplashes, 1.0f, 100 ); } } void CHL2_Player::StopWaterDeathSounds( void ) { if ( m_sndLeeches ) { (CSoundEnvelopeController::GetController()).SoundFadeOut( m_sndLeeches, 0.5f, true ); m_sndLeeches = NULL; } if ( m_sndWaterSplashes ) { (CSoundEnvelopeController::GetController()).SoundFadeOut( m_sndWaterSplashes, 0.5f, true ); m_sndWaterSplashes = NULL; } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CHL2_Player::MissedAR2AltFire() { if( GetPlayerProxy() != NULL ) { GetPlayerProxy()->m_PlayerMissedAR2AltFire.FireOutput( this, this ); } } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CHL2_Player::DisplayLadderHudHint() { #if !defined( CLIENT_DLL ) if( gpGlobals->curtime > m_flTimeNextLadderHint ) { m_flTimeNextLadderHint = gpGlobals->curtime + 60.0f; CFmtStr hint; hint.sprintf( "#Valve_Hint_Ladder" ); UTIL_HudHintText( this, hint.Access() ); } #endif//CLIENT_DLL } //----------------------------------------------------------------------------- // Shuts down sounds //----------------------------------------------------------------------------- void CHL2_Player::StopLoopingSounds( void ) { if ( m_sndLeeches != NULL ) { (CSoundEnvelopeController::GetController()).SoundDestroy( m_sndLeeches ); m_sndLeeches = NULL; } if ( m_sndWaterSplashes != NULL ) { (CSoundEnvelopeController::GetController()).SoundDestroy( m_sndWaterSplashes ); m_sndWaterSplashes = NULL; } BaseClass::StopLoopingSounds(); } //----------------------------------------------------------------------------- void CHL2_Player::ModifyOrAppendPlayerCriteria( AI_CriteriaSet& set ) { BaseClass::ModifyOrAppendPlayerCriteria( set ); if ( GlobalEntity_GetIndex( "gordon_precriminal" ) == -1 ) { set.AppendCriteria( "gordon_precriminal", "0" ); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- const impactdamagetable_t &CHL2_Player::GetPhysicsImpactDamageTable() { if ( m_bUseCappedPhysicsDamageTable ) return gCappedPlayerImpactDamageTable; return BaseClass::GetPhysicsImpactDamageTable(); } //----------------------------------------------------------------------------- // Purpose: Makes a splash when the player transitions between water states //----------------------------------------------------------------------------- void CHL2_Player::Splash( void ) { CEffectData data; data.m_fFlags = 0; data.m_vOrigin = GetAbsOrigin(); data.m_vNormal = Vector(0,0,1); data.m_vAngles = QAngle( 0, 0, 0 ); if ( GetWaterType() & CONTENTS_SLIME ) { data.m_fFlags |= FX_WATER_IN_SLIME; } float flSpeed = GetAbsVelocity().Length(); if ( flSpeed < 300 ) { data.m_flScale = random->RandomFloat( 10, 12 ); DispatchEffect( "waterripple", data ); } else { data.m_flScale = random->RandomFloat( 6, 8 ); DispatchEffect( "watersplash", data ); } } CLogicPlayerProxy *CHL2_Player::GetPlayerProxy( void ) { CLogicPlayerProxy *pProxy = dynamic_cast< CLogicPlayerProxy* > ( m_hPlayerProxy.Get() ); if ( pProxy == NULL ) { pProxy = (CLogicPlayerProxy*)gEntList.FindEntityByClassname(NULL, "logic_playerproxy" ); if ( pProxy == NULL ) return NULL; pProxy->m_hPlayer = this; m_hPlayerProxy = pProxy; } return pProxy; } void CHL2_Player::FirePlayerProxyOutput( const char *pszOutputName, variant_t variant, CBaseEntity *pActivator, CBaseEntity *pCaller ) { if ( GetPlayerProxy() == NULL ) return; GetPlayerProxy()->FireNamedOutput( pszOutputName, variant, pActivator, pCaller ); } LINK_ENTITY_TO_CLASS( logic_playerproxy, CLogicPlayerProxy); BEGIN_DATADESC( CLogicPlayerProxy ) DEFINE_OUTPUT( m_OnFlashlightOn, "OnFlashlightOn" ), DEFINE_OUTPUT( m_OnFlashlightOff, "OnFlashlightOff" ), DEFINE_OUTPUT( m_RequestedPlayerHealth, "PlayerHealth" ), DEFINE_OUTPUT( m_PlayerHasAmmo, "PlayerHasAmmo" ), DEFINE_OUTPUT( m_PlayerHasNoAmmo, "PlayerHasNoAmmo" ), DEFINE_OUTPUT( m_PlayerDied, "PlayerDied" ), DEFINE_OUTPUT( m_PlayerMissedAR2AltFire, "PlayerMissedAR2AltFire" ), DEFINE_INPUTFUNC( FIELD_VOID, "RequestPlayerHealth", InputRequestPlayerHealth ), DEFINE_INPUTFUNC( FIELD_VOID, "SetFlashlightSlowDrain", InputSetFlashlightSlowDrain ), DEFINE_INPUTFUNC( FIELD_VOID, "SetFlashlightNormalDrain", InputSetFlashlightNormalDrain ), DEFINE_INPUTFUNC( FIELD_INTEGER, "SetPlayerHealth", InputSetPlayerHealth ), DEFINE_INPUTFUNC( FIELD_VOID, "RequestAmmoState", InputRequestAmmoState ), DEFINE_INPUTFUNC( FIELD_VOID, "LowerWeapon", InputLowerWeapon ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableCappedPhysicsDamage", InputEnableCappedPhysicsDamage ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableCappedPhysicsDamage", InputDisableCappedPhysicsDamage ), DEFINE_INPUTFUNC( FIELD_STRING, "SetLocatorTargetEntity", InputSetLocatorTargetEntity ), DEFINE_FIELD( m_hPlayer, FIELD_EHANDLE ), END_DATADESC() void CLogicPlayerProxy::Activate( void ) { BaseClass::Activate(); if ( m_hPlayer == NULL ) { m_hPlayer = AI_GetSinglePlayer(); } } bool CLogicPlayerProxy::PassesDamageFilter( const CTakeDamageInfo &info ) { if (m_hDamageFilter) { CBaseFilter *pFilter = (CBaseFilter *)(m_hDamageFilter.Get()); return pFilter->PassesDamageFilter(info); } return true; } void CLogicPlayerProxy::InputSetPlayerHealth( inputdata_t &inputdata ) { if ( m_hPlayer == NULL ) return; m_hPlayer->SetHealth( inputdata.value.Int() ); } void CLogicPlayerProxy::InputRequestPlayerHealth( inputdata_t &inputdata ) { if ( m_hPlayer == NULL ) return; m_RequestedPlayerHealth.Set( m_hPlayer->GetHealth(), inputdata.pActivator, inputdata.pCaller ); } void CLogicPlayerProxy::InputSetFlashlightSlowDrain( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); if( pPlayer ) pPlayer->SetFlashlightPowerDrainScale( hl2_darkness_flashlight_factor.GetFloat() ); } void CLogicPlayerProxy::InputSetFlashlightNormalDrain( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); if( pPlayer ) pPlayer->SetFlashlightPowerDrainScale( 1.0f ); } void CLogicPlayerProxy::InputRequestAmmoState( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); for ( int i = 0 ; i < pPlayer->WeaponCount(); ++i ) { CBaseCombatWeapon* pCheck = pPlayer->GetWeapon( i ); if ( pCheck ) { if ( pCheck->HasAnyAmmo() && (pCheck->UsesPrimaryAmmo() || pCheck->UsesSecondaryAmmo())) { m_PlayerHasAmmo.FireOutput( this, this, 0 ); return; } } } m_PlayerHasNoAmmo.FireOutput( this, this, 0 ); } void CLogicPlayerProxy::InputLowerWeapon( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); pPlayer->Weapon_Lower(); } void CLogicPlayerProxy::InputEnableCappedPhysicsDamage( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); pPlayer->EnableCappedPhysicsDamage(); } void CLogicPlayerProxy::InputDisableCappedPhysicsDamage( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); pPlayer->DisableCappedPhysicsDamage(); } void CLogicPlayerProxy::InputSetLocatorTargetEntity( inputdata_t &inputdata ) { if( m_hPlayer == NULL ) return; CBaseEntity *pTarget = NULL; // assume no target string_t iszTarget = MAKE_STRING( inputdata.value.String() ); if( iszTarget != NULL_STRING ) { pTarget = gEntList.FindEntityByName( NULL, iszTarget ); } CHL2_Player *pPlayer = dynamic_cast<CHL2_Player*>(m_hPlayer.Get()); pPlayer->SetLocatorTargetEntity(pTarget); }
[ "MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61" ]
MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61
5a4a49dacad3d582aaa587c417c14b4cc6a0330b
b88d8ff12b358236fb95b139f643e2e881695172
/ABC/ABC161/a2.cpp
8a479fed798e8434585b1a016765a038f1f58b8d
[]
no_license
Pikeruman-f18/C-_Practice
a7551a5fb55556da400305be4f3535ddce6a289b
57c0dfbaf17afe7bb481f5761c06a56a5d084e38
refs/heads/master
2020-12-19T19:56:26.736532
2020-04-12T13:08:53
2020-04-12T13:08:53
235,836,037
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
cpp
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int,int>; int main() { cin.tie(0); ios::sync_with_stdio(false); int n,m,a1; vector<int> a; cin>>n>>m; if(m<1 || n<1) { return 0; } if(m>100 || n>100) { return 0; } for(int i=0; i<n; i++) { cin>>a1; a.push_back(a1); } sort(a.begin(), a.end()); int goukei; for(int i=0; i<n; i++) { goukei += a.at(i); } double goukei4; goukei4 = goukei * ((double)(1 / (4*(double)m))); int cnt=0; for(int i=0; i<n; i++) { if(a.at(i) > goukei4) { cnt++; } } /*cout<<"goukei:"<<goukei<<endl; cout<<"goukei4:"<<goukei4<<endl; cout<<"CNT:"<<cnt<<endl; cout<<"N:"<<n<<endl; cout<<"M:"<<m<<endl; cout<<a.at(0)<<endl;*/ if(m==1 && a.at(n-1) >= goukei4) { cout<<"Yes"<<endl; return 0; } else if (cnt>=m) { cout<<"Yes"<<endl; return 0; } else { cout<<"No"<<endl; return 0; } return 0; }
[ "wataru.miyaji@gmail.com" ]
wataru.miyaji@gmail.com
62d0e73116f38e93e597a110a29904995a4f0370
037664902b196257640ab5fb30f9b4945f6230fa
/RTCCore/Network/network_request_plugin.cpp
8356da15ef366cf4cf6a9f0c477e16bd4247d470
[]
no_license
blockspacer/meeting_chat
e7e7c68ead1c7df7b8bd5698e8814e0bdaf65a68
2a406bcd5a02fa0003ffe4c9bc286dc5389c1adf
refs/heads/master
2022-12-25T22:26:32.873374
2020-10-12T09:14:42
2020-10-12T09:14:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,248
cpp
#include "network_request_plugin.h" #include <assert.h> #include "network_request_task.h" #include <QDebug> namespace core { NetworkRequestPlugin::NetworkRequestPlugin() { _pendingTasks.insert(std::make_pair(RequestPriority::LOW, std::deque<std::shared_ptr<NetworkRequestTask>>())); _pendingTasks.insert(std::make_pair(RequestPriority::NORMAL, std::deque<std::shared_ptr<NetworkRequestTask>>())); _pendingTasks.insert(std::make_pair(RequestPriority::HIGH, std::deque<std::shared_ptr<NetworkRequestTask>>())); _pendingTasks.insert(std::make_pair(RequestPriority::SEPECIFIC, std::deque<std::shared_ptr<NetworkRequestTask>>())); } NetworkRequestPlugin::~NetworkRequestPlugin() { } void NetworkRequestPlugin::addRequestConsumer(RequestRoute route, const std::shared_ptr<INetworkRequestConsumer>& consumer) { _consumers[route] = consumer; } void NetworkRequestPlugin::cancelAll() { cancelAllPendingTasks(); cancelAllConsumers(); } void NetworkRequestPlugin::cancelRequest(const std::shared_ptr<NetworkRequest>& request) { assert(request != nullptr); request->setCancelled(true); if (isRequestInPending(request)) { //callXApiResponseCallback(NetworkFailType::CANCELLED, request); } else { for (auto iter = _consumers.begin(); iter != _consumers.end(); ++iter) { (iter->second)->cancelRequest(request); } } } void NetworkRequestPlugin::appendTask(const std::shared_ptr<NetworkRequestTask>& task, bool isTail) { { std::lock_guard<std::mutex> guard(_lock); if (isTail) { _pendingTasks[task->priority()].push_back(task); } else { _pendingTasks[task->priority()].push_front(task); } } } void NetworkRequestPlugin::addRequest(const std::shared_ptr<NetworkRequest>& request, bool isTail) { assert(request != nullptr); auto task = std::make_shared<NetworkRequestTask>(request); appendTask(task, isTail); notifyRequestArrived(request->requestRoute()); } std::string NetworkRequestPlugin::pluginName() const { return _pluginName; } void NetworkRequestPlugin::onNetworkStatusChanged(bool online) { } const std::shared_ptr<NetworkRequest> NetworkRequestPlugin::produceRequest(RequestRoute route) { std::shared_ptr<NetworkRequestTask> result = nullptr; qDebug() << "---------------------------- produceRequest ----------------------------"; { std::lock_guard<std::mutex> guard(_lock); for (int32_t index = (int32_t)RequestPriority::SEPECIFIC; index >= (int32_t)RequestPriority::LOW; --index) { if (!canProduceRequest(static_cast<RequestPriority>(index))) { break; } result = nextTaskInQueue(route, _pendingTasks[(RequestPriority)index]); if (result) { break; } } if (result != nullptr) { assert(result->request() != nullptr); //changeTaskWeight(m_pendingTasks[ApiRequestPriority::NORMAL], m_pendingTasks[ApiRequestPriority::HIGH], kApiRequestHighWeight); //changeTaskWeight(m_pendingTasks[ApiRequestPriority::LOW], m_pendingTasks[ApiRequestPriority::NORMAL], kApiRequestNormalWeight); } } return result == nullptr ? nullptr : result->request(); } // private bool NetworkRequestPlugin::canProduceRequest(RequestPriority /*priority*/) { return true; } bool NetworkRequestPlugin::isConsumerAvailable(RequestRoute route) { bool isAvailable = true; auto iter = _consumers.find(route); if (iter != _consumers.end()) { isAvailable = (iter->second)->isAvailiable(); } return isAvailable; } bool NetworkRequestPlugin::canBeHandled(RequestRoute route, const std::shared_ptr<NetworkRequestTask>& task) { return (task->requestRoute() == route) || ((static_cast<int>(task->requestRoute() == route) != 0) && isConsumerAvailable(route)); } std::shared_ptr<NetworkRequestTask> NetworkRequestPlugin::nextTaskInQueue(RequestRoute route, std::deque<std::shared_ptr<NetworkRequestTask>>& queue) { auto iter = queue.begin(); while (iter != queue.end()) { if (canBeHandled(route, (*iter))) { auto task = *iter; queue.erase(iter); return task; } else { ++iter; } } return nullptr; } void NetworkRequestPlugin::notifyRequestArrived(RequestRoute route) { for (int32_t i = (int)RequestRoute::REQUEST_ROUTE_MAX; i >= (int)RequestRoute::HTTP; i >>= 1) { auto iter = _consumers.find(RequestRoute(i)); if (iter != _consumers.end()) { if ((iter->second)->canHandleRequest(route)) { (iter->second)->onNetworkRequestArrived(); } } } } void NetworkRequestPlugin::cancelAllConsumers() { for (auto iter = _consumers.begin(); iter != _consumers.end(); ++iter) { (iter->second)->cancelAll(); } } void NetworkRequestPlugin::cancelAllPendingTasks() { { std::lock_guard<std::mutex> guard(_lock); for (auto iter = _pendingTasks.begin(); iter != _pendingTasks.end(); ++iter) { auto queue = iter->second; for (auto queueIter = queue.begin(); queueIter != queue.end(); ++queueIter) { auto task = *queueIter; //callXApiResponseCallback(NetworkFailType::CANCELLED, task->request()); } } _pendingTasks.clear(); } } bool NetworkRequestPlugin::isRequestInPending(const std::shared_ptr<NetworkRequest>& request) { bool exist = false; { std::lock_guard<std::mutex> guard(_lock); for (auto iter = _pendingTasks.begin(); iter != _pendingTasks.end(); ++iter) { auto queue = iter->second; for (auto queueIter = queue.begin(); queueIter != queue.end(); ++queueIter) { auto task = *queueIter; if (task->request()->requestId() == request->requestId()) { exist = true; break; } } if (exist) { break; } } } return exist; } }
[ "jackie.ou@ringcentral.com" ]
jackie.ou@ringcentral.com
94ca1011351879bb80485533d205d154f6805b81
a2e319ef4342d753111d12c31ad209fbce0dbf6a
/cpp/lecture_08/04.cpp
e0cff71c67c5e56ff569cad664c7c64852a59e45
[]
no_license
SylwiaBoniecka/nauka
a322798370e0ae0e454729d6fddc1707f871b411
08a5af95d8c31e952802b50c3be84069fc7b58cc
refs/heads/main
2023-06-21T20:20:32.192456
2021-07-22T13:03:21
2021-07-22T13:03:21
329,991,934
1
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
#include <iostream> using namespace std; int main() { int a = 7; int *p = &a; cout << "a = " << a << "\t address: " << &a << endl; cout << "p = " << *p << "\t address: " << p << endl; return 0; }
[ "sylwia.boniecka@gmail.com" ]
sylwia.boniecka@gmail.com