hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
7ac967366949dbe3f638032dfce127f62cf8ad06
4,138
cpp
C++
src/condor_gridmanager/boinc-client.cpp
sridish123/htcondor
481d975fd8602242f6a052aab04e20b0b560db89
[ "Apache-2.0" ]
217
2015-01-08T04:49:42.000Z
2022-03-27T10:11:58.000Z
src/condor_gridmanager/boinc-client.cpp
sridish123/htcondor
481d975fd8602242f6a052aab04e20b0b560db89
[ "Apache-2.0" ]
185
2015-05-03T13:26:31.000Z
2022-03-28T03:08:59.000Z
src/condor_gridmanager/boinc-client.cpp
sridish123/htcondor
481d975fd8602242f6a052aab04e20b0b560db89
[ "Apache-2.0" ]
133
2015-02-11T09:17:45.000Z
2022-03-31T07:28:54.000Z
#include "condor_common.h" #include "condor_debug.h" #include "condor_config.h" #include "gahp_common.h" #include "boincjob.h" #include "gahp-client.h" using std::set; using std::vector; using std::pair; using std::string; int GahpClient::boinc_submit( const char *batch_name, const std::set<BoincJob *> &jobs ) { static const char* command = "BOINC_SUBMIT"; // Check if this command is supported if (server->m_commands_supported->contains_anycase(command)==FALSE) { return GAHPCLIENT_COMMAND_NOT_SUPPORTED; } ASSERT( !jobs.empty() ); int job_cnt = jobs.size(); // Generate request line if (!batch_name) batch_name=NULLSTRING; std::string reqline; reqline = escapeGahpString( batch_name ); formatstr_cat( reqline, " %s %d", escapeGahpString( (*jobs.begin())->GetAppName() ), job_cnt ); for ( set<BoincJob*>::const_iterator itr = jobs.begin(); itr != jobs.end(); itr++ ) { ArgList *args_list = (*itr)->GetArgs(); char **args = args_list->GetStringArray(); int arg_cnt = args_list->Count(); formatstr_cat( reqline, " %s %d", (*itr)->remoteJobName, arg_cnt ); for ( int i = 0; i < arg_cnt; i++ ) { reqline += " "; reqline += escapeGahpString( args[i] ); } deleteStringArray( args ); delete args_list; vector<pair<string, string> > inputs; (*itr)->GetInputFilenames( inputs ); formatstr_cat( reqline, " %d", (int)inputs.size() ); for ( vector<pair<string, string> >::iterator jtr = inputs.begin(); jtr != inputs.end(); jtr++ ) { reqline += " "; reqline += escapeGahpString( jtr->first ); reqline += " "; reqline += escapeGahpString( jtr->second ); } } if ( (*jobs.begin())->GetVar("rsc_fpops_est") != "") { reqline += " "; reqline += escapeGahpString( (*jobs.begin())->GetVar("rsc_fpops_est") ); } else reqline += " NULL"; if ( (*jobs.begin())->GetVar("rsc_fpops_bound") != "") { reqline += " "; reqline += escapeGahpString( (*jobs.begin())->GetVar("rsc_fpops_bound") ); } else reqline += " NULL"; if ( (*jobs.begin())->GetVar("rsc_memory_bound") != "") { reqline += " "; reqline += escapeGahpString( (*jobs.begin())->GetVar("rsc_memory_bound") ); } else reqline += " NULL"; if ( (*jobs.begin())->GetVar("rsc_disk_bound") != "") { reqline += " "; reqline += escapeGahpString( (*jobs.begin())->GetVar("rsc_disk_bound") ); } else reqline += " NULL"; if ( (*jobs.begin())->GetVar("delay_bound") != "") { reqline += " "; reqline += escapeGahpString( (*jobs.begin())->GetVar("delay_bound") ); } else reqline += " NULL"; if ( (*jobs.begin())->GetVar("app_version_num") != "") { reqline += " "; reqline += escapeGahpString( (*jobs.begin())->GetVar("app_version_num") ); } else reqline += " NULL"; const char *buf = reqline.c_str(); // Check if this request is currently pending. If not, make // it the pending request. if ( !is_pending( command, buf ) ) { // Command is not pending, so go ahead and submit a new one // if our command mode permits. if ( m_mode == results_only ) { return GAHPCLIENT_COMMAND_NOT_SUBMITTED; } now_pending( command, buf ); } // If we made it here, command is pending. // Check first if command completed. Gahp_Args* result = get_pending_result(command,buf); if ( result ) { // command completed. if ( result->argc != 2 ) { EXCEPT( "Bad %s Result", command ); } int rc; if ( strcmp( result->argv[1], NULLSTRING ) == 0 ) { rc = 0; } else { rc = 1; error_string = result->argv[1]; } delete result; return rc; } // Now check if pending command timed out. if ( check_pending_timeout( command, buf ) ) { // pending command timed out. formatstr( error_string, "%s timed out", command ); return GAHPCLIENT_COMMAND_TIMED_OUT; } // If we made it here, command is still pending... return GAHPCLIENT_COMMAND_PENDING; }
29.557143
87
0.589899
sridish123
7acd61a3f6537f24b796f183aa72bb1775340c01
4,101
cpp
C++
src/camera_model_filter/CameraModelFilter.cpp
Tobi2001/asr_next_best_view
7dace46b903d15e218a39f994802288103818f48
[ "BSD-3-Clause" ]
9
2019-12-10T07:39:07.000Z
2022-03-25T11:40:02.000Z
src/camera_model_filter/CameraModelFilter.cpp
Tobi2001/asr_next_best_view
7dace46b903d15e218a39f994802288103818f48
[ "BSD-3-Clause" ]
null
null
null
src/camera_model_filter/CameraModelFilter.cpp
Tobi2001/asr_next_best_view
7dace46b903d15e218a39f994802288103818f48
[ "BSD-3-Clause" ]
2
2020-01-13T17:41:33.000Z
2022-03-25T11:40:04.000Z
/** Copyright (c) 2016, Aumann Florian, Borella Jocelyn, Heller Florian, Meißner Pascal, Schleicher Ralf, Stöckle Patrick, Stroh Daniel, Trautmann Jeremias, Walter Milena, Wittenbeck Valerij All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 4. The use is explicitly not permitted to any application which deliberately try to kill or do harm to any living creature. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "next_best_view/camera_model_filter/CameraModelFilter.hpp" namespace next_best_view { CameraModelFilter::CameraModelFilter() : GeneralFilter(), mParametersChanged(true), mFOVX(0.0), mFOVY(0.0), mNcp(0.0), mFcp(0.0) { } CameraModelFilter::~CameraModelFilter() { } void CameraModelFilter::setRecognizerCosts(float recognizerCosts, std::string objectType) { this->recognizerCosts = recognizerCosts; } float CameraModelFilter::getRecognizerCosts(std::string objectType) { return recognizerCosts; } void CameraModelFilter::setPivotPointPose(const SimpleVector3 &position, const SimpleQuaternion &orientation) { this->setPivotPointPosition(position); this->setOrientation(orientation); } void CameraModelFilter::setPivotPointPosition(const SimpleVector3 &position) { mPivotPointPosition = position; this->setParametersChanged(true); } SimpleVector3 CameraModelFilter::getPivotPointPosition() { return mPivotPointPosition; } void CameraModelFilter::setOrientation(const SimpleQuaternion &orientation) { mPivotPointOrientation = orientation; this->setParametersChanged(true); } SimpleQuaternion CameraModelFilter::getOrientation() { return mPivotPointOrientation; } SimpleMatrix4 CameraModelFilter::getCameraPoseMatrix(const SimpleVector3 &position, const SimpleQuaternion &orientation) { SimpleMatrix4 cameraPoseMatrix = SimpleMatrix4::Identity(); cameraPoseMatrix.block<3, 3>(0, 0) = orientation.toRotationMatrix(); cameraPoseMatrix.block<3, 1>(0, 3) = position; return cameraPoseMatrix; } void CameraModelFilter::setHorizontalFOV(double fovDegrees) { mFOVX = fovDegrees; this->setParametersChanged(true); } double CameraModelFilter::getHorizontalFOV() { return mFOVX; } void CameraModelFilter::setVerticalFOV(double fovDegrees) { mFOVY = fovDegrees; this->setParametersChanged(true); } double CameraModelFilter::getVerticalFOV() { return mFOVY; } void CameraModelFilter::setNearClippingPlane(double ncp) { mNcp = ncp; this->setParametersChanged(true); } double CameraModelFilter::getNearClippingPlane() { return mNcp; } void CameraModelFilter::setFarClippingPlane(double fcp) { mFcp = fcp; this->setParametersChanged(true); } double CameraModelFilter::getFarClippingPlane() { return mFcp; } }
39.057143
755
0.787369
Tobi2001
7acd9e946c6ca74c7a80aca9542ff51c5e30f033
2,706
cpp
C++
examples/SplineDev.cpp
bmharper/xo
575429591c166cc70db60385d2a6563d0f9bc9ed
[ "Unlicense" ]
7
2015-12-18T04:17:29.000Z
2020-03-13T15:38:54.000Z
examples/SplineDev.cpp
benharper123/xo
575429591c166cc70db60385d2a6563d0f9bc9ed
[ "Unlicense" ]
null
null
null
examples/SplineDev.cpp
benharper123/xo
575429591c166cc70db60385d2a6563d0f9bc9ed
[ "Unlicense" ]
4
2016-09-18T13:16:02.000Z
2022-03-23T11:33:53.000Z
#include "../xo/xo.h" #include <omp.h> // This was used when developing the spline rendering code void Render(xo::Canvas2D* canvas, int cx, int cy, float scale); void xoMain(xo::SysWnd* wnd) { int left = 550; int width = 1000; int top = 60; int height = 1000; wnd->SetPosition(xo::Box(left, top, left + width, top + height), xo::SysWnd::SetPosition_Move | xo::SysWnd::SetPosition_Size); //auto magic = xo::Color::RGBA(0xff, 0xf0, 0xf0, 0xff); xo::DomCanvas* canvas = wnd->Doc()->Root.AddCanvas(); canvas->StyleParsef("width: %dep; height: %dep;", width, height); canvas->SetImageSizeOnly(width, height); canvas->OnMouseMove([width, height](xo::Event& ev) { xo::DomCanvas* canvas = (xo::DomCanvas*) ev.Target; xo::Canvas2D* cx = canvas->GetCanvas2D(); //Render(cx, (int) ev.Points[0].x, (int) ev.Points[0].y); Render(cx, width / 2, height / 2, FLT_EPSILON + ev.PointsRel[0].x * 0.0001f); canvas->ReleaseCanvas(cx); }); } float Eval(float x, float y) { //return 0.0005f * (x - sqrt(y)); return 0.0005f * (y - x*x); //return 0.0005f * (x * x + y * 10.0f); } float Eval2(float x, float y) { float eps = 0.1f; float g = Eval(x, y); float dx = (Eval(x + eps, y) - Eval(x - eps, y)) / eps; float dy = (Eval(x, y + eps) - Eval(x, y - eps)) / eps; return g / sqrt(dx * dx + dy * dy); //return sqrt(dx * dx + dy * dy); } void Render(xo::Canvas2D* canvas, int cx, int cy, float scale) { //canvas->Fill(xoColor::White()); //xoBox box(0, 0, 7, 7); //box.Offset(cx - box.Width() / 2.0f, cy - box.Height() / 2.0f); //canvas->FillRect(box, xoColor::RGBA(200, 50, 50, 255)); double start = xo::TimeAccurateSeconds(); uint8_t lut[256]; for (int i = 0; i < 256; i++) { lut[i] = i; //lut[i] = 2 * abs(127 - i); //lut[i] = xoLinear2SRGB(i / 255.0f); } const float iscale = 255.0f / scale; int height = canvas->Height(); int width = canvas->Width(); // This omp directive gives close to an 8x speedup on VS 2015, quad core skylake. #pragma omp parallel for for (int y = 0; y < height; y++) { float yf = scale * (float) (cy - y); // we invert Y, so that up is positive xo::RGBA* line = (xo::RGBA*) canvas->RowPtr(y); for (int x = 0; x < width; x++) { float xf = scale * (float) (x - cx); float v = iscale * Eval2(xf, yf); // This is useful for illustration - having a gradient either side of the zero line //float v = 127.0f + iscale * Eval(xf, yf)); int ilut = xo::Clamp((int) v, 0, 255); uint8_t lum = lut[ilut]; line[x] = xo::RGBA::Make(lum, lum, lum, 255); } } canvas->Invalidate(xo::Box(0, 0, canvas->Width(), canvas->Height())); xo::Trace("canvas render: %.3f ms\n", 1000.0f * (xo::TimeAccurateSeconds() - start)); }
29.736264
127
0.608647
bmharper
7ad071cb5777505968fc4620b5d2ebad0926b154
464
cpp
C++
08. classes-and-objects/homework/02. distance.cpp
ihristova11/cpp-fundamentals
a72a0fb9e302921760a81f0a3436039b34b0981f
[ "MIT" ]
null
null
null
08. classes-and-objects/homework/02. distance.cpp
ihristova11/cpp-fundamentals
a72a0fb9e302921760a81f0a3436039b34b0981f
[ "MIT" ]
null
null
null
08. classes-and-objects/homework/02. distance.cpp
ihristova11/cpp-fundamentals
a72a0fb9e302921760a81f0a3436039b34b0981f
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <iomanip> using namespace std; struct Point { Point(double xp, double yp) { x = xp; y = yp; } public: double x; double y; double distanceToPoint(Point a) { return sqrt(pow(abs(a.x - this->x), 2.0) + (pow(abs(a.y - this->y), 2.0))); } }; int main() { int x, y; cin >> x >> y; Point a(x, y); cin >> x >> y; Point b(x, y); cout << fixed << setprecision(3) << b.distanceToPoint(a); return 0; }
12.540541
77
0.575431
ihristova11
7ad0bcc40231933ba0dafb97efda25266b4355df
6,377
cpp
C++
c++/floor_fHf/solver_floor_fHf.cpp
marcusvaltonen/minimal_indoor_uav
79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca
[ "MIT" ]
null
null
null
c++/floor_fHf/solver_floor_fHf.cpp
marcusvaltonen/minimal_indoor_uav
79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca
[ "MIT" ]
null
null
null
c++/floor_fHf/solver_floor_fHf.cpp
marcusvaltonen/minimal_indoor_uav
79f3a26f2a6c10ee74a9fb70c5f3b42e4cf105ca
[ "MIT" ]
1
2020-09-15T17:05:32.000Z
2020-09-15T17:05:32.000Z
#include <Eigen/Dense> using namespace Eigen; MatrixXcd solver_floor_fHf(const VectorXd& data) { // Compute coefficients const double* d = data.data(); VectorXd coeffs(45); coeffs[0] = 1; coeffs[1] = -1; coeffs[2] = d[20]*d[28]; coeffs[3] = -d[18]*d[28]; coeffs[4] = -d[19]*d[29]; coeffs[5] = d[19]*d[28]; coeffs[6] = d[2]*d[20]*d[22] + d[3]*d[20]*d[25] + d[0]*d[14]*d[28] + d[1]*d[17]*d[28]; coeffs[7] = -d[2]*d[18]*d[22] - d[3]*d[18]*d[25] - d[0]*d[12]*d[28] - d[1]*d[15]*d[28]; coeffs[8] = -d[2]*d[19]*d[23] - d[3]*d[19]*d[26] - d[0]*d[13]*d[29] - d[1]*d[16]*d[29]; coeffs[9] = d[2]*d[19]*d[22] + d[3]*d[19]*d[25] + d[0]*d[13]*d[28] + d[1]*d[16]*d[28]; coeffs[10] = d[0]*d[2]*d[14]*d[22] + d[1]*d[2]*d[17]*d[22] + d[0]*d[3]*d[14]*d[25] + d[1]*d[3]*d[17]*d[25]; coeffs[11] = -d[0]*d[2]*d[12]*d[22] - d[1]*d[2]*d[15]*d[22] - d[0]*d[3]*d[12]*d[25] - d[1]*d[3]*d[15]*d[25]; coeffs[12] = -d[0]*d[2]*d[13]*d[23] - d[1]*d[2]*d[16]*d[23] - d[0]*d[3]*d[13]*d[26] - d[1]*d[3]*d[16]*d[26]; coeffs[13] = d[0]*d[2]*d[13]*d[22] + d[1]*d[2]*d[16]*d[22] + d[0]*d[3]*d[13]*d[25] + d[1]*d[3]*d[16]*d[25]; coeffs[14] = -d[20]*d[28]; coeffs[15] = -d[19]*d[28]; coeffs[16] = d[19]*d[27]; coeffs[17] = -d[2]*d[20]*d[22] - d[3]*d[20]*d[25] - d[0]*d[14]*d[28] - d[1]*d[17]*d[28]; coeffs[18] = -d[2]*d[19]*d[22] - d[3]*d[19]*d[25] - d[0]*d[13]*d[28] - d[1]*d[16]*d[28]; coeffs[19] = d[2]*d[19]*d[21] + d[3]*d[19]*d[24] + d[0]*d[13]*d[27] + d[1]*d[16]*d[27]; coeffs[20] = -d[0]*d[2]*d[14]*d[22] - d[1]*d[2]*d[17]*d[22] - d[0]*d[3]*d[14]*d[25] - d[1]*d[3]*d[17]*d[25]; coeffs[21] = -d[0]*d[2]*d[13]*d[22] - d[1]*d[2]*d[16]*d[22] - d[0]*d[3]*d[13]*d[25] - d[1]*d[3]*d[16]*d[25]; coeffs[22] = d[0]*d[2]*d[13]*d[21] + d[1]*d[2]*d[16]*d[21] + d[0]*d[3]*d[13]*d[24] + d[1]*d[3]*d[16]*d[24]; coeffs[23] = d[6]*d[20]*d[22] + d[7]*d[20]*d[25] + d[4]*d[14]*d[28] + d[5]*d[17]*d[28]; coeffs[24] = -d[6]*d[18]*d[22] - d[7]*d[18]*d[25] - d[4]*d[12]*d[28] - d[5]*d[15]*d[28]; coeffs[25] = -d[6]*d[19]*d[23] - d[7]*d[19]*d[26] - d[4]*d[13]*d[29] - d[5]*d[16]*d[29]; coeffs[26] = d[6]*d[19]*d[22] + d[7]*d[19]*d[25] + d[4]*d[13]*d[28] + d[5]*d[16]*d[28]; coeffs[27] = d[4]*d[6]*d[14]*d[22] + d[5]*d[6]*d[17]*d[22] + d[4]*d[7]*d[14]*d[25] + d[5]*d[7]*d[17]*d[25]; coeffs[28] = -d[4]*d[6]*d[12]*d[22] - d[5]*d[6]*d[15]*d[22] - d[4]*d[7]*d[12]*d[25] - d[5]*d[7]*d[15]*d[25]; coeffs[29] = -d[4]*d[6]*d[13]*d[23] - d[5]*d[6]*d[16]*d[23] - d[4]*d[7]*d[13]*d[26] - d[5]*d[7]*d[16]*d[26]; coeffs[30] = d[4]*d[6]*d[13]*d[22] + d[5]*d[6]*d[16]*d[22] + d[4]*d[7]*d[13]*d[25] + d[5]*d[7]*d[16]*d[25]; coeffs[31] = -d[6]*d[20]*d[22] - d[7]*d[20]*d[25] - d[4]*d[14]*d[28] - d[5]*d[17]*d[28]; coeffs[32] = -d[6]*d[19]*d[22] - d[7]*d[19]*d[25] - d[4]*d[13]*d[28] - d[5]*d[16]*d[28]; coeffs[33] = d[6]*d[19]*d[21] + d[7]*d[19]*d[24] + d[4]*d[13]*d[27] + d[5]*d[16]*d[27]; coeffs[34] = -d[4]*d[6]*d[14]*d[22] - d[5]*d[6]*d[17]*d[22] - d[4]*d[7]*d[14]*d[25] - d[5]*d[7]*d[17]*d[25]; coeffs[35] = -d[4]*d[6]*d[13]*d[22] - d[5]*d[6]*d[16]*d[22] - d[4]*d[7]*d[13]*d[25] - d[5]*d[7]*d[16]*d[25]; coeffs[36] = d[4]*d[6]*d[13]*d[21] + d[5]*d[6]*d[16]*d[21] + d[4]*d[7]*d[13]*d[24] + d[5]*d[7]*d[16]*d[24]; coeffs[37] = d[10]*d[20]*d[22] + d[11]*d[20]*d[25] + d[8]*d[14]*d[28] + d[9]*d[17]*d[28]; coeffs[38] = -d[10]*d[18]*d[22] - d[11]*d[18]*d[25] - d[8]*d[12]*d[28] - d[9]*d[15]*d[28]; coeffs[39] = -d[10]*d[19]*d[23] - d[11]*d[19]*d[26] - d[8]*d[13]*d[29] - d[9]*d[16]*d[29]; coeffs[40] = d[10]*d[19]*d[22] + d[11]*d[19]*d[25] + d[8]*d[13]*d[28] + d[9]*d[16]*d[28]; coeffs[41] = d[8]*d[10]*d[14]*d[22] + d[9]*d[10]*d[17]*d[22] + d[8]*d[11]*d[14]*d[25] + d[9]*d[11]*d[17]*d[25]; coeffs[42] = -d[8]*d[10]*d[12]*d[22] - d[9]*d[10]*d[15]*d[22] - d[8]*d[11]*d[12]*d[25] - d[9]*d[11]*d[15]*d[25]; coeffs[43] = -d[8]*d[10]*d[13]*d[23] - d[9]*d[10]*d[16]*d[23] - d[8]*d[11]*d[13]*d[26] - d[9]*d[11]*d[16]*d[26]; coeffs[44] = d[8]*d[10]*d[13]*d[22] + d[9]*d[10]*d[16]*d[22] + d[8]*d[11]*d[13]*d[25] + d[9]*d[11]*d[16]*d[25]; // Setup elimination template static const int coeffs0_ind[] = { 2,3,2,3,2,3,14,3,14,3,6,7,3,2,23,24,37,2,2,3,7,17,14,3,24,31,38,3,3,14,18,15,32,15,8,19,16,4,25,33,39,4,4,16,9,5,26,40,5,5,10,11,7,6,27,28,41,23,37,24,11,20,17,7,28,34,42,24,38,31,21,18,35,32 }; static const int coeffs1_ind[] = { 11,10,27,41,28,20,11,28,42,34,21,35,22,12,29,43,36,12,22,19,8,29,36,43,25,39,33,13,30,44,13,9,30,44,26,40 }; static const int C0_ind[] = { 0,1,4,5,6,10,11,14,15,16,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,41,42,45,49,50,51,52,53,54,55,56,57,58,59,60,63,64,66,67,68,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,91,92,95,99 } ; static const int C1_ind[] = { 2,3,7,8,9,12,13,17,18,19,22,29,32,33,37,38,39,40,41,42,43,44,45,46,47,48,49,53,57,58,60,63,64,66,67,68 }; Matrix<double,10,10> C0; C0.setZero(); Matrix<double,10,7> C1; C1.setZero(); for (int i = 0; i < 74; i++) { C0(C0_ind[i]) = coeffs(coeffs0_ind[i]); } for (int i = 0; i < 36; i++) { C1(C1_ind[i]) = coeffs(coeffs1_ind[i]); } Matrix<double,10,7> C12 = C0.partialPivLu().solve(C1); // Setup action matrix Matrix<double,12, 7> RR; RR << -C12.bottomRows(5), Matrix<double,7,7>::Identity(7, 7); static const int AM_ind[] = { 2,3,4,9,0,11,1 }; Matrix<double, 7, 7> AM; for (int i = 0; i < 7; i++) { AM.row(i) = RR.row(AM_ind[i]); } Matrix<std::complex<double>, 6, 7> sols; sols.setZero(); // Solve eigenvalue problem EigenSolver<Matrix<double, 7, 7> > es(AM); ArrayXcd D = es.eigenvalues(); ArrayXXcd V = es.eigenvectors(); // Normalize eigenvectors ArrayXcd normalization = (V.row(0).array().square() + V.row(1).array().square()).sqrt(); for (int i = 0; i < 7; i++) { V.col(i) /= normalization(i); } sols.row(0) = V.row(0).array(); sols.row(1) = V.row(1).array(); sols.row(2) = V.row(2).array(); sols.row(3) = V.row(3).array(); sols.row(4) = V.row(5).array(); sols.row(5) = D.transpose().array(); return sols; } // Action = x6 // Quotient ring basis (V) = x1,x2,x3,x4,x4*x6,x5,x5*x6, // Available monomials (RR*V) = x4*x6^2,x5*x6^2,x1*x6,x2*x6,x3*x6,x1,x2,x3,x4,x4*x6,x5,x5*x6,
58.504587
254
0.493649
marcusvaltonen
7ad1ad887976ef560596186d1dea1867a528d111
2,421
cpp
C++
lib/stages/removeEv.cpp
james-s-willis/kotekan
155e874bb039702cec72c1785362a017548aa00a
[ "MIT" ]
null
null
null
lib/stages/removeEv.cpp
james-s-willis/kotekan
155e874bb039702cec72c1785362a017548aa00a
[ "MIT" ]
null
null
null
lib/stages/removeEv.cpp
james-s-willis/kotekan
155e874bb039702cec72c1785362a017548aa00a
[ "MIT" ]
null
null
null
#include "removeEv.hpp" #include "datasetManager.hpp" #include "errors.h" #include "visBuffer.hpp" #include "visUtil.hpp" using kotekan::bufferContainer; using kotekan::Config; using kotekan::Stage; REGISTER_KOTEKAN_STAGE(removeEv); removeEv::removeEv(Config& config, const string& unique_name, bufferContainer& buffer_container) : Stage(config, unique_name, buffer_container, std::bind(&removeEv::main_thread, this)) { in_buf = get_buffer("in_buf"); register_consumer(in_buf, unique_name.c_str()); out_buf = get_buffer("out_buf"); register_producer(out_buf, unique_name.c_str()); // Create the state describing the eigenvalues auto& dm = datasetManager::instance(); ev_state_id = dm.create_state<eigenvalueState>(0).first; } void removeEv::change_dataset_state(dset_id_t input_dset_id) { auto& dm = datasetManager::instance(); dset_id_map[input_dset_id] = dm.add_dataset(ev_state_id, input_dset_id); } void removeEv::main_thread() { frameID in_frame_id(in_buf); frameID out_frame_id(out_buf); while (!stop_thread) { // Get input visibilities. We assume the shape of these doesn't change. if (wait_for_full_frame(in_buf, unique_name.c_str(), in_frame_id) == nullptr) { break; } auto input_frame = visFrameView(in_buf, in_frame_id); // Get output buffer for visibilities. Essentially identical to input buffers. if (wait_for_empty_frame(out_buf, unique_name.c_str(), out_frame_id) == nullptr) { break; } allocate_new_metadata_object(out_buf, out_frame_id); auto output_frame = visFrameView(out_buf, out_frame_id, input_frame.num_elements, input_frame.num_prod, 0); // check if the input dataset has changed if (dset_id_map.count(input_frame.dataset_id) == 0) { change_dataset_state(input_frame.dataset_id); } // Copy over metadata and data, but skip all ev members which may not be // defined output_frame.copy_metadata(input_frame); output_frame.copy_data(input_frame, {visField::eval, visField::evec, visField::erms}); output_frame.dataset_id = dset_id_map.at(input_frame.dataset_id); // Finish up iteration. mark_frame_empty(in_buf, unique_name.c_str(), in_frame_id++); mark_frame_full(out_buf, unique_name.c_str(), out_frame_id++); } }
33.625
99
0.697233
james-s-willis
7ad487f6292732c62c147417a586cf00245677d9
59
cpp
C++
test_lib/test_lib.cpp
antonte/coddle
906c0262c1f7ce251d40879f2377e77c2ff1db9f
[ "MIT" ]
null
null
null
test_lib/test_lib.cpp
antonte/coddle
906c0262c1f7ce251d40879f2377e77c2ff1db9f
[ "MIT" ]
2
2015-04-09T23:55:06.000Z
2017-04-15T01:37:36.000Z
test_lib/test_lib.cpp
antonte/coddle
906c0262c1f7ce251d40879f2377e77c2ff1db9f
[ "MIT" ]
null
null
null
#include "test_lib.hpp" int test_lib() { return 1000; }
8.428571
23
0.661017
antonte
7ad7066d9fe6444678b3f5cd01d67b925e152743
51,314
cc
C++
src/half_edge_mesh.cc
paulmiller/glFun
39df2c7f92b41c09d618b81e2016f1c530fb2108
[ "Unlicense" ]
null
null
null
src/half_edge_mesh.cc
paulmiller/glFun
39df2c7f92b41c09d618b81e2016f1c530fb2108
[ "Unlicense" ]
null
null
null
src/half_edge_mesh.cc
paulmiller/glFun
39df2c7f92b41c09d618b81e2016f1c530fb2108
[ "Unlicense" ]
null
null
null
#include "half_edge_mesh.h" #include "scoped_timer.h" #include <algorithm> #include <cassert> #include <cmath> #include <limits> #include <memory> #include <stack> #include <unordered_map> HalfEdgeMesh::VertexIndex HalfEdgeMesh::AddVertex() { auto [index, realloc_offset] = vertices_.Append({}); if(realloc_offset) { for(HalfEdge &edge: half_edges_) { if(edge.vertex) edge.vertex = (Vertex*)(uintptr_t(edge.vertex) + realloc_offset); } } return index; } HalfEdgeMesh::VertexPositionIndex HalfEdgeMesh::AddVertexPosition(const Vector3d &position) { auto [index, realloc_offset] = vertex_positions_.Append(position); if(realloc_offset) { for(Vertex &vertex: vertices_) { if(vertex.position) vertex.position = (Vector3d*)(uintptr_t(vertex.position) + realloc_offset); } } return index; } HalfEdgeMesh::VertexNormalIndex HalfEdgeMesh::AddVertexNormal(const Vector3d &normal) { auto [index, realloc_offset] = vertex_normals_.Append(normal); if(realloc_offset) { for(HalfEdge &edge: half_edges_) { if(edge.normal) edge.normal = (Vector3d*)(uintptr_t(edge.normal) + realloc_offset); } } return index; } HalfEdgeMesh::HalfEdgeIndex HalfEdgeMesh::AddHalfEdge() { auto [index, realloc_offset] = half_edges_.Append({}); if(realloc_offset) { for(Vertex &vertex: vertices_) { if(vertex.edge) vertex.edge = (HalfEdge*)(uintptr_t(vertex.edge) + realloc_offset); } for(HalfEdge &other_edge: half_edges_) { if(other_edge.twin_edge) other_edge.twin_edge = (HalfEdge*)(uintptr_t(other_edge.twin_edge) + realloc_offset); if(other_edge.next_edge) other_edge.next_edge = (HalfEdge*)(uintptr_t(other_edge.next_edge) + realloc_offset); } for(Face &face: faces_) { if(face.edge) face.edge = (HalfEdge*)(uintptr_t(face.edge) + realloc_offset); } } return index; } HalfEdgeMesh::FaceIndex HalfEdgeMesh::AddFace() { auto [index, realloc_offset] = faces_.Append({}); if(realloc_offset) { for(HalfEdge &edge: half_edges_) { if(edge.face) edge.face = (Face*)(uintptr_t(edge.face) + realloc_offset); } } return index; } HalfEdgeMesh::ObjectIndex HalfEdgeMesh::AddObject(std::string name) { auto [index, realloc_offset] = objects_.Append({std::move(name)}); if(realloc_offset) { for(Face &face: faces_) { if(face.object) face.object = (Object*)(uintptr_t(face.object) + realloc_offset); } } return index; } #ifndef NDEBUG void HalfEdgeMesh::CheckPtrs() const { for(const Vertex &vertex: vertices_) { vertex_positions_.CheckPtr(vertex.position); half_edges_.CheckPtr(vertex.edge); } for(const HalfEdge &edge: half_edges_) { vertices_.CheckPtr(edge.vertex); vertex_normals_.CheckPtr(edge.normal); half_edges_.CheckPtr(edge.twin_edge); half_edges_.CheckPtr(edge.next_edge); faces_.CheckPtr(edge.face); } for(const Face &face: faces_) { half_edges_.CheckPtr(face.edge); objects_.CheckPtr(face.object); } } void HalfEdgeMesh::CheckAll() const { PrintingScopedTimer timer("HalfEdgeMesh::CheckAll"); CheckPtrs(); // Every time a mesh component with index = X is referenced by some other // component, mark vector[X] = true in the corresponding vector. They should // become all true; there should be no unused elements. std::vector<bool> vertices_used(vertices_.size()); std::vector<bool> vertex_positions_used(vertex_positions_.size()); std::vector<bool> vertex_normals_used(vertex_normals_.size()); std::vector<bool> faces_used(faces_.size()); std::vector<bool> objects_used(objects_.size()); for(const HalfEdge &edge: half_edges_) { { auto &vp = vertex_positions_; auto &vn = vertex_normals_; vertices_used [ IndexOf(edge.vertex ).value ] = true; faces_used [ IndexOf(edge.face ).value ] = true; objects_used [ IndexOf(edge.face->object ).value ] = true; vertex_positions_used [ vp.IndexOf(edge.vertex->position).value ] = true; vertex_normals_used [ vn.IndexOf(edge.normal ).value ] = true; } assert(edge.vertex->position->isfinite()); assert(edge.normal->isfinite()); assert(&edge != edge.twin_edge); assert(&edge == edge.twin_edge->twin_edge); assert(edge.next_edge != edge.twin_edge); assert(edge.twin_edge->next_edge != &edge); assert(edge.face != edge.twin_edge->face); assert(edge.vertex != edge.twin_edge->vertex); assert(edge.face->object == edge.twin_edge->face->object); // square of the minimum allowable distance between Vertices // (v.len2() < 0.0001) == (v.len() < 0.01) constexpr double min2 = 0.0001; const Vector3d *start = edge.twin_edge->vertex->position; const Vector3d *end = edge.vertex->position; // TODO threshold? assert((*end - *start).len2() >= min2); // compare to every other edge on the same object and ensure they're // different (slow) for(const HalfEdge &other_edge: half_edges_) { if(&other_edge == &edge) continue; if(&other_edge == edge.twin_edge) continue; if(other_edge.face->object != edge.face->object) continue; const Vector3d *other_start = other_edge.twin_edge->vertex->position; const Vector3d *other_end = other_edge.vertex->position; // TODO threshold? assert((*start - *other_start).len2() >= min2 || (*end - *other_end).len2() >= min2); assert((*start - *other_end).len2() >= min2 || (*end - *other_start).len2() >= min2); } // walk the HalfEdges surrounding edge.face int edge_num = 0; bool found_face_edge = false; const HalfEdge *previous_edge = nullptr; const HalfEdge *current_edge = &edge; do { assert(current_edge->face == edge.face); if(current_edge == edge.face->edge) found_face_edge = true; previous_edge = current_edge; current_edge = current_edge->next_edge; edge_num++; } while(current_edge != &edge); assert(edge_num >= 3); assert(found_face_edge); assert(previous_edge != nullptr); // check normals /* switch(edge.type) { case NormalType::Constant: assert( *(edge.normal) == *(previous_edge->normal) ); break; case NormalType::Spherical: assert(start->len2() == end->len2()); break; case NormalType::X_Cylindrical: assert(start->y * start->y + start->z * start->z == end->y * end->y + end->z * end->z); break; case NormalType::Y_Cylindrical: assert(start->z * start->z + start->z * start->z == end->z * end->z + end->z * end->z); break; case NormalType::Z_Cylindrical: assert(start->x * start->x + start->y * start->y == end->x * end->x + end->y * end->y); break; default: assert(0); } */ // walk the HalfEdges surrounding edge.vertex bool found_this_edge = false; const HalfEdge *first_outgoing_edge = edge.vertex->edge; const HalfEdge *outgoing_edge = first_outgoing_edge; do { const HalfEdge *incoming_edge = outgoing_edge->twin_edge; assert(incoming_edge->vertex == edge.vertex); if(incoming_edge == &edge) found_this_edge = true; outgoing_edge = incoming_edge->next_edge; } while(outgoing_edge != first_outgoing_edge); assert(found_this_edge); } // no unused elements auto end = vertices_used.end(); assert(end == std::find(vertices_used.begin(), end, false)); end = vertex_positions_used.end(); assert(end == std::find(vertex_positions_used.begin(), end, false)); end = vertex_normals_used.end(); assert(end == std::find(vertex_normals_used.begin(), end, false)); end = faces_used.end(); assert(end == std::find(faces_used.begin(), end, false)); end = objects_used.end(); assert(end == std::find(objects_used.begin(), end, false)); } #endif // #ifndef NDEBUG std::unordered_set<HalfEdgeMesh::Face*> HalfEdgeMesh::FindConnectedFaces(Face *start_face) { std::unordered_set<Face*> visited; std::stack<Face*> stack; stack.push(start_face); while(!stack.empty()) { Face *current_face = stack.top(); stack.pop(); visited.insert(current_face); HalfEdge *start_edge = current_face->edge; HalfEdge *current_edge = start_edge; do { Face *next_face = current_edge->twin_edge->face; if(!visited.count(next_face)) stack.push(next_face); current_edge = current_edge->next_edge; } while(current_edge != start_edge); } return visited; } WavFrObj HalfEdgeMesh::MakeWavFrObj() const { PrintingScopedTimer timer("HalfEdgeMesh::MakeWavFrObj"); size_t num_vertex_positions = vertex_positions_.size(); std::vector<Vector3f> wavfr_vertices; wavfr_vertices.reserve(num_vertex_positions); for(const Vector3d &pos: vertex_positions_) wavfr_vertices.push_back( Vector3f{float(pos.x), float(pos.y), float(pos.z)}); size_t num_vertex_normals = vertex_normals_.size(); std::vector<Vector3f> wavfr_normals; wavfr_normals.reserve(num_vertex_normals); for(const Vector3d &normal: vertex_normals_) wavfr_normals.push_back( Vector3f{float(normal.x), float(normal.y), float(normal.z)}); size_t num_objects = objects_.size(); std::vector<WavFrObj::ObjObject> wavfr_objects; wavfr_objects.reserve(num_objects); for(const Object &object: objects_) wavfr_objects.push_back(WavFrObj::ObjObject(object.name)); for(const Face &face: faces_) { std::vector<WavFrObj::ObjVert> wavfr_face_verts; const HalfEdge *first_edge = face.edge; const HalfEdge *edge = first_edge; do { size_t position_index = vertex_positions_.IndexOf(edge->vertex->position).value; size_t normal_index = vertex_normals_.IndexOf(edge->normal).value; wavfr_face_verts.push_back( WavFrObj::ObjVert{int(position_index), -1, int(normal_index)}); edge = edge->next_edge; } while(edge != first_edge); size_t object_index = IndexOf(face.object).value; wavfr_objects[object_index].addFace( std::move(wavfr_face_verts)); } return WavFrObj(std::move(wavfr_vertices), std::vector<UvCoord>(), std::move(wavfr_normals), std::move(wavfr_objects)); } Vector3d HalfEdgeMesh::CenterOfBoundingBox(FaceIndex face_index) const { constexpr double inf = std::numeric_limits<double>::infinity(); double x_min = inf, x_max = -inf, y_min = inf, y_max = -inf, z_min = inf, z_max = -inf; HalfEdge *first_edge = get(face_index).edge; HalfEdge *edge = first_edge; do { Vector3d position = *(edge->vertex->position); x_min = std::min(x_min, position.x); x_max = std::max(x_max, position.x); y_min = std::min(y_min, position.y); y_max = std::max(y_max, position.y); z_min = std::min(z_min, position.z); z_max = std::max(z_max, position.z); edge = edge->next_edge; } while(edge != first_edge); assert(std::isfinite(x_min)); assert(std::isfinite(x_max)); assert(std::isfinite(y_min)); assert(std::isfinite(y_max)); assert(std::isfinite(z_min)); assert(std::isfinite(z_max)); return Vector3d{ (x_min+x_max)/2, (y_min+y_max)/2, (z_min+z_max)/2 }; } HalfEdgeMesh::VertexIndex HalfEdgeMesh::CutEdge(HalfEdgeIndex edge_index, double t) { VertexIndex new_vertex_index = AddVertex(); HalfEdgeIndex new_edge_a_index = AddHalfEdge(); HalfEdgeIndex new_edge_b_index = AddHalfEdge(); // reallocs may invalidate pointers, so add all components before getting // pointers HalfEdge *edge = &get(edge_index); HalfEdge *twin_edge = edge->twin_edge; HalfEdge *new_edge_a = &get(new_edge_a_index); HalfEdge *new_edge_b = &get(new_edge_b_index); Vertex *start = edge->twin_edge->vertex; Vertex *end = edge->vertex; Vertex *new_vertex = &get(new_vertex_index); // the edges now look like this: // _ _ _ _ _ _ // 🡕 edge 🡖 // start * * end // 🡔 _ _ _ _ _ _ 🡗 // edge.twin_edge // TODO deduplicate positions Vector3d start_position = *(start->position); Vector3d end_position = *(end->position); Vector3d new_vertex_position = start_position + t * (end_position - start_position); new_vertex->position = &get(AddVertexPosition(new_vertex_position)); edge->vertex = new_vertex; edge->twin_edge->vertex = new_vertex; // the edges now look like this: // _ _ _ // 🡕 edge 🡖 // * * new * // 🡔 _ _ _ 🡗 // twin_edge new_edge_a->twin_edge = edge->twin_edge; new_edge_a->next_edge = edge->next_edge; new_edge_a->face = edge->face; new_edge_a->vertex = end; new_edge_a->normal = edge->normal; new_edge_b->twin_edge = edge; new_edge_b->next_edge = twin_edge->next_edge; new_edge_b->face = twin_edge->face; new_edge_b->vertex = start; new_edge_b->normal = twin_edge->normal; edge->twin_edge->twin_edge = new_edge_a; edge->twin_edge->next_edge = new_edge_b; edge->twin_edge = new_edge_b; edge->next_edge = new_edge_a; new_vertex->edge = new_edge_a; // the edges now look like this: // _ _ _ _ _ _ // 🡕 edge 🡖 🡕 new a 🡖 // * * * // 🡔 _ _ _ 🡗 🡔 _ _ _ 🡗 // new b twin_edge /* #ifndef NDEBUG CheckAll(); #endif */ return new_vertex_index; } HalfEdgeMesh::HalfEdgeIndex HalfEdgeMesh::CutFace( FaceIndex face_idx, VertexIndex vertex_a_idx, VertexIndex vertex_b_idx ) { assert(vertex_a_idx != vertex_b_idx); Vertex *vertex_a = &get(vertex_a_idx); Vertex *vertex_b = &get(vertex_b_idx); HalfEdgeIndex edge_a_in_index, edge_a_out_index; HalfEdgeIndex edge_b_in_index, edge_b_out_index; { // reallocs may invalidate these pointers, so confine them to this block Face *face = &get(face_idx); HalfEdge *edge_a_in = nullptr, *edge_a_out = nullptr; HalfEdge *edge_b_in = nullptr, *edge_b_out = nullptr; HalfEdge *first_edge = face->edge; HalfEdge *current_edge = first_edge; do { if(current_edge->vertex == vertex_a) { edge_a_in = current_edge; edge_a_out = current_edge->next_edge; } if(current_edge->vertex == vertex_b) { edge_b_in = current_edge; edge_b_out = current_edge->next_edge; } current_edge = current_edge->next_edge; } while(current_edge != first_edge); assert(edge_a_in); assert(edge_a_out); assert(edge_b_in); assert(edge_b_out); if(edge_a_in == edge_b_out || edge_a_out == edge_b_in) return HalfEdgeIndex(); edge_a_in_index = IndexOf(edge_a_in); edge_a_out_index = IndexOf(edge_a_out); edge_b_in_index = IndexOf(edge_b_in); edge_b_out_index = IndexOf(edge_b_out); } // invalidates Face, HalfEdge pointers FaceIndex new_face_idx = AddFace(); // TODO support other edge types HalfEdgeIndex new_edge_idx = AddHalfEdge(); HalfEdgeIndex new_edge_twin_idx = AddHalfEdge(); HalfEdge *new_edge = &get(new_edge_idx); HalfEdge *new_edge_twin = &get(new_edge_twin_idx); Face *face = &get(face_idx); Face *new_face = &get(new_face_idx); HalfEdge *edge_a_in = &get(edge_a_in_index); HalfEdge *edge_a_out = &get(edge_a_out_index); HalfEdge *edge_b_in = &get(edge_b_in_index); HalfEdge *edge_b_out = &get(edge_b_out_index); // the face now looks like this: // // / \ // edge_a_in / \ edge_b_out // / \ // vertex_a * face * vertex_b // \ / // edge_a_out \ / edge_b_in // \ / new_face->object = face->object; face->edge = new_edge; new_face->edge = new_edge_twin; new_edge->twin_edge = new_edge_twin; new_edge->next_edge = edge_b_out; new_edge->face = face; new_edge->vertex = vertex_b; new_edge->normal = edge_b_in->normal; new_edge_twin->twin_edge = new_edge; new_edge_twin->next_edge = edge_a_out; new_edge_twin->face = new_face; new_edge_twin->vertex = vertex_a; new_edge_twin->normal = edge_a_in->normal; edge_a_in->next_edge = new_edge; edge_b_in->next_edge = new_edge_twin; HalfEdge *current_edge = edge_a_out; do { current_edge->face = new_face; current_edge = current_edge->next_edge; } while(current_edge != new_edge_twin); // the faces now look like this: // // / face \ // edge_a_in / \ edge_b_out // / new_edge \ // vertex_a * - - - - - - - - - * vertex_b // \ new_edge_twin / // edge_a_out \ / edge_b_in // \ new_face / /* #ifndef NDEBUG CheckAll(); #endif */ return new_edge_twin_idx; } void HalfEdgeMesh::LoopCut(std::unordered_set<HalfEdgeIndex> edge_idxs) { PrintingScopedTimer timer("HalfEdgeMesh::LoopCut"); #ifndef NDEBUG // "edge_idxs" must contain only matched pairs of HalfEdges for(HalfEdgeIndex edge_idx: edge_idxs) { HalfEdgeIndex twin_idx = IndexOf(get(edge_idx).twin_edge); assert(edge_idxs.count(twin_idx)); } // ensure every Vertex has 0 or 2 incoming and outgoing edges in "edge_idxs" // i.e. there is at most 1 cutting path through each Vertex for(Vertex &vertex: vertices_) { int outgoing_cut_edges = 0, incoming_cut_edges = 0; HalfEdge *first_outgoing_edge = vertex.edge; HalfEdge *outgoing_edge = first_outgoing_edge; do { HalfEdge *incoming_edge = outgoing_edge->twin_edge; if(edge_idxs.count(IndexOf(outgoing_edge))) outgoing_cut_edges++; if(edge_idxs.count(IndexOf(incoming_edge))) incoming_cut_edges++; outgoing_edge = incoming_edge->next_edge; } while(outgoing_edge != first_outgoing_edge); assert(outgoing_cut_edges == incoming_cut_edges); assert(outgoing_cut_edges == 0 || outgoing_cut_edges == 2); } #endif // a map from each Index in "edge_idxs" to the Index of the next HalfEdge in // the loop std::unordered_map<HalfEdgeIndex, HalfEdgeIndex> next_loop_edge_idxs; // populate "next_loop_edge_idxs" for(HalfEdgeIndex edge_idx: edge_idxs) { assert(!next_loop_edge_idxs.count(edge_idx)); HalfEdge *edge = &get(edge_idx); // find the HalfEdge following "edge" in the loop: this is the HalfEdge // exiting the Vertex "edge->vertex", which is not the twin of "edge", and // is in the set of loop edges "edge_idxs" HalfEdge *first_outgoing_edge = edge->vertex->edge; HalfEdge *outgoing_edge = first_outgoing_edge; while(outgoing_edge == edge->twin_edge || !edge_idxs.count(IndexOf(outgoing_edge))) { outgoing_edge = outgoing_edge->twin_edge->next_edge; // the loop should terminate before getting back to // "first_outgoing_edge_id" if(outgoing_edge == first_outgoing_edge) { std::cout << "HalfEdgeMesh::LoopCut failed: couldn't follow loop " "through vertex at " << *(edge->vertex->position) << '\n'; return; } } next_loop_edge_idxs[edge_idx] = IndexOf(outgoing_edge); } // when splitting a Vertex, one side gets the original Vertex and marks it as // "claimed" here, and subsequent visits must create new Vertices std::unordered_set<VertexIndex> claimed_vertex_indices; // Splitting an Object is the same, except it's possible for a single Object // to be cut by multiple, unconnected loops. We don't know how many new // Objects are needed until all loops are cut. So when making a cut, add the // new Face to "new_face_indices". These Faces, and all the Faces connected to // them, will get Objects assigned at the end. std::unordered_set<FaceIndex> new_face_indices; // make the cuts while(!edge_idxs.empty()) { // take an arbitrary HalfEdge and cut its associated loop HalfEdgeIndex first_edge_idx = *(edge_idxs.begin()); FaceIndex new_face_index = AddFace(); new_face_indices.insert(new_face_index); Face *new_face = &get(new_face_index); // invalidates Face pointers // may be reassigned to a new Object later new_face->object = get(first_edge_idx).face->object; // remember the 1st 3 vertices along the loop to get a normal vector later Vector3d sample_vertex_positions[3]; int sample_vertices = 0; VertexIndex saved_split_vertex_index; HalfEdgeIndex prev_edge_idx; HalfEdgeIndex edge_idx = first_edge_idx; do { // TODO pick these to avoid NaN normals if(sample_vertices < 3) { Vector3d *position = get(edge_idx).vertex->position; sample_vertex_positions[sample_vertices] = *position; sample_vertices++; } // invalidates HalfEdge pointers HalfEdge *new_twin_edge = &get(AddHalfEdge()); HalfEdge *edge = &get(edge_idx); HalfEdge *old_twin_edge = edge->twin_edge; new_twin_edge->twin_edge = edge; new_twin_edge->face = new_face; VertexIndex old_start_vertex_index = IndexOf(old_twin_edge->vertex); if(claimed_vertex_indices.count(old_start_vertex_index)) { // invalidates Vertex pointers VertexIndex new_start_vertex_index = AddVertex(); Vertex *new_start_vertex = &get(new_start_vertex_index); new_start_vertex->position = get(old_start_vertex_index).position; new_start_vertex->edge = edge; new_twin_edge->vertex = new_start_vertex; // Update all the HalfEdges on this side of the cut, that used to point // to the claimed Vertex, to point to the new Vertex, starting with the // "previous" HalfEdge. Or if we can't, because this is the first // iteration, and "prev_edge_idx" is null, then save the new Vertex so // we can update it later. if(prev_edge_idx.IsNull()) { saved_split_vertex_index = new_start_vertex_index; } else { HalfEdge *first_incoming_edge = &get(prev_edge_idx); HalfEdge *incoming_edge = first_incoming_edge; for(;;) { assert(incoming_edge->vertex == old_twin_edge->vertex); incoming_edge->vertex = new_start_vertex; if(edge_idxs.count(IndexOf(incoming_edge->next_edge))) break; incoming_edge = incoming_edge->next_edge->twin_edge; // we should end the fan before going all the way around the Vertex assert(incoming_edge != first_incoming_edge); } } } else { claimed_vertex_indices.insert(old_start_vertex_index); old_twin_edge->vertex->edge = edge; new_twin_edge->vertex = old_twin_edge->vertex; } // "edge" points at "new_twin_edge", but "old_twin_edge" may still // point at "edge". This will be fixed when "old_twin_edge"'s loop comes // up for cutting. edge->twin_edge = new_twin_edge; new_face->edge = new_twin_edge; edge_idxs.erase(edge_idx); prev_edge_idx = edge_idx; edge_idx = next_loop_edge_idxs[edge_idx]; } while(edge_idx != first_edge_idx); assert(new_face->edge != nullptr); if(!saved_split_vertex_index.IsNull()) { // Update the HalfEdges on this side of the cut for the saved Vertex. The // difference is that we can't check "edge_idxs" to see when we've // reached the end of the fan, because all the HalfEdges on this side of // the loop cut have been removed from "edge_idxs". But since the // "previous" HalfEdge is now the one right behind "loop_start_edge" in // the loop, we can use "loop_start_edge" to mark the end of the fan. assert(!prev_edge_idx.IsNull()); Vertex *new_start_vertex = &get(saved_split_vertex_index); HalfEdge *first_incoming_edge = &get(prev_edge_idx); HalfEdge *incoming_edge = first_incoming_edge; HalfEdge *loop_start_edge = &get(edge_idx); for(;;) { assert(incoming_edge->vertex != new_start_vertex); incoming_edge->vertex = new_start_vertex; if(incoming_edge->next_edge == loop_start_edge) break; incoming_edge = incoming_edge->next_edge->twin_edge; // we should end the fan before going all the way around the Vertex assert(incoming_edge != first_incoming_edge); } } assert(sample_vertices == 3); Vector3d &a = sample_vertex_positions[0]; Vector3d &b = sample_vertex_positions[1]; Vector3d &c = sample_vertex_positions[2]; Vector3d face_normal = cross(c - a, b - a).unit(); assert(face_normal.isfinite()); // invalidates previous normal pointers Vector3d *new_normal = &get(AddVertexNormal(face_normal)); edge_idx = first_edge_idx; do { HalfEdge *edge = &get(edge_idx); HalfEdge *new_twin_edge = edge->twin_edge; new_twin_edge->next_edge = get(prev_edge_idx).twin_edge; new_twin_edge->normal = new_normal; prev_edge_idx = edge_idx; edge_idx = next_loop_edge_idxs[edge_idx]; } while(edge_idx != first_edge_idx); } std::unordered_set<ObjectIndex> claimed_object_indices; while(!new_face_indices.empty()) { FaceIndex new_face_index = *(new_face_indices.begin()); new_face_indices.erase(new_face_index); Face *new_face = &get(new_face_index); ObjectIndex old_object_index = IndexOf(new_face->object); Object *new_object = nullptr; if(claimed_object_indices.count(old_object_index)) { std::string name = get(old_object_index).name + "-cut"; // invalidates Object pointers new_object = &get(AddObject(std::move(name))); } else { claimed_object_indices.insert(old_object_index); } std::unordered_set<Face*> faces = FindConnectedFaces(new_face); for(Face *face: faces) { new_face_indices.erase(IndexOf(face)); if(new_object) face->object = new_object; } } /* #ifndef NDEBUG CheckAll(); #endif */ } std::unordered_set<HalfEdgeMesh::HalfEdgeIndex> HalfEdgeMesh::Bisect(const Vector3d &normal) { PrintingScopedTimer timer("HalfEdgeMesh::Bisect"); // Objects which should be ignored, because they don't pass through the // bisecting plane (though they may have components inside the plane) std::unordered_set<ObjectIndex> ignored_objects; // populate "ignored_objects" // TODO edged HalfEdges may pass through plane despite all Vertices being on // one side { // an Object's location relative to the bisecting plane enum Location : char { Unknown = 0, InFront, // all Vertices are on or in front of the plane Behind, // all Vertices are on or behind the plane Through // Object has Vertices both in front and behind }; // Find each Object's location by checking all its Vertices. Objects // contained entirely inside the plane will remain "Unknown". size_t objects_size = objects_.size(); std::vector<Location> object_locations(objects_size); for(const Vertex &vertex: vertices_) { size_t object_index = IndexOf(vertex.edge->face->object).value; Location object_location = object_locations[object_index]; // if we've already found this Object's Vertices on both sides, don't // check the remaining Vertices if(object_location == Through) continue; double d = dot(normal, *(vertex.position)); if(d == 0 || std::isnan(d)) continue; Location vertex_location = (d < 0 ? Behind : InFront); if(object_location != vertex_location) { if(object_location == Unknown) { // this Vertex is on the same side as the previous Vertices object_locations[object_index] = vertex_location; } else { // this Vertex is on a different side as the previous Vertices object_locations[object_index] = Through; } } } // ignore Objects which don't pass through the plane for(size_t i = 0; i < objects_size; i++) { if(object_locations[i] != Through) ignored_objects.insert(ObjectIndex(i)); } } // all vertices lying on the plane: both new vertices created to bisect // edges, and existing vertices that happened to be on the plane already std::unordered_set<VertexIndex> planar_vertex_indices; // all edges (and their twins) lying on the plane: new edges bisecting // faces, and existing edges std::unordered_set<HalfEdgeIndex> planar_edge_indices; // a set of HalfEdge IDs to skip, because we already checked their twin std::unordered_set<HalfEdge*> checked_twin_edges; // TODO support other edge types size_t edge_num = half_edges_.size(); for(HalfEdgeIndex edge_index(0); edge_index < edge_num; ++edge_index) { HalfEdge *edge = &get(edge_index); if(ignored_objects.count(IndexOf(edge->face->object))) continue; if(checked_twin_edges.count(edge)) continue; checked_twin_edges.insert(edge->twin_edge); // line equation: S + t⋅D Vector3d S = *(edge->twin_edge->vertex->position); Vector3d D = *(edge->vertex->position) - S; // plane equation: 0 = a⋅x + b⋅y + c⋅z // (where abc are the xyz componets of normal) // // solve for t: // 0 = a⋅(Sx + t⋅Dx) + b⋅(Sy + t⋅Dy) + c⋅(Sz + t⋅Dz) // 0 = a⋅Sx + a⋅t⋅Dx + b⋅Sy + b⋅t⋅Dy + c⋅Sz + c⋅t⋅Dz // 0 = t⋅(a⋅Dx + b⋅Dy + c⋅Dz) + a⋅Sx + b⋅Sy + c⋅Sz // a⋅Sx + b⋅Sy + c⋅Sz dot(normal, S) // t = - -------------------- = - ---------------- // a⋅Dx + b⋅Dy + c⋅Dz dot(normal, D) // if the line parallel to the plane, then "normal" and D are at right // angles, and dot_D == 0 double dot_D = dot(normal, D); // if the dot_D == 0 && dot_S == 0, then the line is inside the plane double dot_S = dot(normal, S); if(dot_D == 0) { if(dot_S == 0) { planar_edge_indices.insert(edge_index); planar_edge_indices.insert(IndexOf(edge->twin_edge)); } } else { double t = - dot_S / dot_D; // TODO threshold? constexpr double epsilon = 0.0001; // does the intersection lie within the line segment? if(epsilon < t && t < 1-epsilon) { // Invalidates HalfEdge pointers. We got "edge_num" before the for // loop, so we won't iterate over any new HalfEdges appended by // CutEdge. planar_vertex_indices.insert(CutEdge(edge_index, t)); } // does the intersection lie at one end of the segment? if(-epsilon < t && t < epsilon) { VertexIndex start_vertex = IndexOf(get(edge_index).twin_edge->vertex); planar_vertex_indices.insert(start_vertex); } else if(1-epsilon < t && t < 1+epsilon) { VertexIndex end_vertex = IndexOf(get(edge_index).vertex); planar_vertex_indices.insert(end_vertex); } } } #ifndef NDEBUG CheckAll(); #endif std::vector<VertexIndex> planar_vertex_indices_on_this_face; size_t face_num = faces_.size(); for(FaceIndex face_index(0); face_index < face_num; ++face_index) { int num_vertices = 0; HalfEdge *first_edge = get(face_index).edge; HalfEdge *current_edge = first_edge; do { VertexIndex vertex_index = IndexOf(current_edge->vertex); if(planar_vertex_indices.count(vertex_index)) planar_vertex_indices_on_this_face.push_back(vertex_index); num_vertices++; current_edge = current_edge->next_edge; } while(current_edge != first_edge); // does this face have enough vertices for CutFace to work? if(num_vertices >= 4) { size_t num_vertices_on_plane = planar_vertex_indices_on_this_face.size(); if(num_vertices_on_plane == 2) { // invalidates Face and HalfEdge pointers HalfEdgeIndex new_edge_index = CutFace( face_index, planar_vertex_indices_on_this_face[0], planar_vertex_indices_on_this_face[1] ); if(!new_edge_index.IsNull()) { planar_edge_indices.insert(new_edge_index); planar_edge_indices.insert(IndexOf(get(new_edge_index).twin_edge)); } } else if(num_vertices_on_plane > 2) { // TODO support concave faces std::cout << "HalfEdgeMesh::Bisect skipping face at " << CenterOfBoundingBox(face_index) << " with " << num_vertices_on_plane << " of " << num_vertices << " on the plane\n"; } } planar_vertex_indices_on_this_face.clear(); } #ifndef NDEBUG CheckAll(); #endif return planar_edge_indices; } template<typename T> std::tuple<HalfEdgeMesh::ComponentIndex<T>, uintptr_t> HalfEdgeMesh::ComponentList<T>::Append(T e) { uintptr_t realloc_offset = 0; // unsigned so overflow is defined if(size_ == capacity_) { if(capacity_ == 0) capacity_ = 8; else capacity_ *= 2; T *new_list; if(std::is_pod<T>::value) { new_list = reinterpret_cast<T*>( std::realloc(list_, capacity_ * sizeof(T))); } else { new_list = new T[capacity_]; for(size_t i = 0; i < size_; i++) new_list[i] = std::move(list_[i]); delete[] list_; } if(list_) { // Cast to uintptr_t before subtraction. Subtracting pointers directly // gives a result in units of sizeof(T) bytes, suitable for offsetting // an index into an array of T[]. However, "list_" and "new_list" may // not be divisible by sizeof(T) (if alignof(T) < sizeof(T)), and more // importantly may have different remainders divided by sizeof(T), so // pointer subtraction may give an inexact result. realloc_offset = uintptr_t(new_list) - uintptr_t(list_); } list_ = new_list; } list_[size_] = std::move(e); ComponentIndex<T> index(size_); size_++; return {index, realloc_offset}; } namespace { // RXDY = sqrt(X)/Y constexpr double R2D2 = 0.7071067811865475244008443621048490392848; // beep boop constexpr double R3D2 = 0.8660254037844386467637231707529361834714; constexpr double R6D4 = 0.6123724356957945245493210186764728479915; constexpr double R10D4 = 0.7905694150420948329997233861081796334299; const double AlignedPlaneOffsets[] = { -1, -R3D2, -R2D2, -R6D4, -0.5, 0, 0.5, R6D4, R2D2, R3D2, 1 }; const double CylinderRadii[] = { R2D2, R10D4, R3D2, 1 }; } // namespace /* create an icosohedron with a unit circumsphere an icosohedron's vertices make 3 golden rectangles: * - - - - - - - - * | | | | | | | | * - - -| / |- - - - - - * / | / | / / | / | / / / / / * / * - - - - - - - -| - - - - - - - - - * | | | | | / | | | / | | | / | * - -|/ - - - - - * * number the vertices like so: * 0 /| 8 * - - - * 9 / | | | / | 4 * - - - - - - - * 7 | | / * 1 / / | | 3 * / / / | | | / 5 * - - - - - - - * 6 | | | / | | |/ 11 * - - - * 10 2 * Z | X |/ Y - * for a 2 x 2⋅φ rectangle, vertex 0 is at coordinates: ( φ, 0, 1 ) with distance from the origin: ________ √ 1² + φ² to scale vertices down onto a unit sphere, divide everything by that distance, and call the resulting values L and S: ________ ________ ( L, 0, S ) = ( φ ÷ √ 1² + φ², 0, 1 ÷ √ 1² + φ² ) */ HalfEdgeMesh MakeIcosohedron() { PrintingScopedTimer timer("MakeIcosohedron"); constexpr double L = 0.8506508083520399321815404970630110722404; constexpr double S = 0.5257311121191336060256690848478766072855; Vector3d icosohedron_vertices[12] = { Vector3d{ L, 0, S }, Vector3d{ L, 0, -S }, Vector3d{ -L, 0, -S }, Vector3d{ -L, 0, S }, Vector3d{ S, L, 0 }, Vector3d{ -S, L, 0 }, Vector3d{ -S, -L, 0 }, Vector3d{ S, -L, 0 }, Vector3d{ 0, S, L }, Vector3d{ 0, -S, L }, Vector3d{ 0, -S, -L }, Vector3d{ 0, S, -L }, }; int icosohedron_faces[20][3] = { { 0, 1, 4}, { 0, 7, 1}, { 2, 3, 5}, { 2, 6, 3}, { 4, 5, 8}, { 4,11, 5}, { 6, 7, 9}, { 6,10, 7}, { 0, 4, 8}, { 0, 9, 7}, { 0, 8, 9}, { 3, 9, 8}, { 3, 8, 5}, { 3, 6, 9}, { 1,11, 4}, { 1, 7,10}, { 1,10,11}, { 2,11,10}, { 2, 5,11}, { 2,10, 6}, }; using VertexIndex = HalfEdgeMesh::VertexIndex; using VertexNormalIndex = HalfEdgeMesh::VertexNormalIndex; using VertexPositionIndex = HalfEdgeMesh::VertexPositionIndex; using HalfEdgeIndex = HalfEdgeMesh::HalfEdgeIndex; using FaceIndex = HalfEdgeMesh::FaceIndex; using ObjectIndex = HalfEdgeMesh::ObjectIndex; using Vertex = HalfEdgeMesh::Vertex; using HalfEdge = HalfEdgeMesh::HalfEdge; using Face = HalfEdgeMesh::Face; using Object = HalfEdgeMesh::Object; using NormalType = HalfEdgeMesh::NormalType; HalfEdgeMesh mesh; ObjectIndex object = mesh.AddObject("sphere"); Object *object_ptr = &mesh[object]; VertexPositionIndex positions[12]; VertexNormalIndex normals[12]; VertexIndex vertices[12]; for(int i = 0; i < 12; i++) { // on a unit sphere, position and normal vectors are identical positions[i] = mesh.AddVertexPosition(icosohedron_vertices[i]); normals[i] = mesh.AddVertexNormal(icosohedron_vertices[i]); vertices[i] = mesh.AddVertex(); mesh[vertices[i]].position = &mesh[positions[i]]; } std::unordered_map<std::pair<VertexIndex,VertexIndex>, HalfEdgeIndex> edges; for(int i = 0; i < 20; i++) { int a_number = icosohedron_faces[i][0]; int b_number = icosohedron_faces[i][1]; int c_number = icosohedron_faces[i][2]; VertexIndex a = vertices[a_number]; VertexIndex b = vertices[b_number]; VertexIndex c = vertices[c_number]; Vertex *a_ptr = &mesh[a]; Vertex *b_ptr = &mesh[b]; Vertex *c_ptr = &mesh[c]; HalfEdgeIndex ab = mesh.AddHalfEdge(); HalfEdgeIndex bc = mesh.AddHalfEdge(); HalfEdgeIndex ca = mesh.AddHalfEdge(); HalfEdge *ab_ptr = &mesh[ab]; HalfEdge *bc_ptr = &mesh[bc]; HalfEdge *ca_ptr = &mesh[ca]; edges.insert(std::make_pair(std::make_pair(a,b), ab)); edges.insert(std::make_pair(std::make_pair(b,c), bc)); edges.insert(std::make_pair(std::make_pair(c,a), ca)); if(a_ptr->edge == nullptr) a_ptr->edge = ab_ptr; if(b_ptr->edge == nullptr) b_ptr->edge = bc_ptr; if(c_ptr->edge == nullptr) c_ptr->edge = ca_ptr; auto ba_iter = edges.find(std::make_pair(b,a)); if(ba_iter != edges.end()) { HalfEdge *ba_ptr = &mesh[ba_iter->second]; ab_ptr->twin_edge = ba_ptr; ba_ptr->twin_edge = ab_ptr; } auto cb_iter = edges.find(std::make_pair(c,b)); if(cb_iter != edges.end()) { HalfEdge *cb_ptr = &mesh[cb_iter->second]; bc_ptr->twin_edge = cb_ptr; cb_ptr->twin_edge = bc_ptr; } auto ac_iter = edges.find(std::make_pair(a,c)); if(ac_iter != edges.end()) { HalfEdge *ac_ptr = &mesh[ac_iter->second]; ca_ptr->twin_edge = ac_ptr; ac_ptr->twin_edge = ca_ptr; } ab_ptr->next_edge = bc_ptr; bc_ptr->next_edge = ca_ptr; ca_ptr->next_edge = ab_ptr; ab_ptr->vertex = b_ptr; bc_ptr->vertex = c_ptr; ca_ptr->vertex = a_ptr; ab_ptr->normal = &mesh[normals[b_number]]; bc_ptr->normal = &mesh[normals[c_number]]; ca_ptr->normal = &mesh[normals[a_number]]; ab_ptr->type = NormalType::Spherical; bc_ptr->type = NormalType::Spherical; ca_ptr->type = NormalType::Spherical; FaceIndex abc = mesh.AddFace(); Face *abc_ptr = &mesh[abc]; abc_ptr->edge = ab_ptr; abc_ptr->object = object_ptr; ab_ptr->face = abc_ptr; bc_ptr->face = abc_ptr; ca_ptr->face = abc_ptr; } #ifndef NDEBUG mesh.CheckAll(); #endif return mesh; } void SubdivideGeosphere(HalfEdgeMesh &mesh) { PrintingScopedTimer timer("SubdivideGeosphere"); using VertexIndex = HalfEdgeMesh::VertexIndex; using VertexNormalIndex = HalfEdgeMesh::VertexNormalIndex; using VertexPositionIndex = HalfEdgeMesh::VertexPositionIndex; using HalfEdgeIndex = HalfEdgeMesh::HalfEdgeIndex; using FaceIndex = HalfEdgeMesh::FaceIndex; using Vertex = HalfEdgeMesh::Vertex; using HalfEdge = HalfEdgeMesh::HalfEdge; using NormalType = HalfEdgeMesh::NormalType; #ifndef NDEBUG { // all Faces must be triangles size_t face_count = mesh.FaceCount(); for(FaceIndex f(0); f < face_count; ++f) { HalfEdge *start = mesh[f].edge; assert(start->next_edge->next_edge->next_edge == start); } // all Vertices must be on the surface of a unit sphere size_t position_count = mesh.VertexPositionCount(); for(VertexPositionIndex p; p < position_count; ++p) { double len2 = mesh[p].len2(); assert(0.9999 < len2 && len2 < 1.0001); // TODO threshold? } } #endif // after cutting an edge, put its twin here so we don't cut the twin again std::unordered_set<HalfEdgeIndex> cut_twins; std::unordered_set<VertexIndex> new_vertices; size_t edge_count = mesh.HalfEdgeCount(); for(HalfEdgeIndex e(0); e < edge_count; ++e) { if(cut_twins.count(e)) continue; cut_twins.insert(mesh.IndexOf(mesh[e].twin_edge)); VertexIndex v = mesh.CutEdge(e, 0.5); new_vertices.insert(v); Vertex *v_ptr = &mesh[v]; Vector3d *p_ptr = v_ptr->position; *p_ptr = p_ptr->unit(); VertexNormalIndex n = mesh.AddVertexNormal(*p_ptr); Vector3d *n_ptr = &mesh[n]; HalfEdge *incoming_edge_1 = v_ptr->edge->twin_edge; HalfEdge *incoming_edge_2 = incoming_edge_1->next_edge->twin_edge; incoming_edge_1->normal = n_ptr; incoming_edge_1->type = NormalType::Spherical; incoming_edge_2->normal = n_ptr; incoming_edge_2->type = NormalType::Spherical; } size_t face_count = mesh.FaceCount(); for(FaceIndex f(0); f < face_count; ++f) { // find the 3 vertices to be joined VertexIndex new_vertices_on_this_face[3]; int new_vertices_found = 0; HalfEdge *start_edge = mesh[f].edge; HalfEdge *current_edge = start_edge; for(;;) { VertexIndex v = mesh.IndexOf(current_edge->vertex); if(new_vertices.count(v)) { new_vertices_on_this_face[new_vertices_found] = v; new_vertices_found++; if(new_vertices_found == 3) break; } current_edge = current_edge->next_edge; assert(current_edge != start_edge); } mesh.CutFace(f, new_vertices_on_this_face[0], new_vertices_on_this_face[1]); mesh.CutFace(f, new_vertices_on_this_face[1], new_vertices_on_this_face[2]); mesh.CutFace(f, new_vertices_on_this_face[2], new_vertices_on_this_face[0]); } #ifndef NDEBUG mesh.CheckAll(); #endif } /* each cell's components are indexed like so: vertices: faces: * - - - - - - * / / / 5 / 7 - - - - - 5 * / /- * * /| /| /| * - - - - - - * | /| / | / | / | | | / | 6 - - - - - 4 | / | | 1 | / | | | | | * | * - - - - - - * | * | | 3 - - - -|- 1 Z | 3 | | | | | 2 | | / | / | X | * | | - * | * |/ |/ |/ | / | 0 | | / 2 - - - - - 0 Y - * | / | | | / |/ | | - * |/ * * - - - - - - * / * 14 / 4 / half-edges: * - - - - - - * / / / / * - - - - - - * 10 / / 8 / / * - - - - - - * 12 15 * * - - - - - - * * 11 /| | | 9 /| / | | | / | / | 22 23 | 13 | 19 / | 18 * | * - - - - - - * | * | | | | | | | | | | * | * - - - - | - * | * 20 | / 21 | 7 | 17 16 | / | / | | | / |/ 3 | | |/ 1 * * - - - - - - * * 5 6 * - - - - - - * / / 2 / / 0 / / * - - - - - - * 4 */ HalfEdgeMesh MakeAlignedCells() { PrintingScopedTimer timer("MakeAlignedCells"); HalfEdgeMesh mesh; using VertexIndex = HalfEdgeMesh::VertexIndex; using VertexNormalIndex = HalfEdgeMesh::VertexNormalIndex; using VertexPositionIndex = HalfEdgeMesh::VertexPositionIndex; using HalfEdgeIndex = HalfEdgeMesh::HalfEdgeIndex; using FaceIndex = HalfEdgeMesh::FaceIndex; using ObjectIndex = HalfEdgeMesh::ObjectIndex; // create the 6 axis-aligned normal vectors VertexNormalIndex x_pos = mesh.AddVertexNormal( UnitX_Vector3d); VertexNormalIndex x_neg = mesh.AddVertexNormal(-UnitX_Vector3d); VertexNormalIndex y_pos = mesh.AddVertexNormal( UnitY_Vector3d); VertexNormalIndex y_neg = mesh.AddVertexNormal(-UnitY_Vector3d); VertexNormalIndex z_pos = mesh.AddVertexNormal( UnitZ_Vector3d); VertexNormalIndex z_neg = mesh.AddVertexNormal(-UnitZ_Vector3d); constexpr size_t size = std::size(AlignedPlaneOffsets); // a unique_ptr to a size x size x size 3D array of VertexPositionIndex auto positions = std::make_unique<VertexPositionIndex[][size][size]>(size); // populate vertex positions at every intersection of 3 axis-aligned planes for(size_t zi = 0; zi < size; zi++) { double z = AlignedPlaneOffsets[zi]; for(size_t yi = 0; yi < size; yi++) { double y = AlignedPlaneOffsets[yi]; for(size_t xi = 0; xi < size; xi++) { double x = AlignedPlaneOffsets[xi]; positions.get()[zi][yi][xi] = mesh.AddVertexPosition(Vector3d{x,y,z}); } } } for(size_t zi = 0; zi < size-1; zi++) { for(size_t yi = 0; yi < size-1; yi++) { for(size_t xi = 0; xi < size-1; xi++) { std::string object_name = std::to_string(zi) + '-' + std::to_string(yi) + '-' + std::to_string(xi); ObjectIndex object = mesh.AddObject(std::move(object_name)); FaceIndex faces[6]; for(int i = 0; i < 6; i++) { faces[i] = mesh.AddFace(); mesh[faces[i]].object = &mesh[object]; } VertexIndex vertices[8]; vertices[0] = mesh.AddVertex(); vertices[1] = mesh.AddVertex(); vertices[2] = mesh.AddVertex(); vertices[3] = mesh.AddVertex(); vertices[4] = mesh.AddVertex(); vertices[5] = mesh.AddVertex(); vertices[6] = mesh.AddVertex(); vertices[7] = mesh.AddVertex(); mesh[vertices[0]].position = &mesh[positions.get()[zi ][yi ][xi ]]; mesh[vertices[1]].position = &mesh[positions.get()[zi ][yi ][xi+1]]; mesh[vertices[2]].position = &mesh[positions.get()[zi ][yi+1][xi ]]; mesh[vertices[3]].position = &mesh[positions.get()[zi ][yi+1][xi+1]]; mesh[vertices[4]].position = &mesh[positions.get()[zi+1][yi ][xi ]]; mesh[vertices[5]].position = &mesh[positions.get()[zi+1][yi ][xi+1]]; mesh[vertices[6]].position = &mesh[positions.get()[zi+1][yi+1][xi ]]; mesh[vertices[7]].position = &mesh[positions.get()[zi+1][yi+1][xi+1]]; // create the 12 edges (2 half-edges each) of the cell HalfEdgeIndex edges[24]; for(int i = 0; i < 24; i++) edges[i] = mesh.AddHalfEdge(); // a macro to help fill in the edge data #define hcm_set_linear_edge(this, twin, next, face_, vert, norm) { \ HalfEdgeMesh::HalfEdge &edge = mesh[edges[this]]; \ edge.twin_edge = &mesh[edges[twin]]; \ edge.next_edge = &mesh[edges[next]]; \ edge.face = &mesh[faces[face_]]; \ edge.vertex = &mesh[vertices[vert]]; \ edge.normal = &mesh[norm]; \ } // this twin next face vert norm hcm_set_linear_edge( 0, 1, 4, 4, 0, z_neg) hcm_set_linear_edge( 1, 0, 18, 2, 1, y_neg) hcm_set_linear_edge( 2, 3, 6, 4, 3, z_neg) hcm_set_linear_edge( 3, 2, 20, 3, 2, y_pos) hcm_set_linear_edge( 4, 5, 2, 4, 2, z_neg) hcm_set_linear_edge( 5, 4, 17, 0, 0, x_neg) hcm_set_linear_edge( 6, 7, 0, 4, 1, z_neg) hcm_set_linear_edge( 7, 6, 23, 1, 3, x_pos) hcm_set_linear_edge( 8, 9, 14, 5, 5, z_pos) hcm_set_linear_edge( 9, 8, 16, 2, 4, y_neg) hcm_set_linear_edge( 10, 11, 12, 5, 6, z_pos) hcm_set_linear_edge( 11, 10, 22, 3, 7, y_pos) hcm_set_linear_edge( 12, 13, 8, 5, 4, z_pos) hcm_set_linear_edge( 13, 12, 21, 0, 6, x_neg) hcm_set_linear_edge( 14, 15, 10, 5, 7, z_pos) hcm_set_linear_edge( 15, 14, 19, 1, 5, x_pos) hcm_set_linear_edge( 16, 17, 1, 2, 0, y_neg) hcm_set_linear_edge( 17, 16, 13, 0, 4, x_neg) hcm_set_linear_edge( 18, 19, 9, 2, 5, y_neg) hcm_set_linear_edge( 19, 18, 7, 1, 1, x_pos) hcm_set_linear_edge( 20, 21, 11, 3, 6, y_pos) hcm_set_linear_edge( 21, 20, 5, 0, 2, x_neg) hcm_set_linear_edge( 22, 23, 3, 3, 3, y_pos) hcm_set_linear_edge( 23, 22, 15, 1, 7, x_pos) #undef hcm_set_linear_edge mesh[faces[0]].edge = &mesh[edges[5]]; mesh[faces[1]].edge = &mesh[edges[7]]; mesh[faces[2]].edge = &mesh[edges[1]]; mesh[faces[3]].edge = &mesh[edges[3]]; mesh[faces[4]].edge = &mesh[edges[2]]; mesh[faces[5]].edge = &mesh[edges[8]]; mesh[vertices[0]].edge = &mesh[edges[1]]; mesh[vertices[1]].edge = &mesh[edges[0]]; mesh[vertices[2]].edge = &mesh[edges[2]]; mesh[vertices[3]].edge = &mesh[edges[3]]; mesh[vertices[4]].edge = &mesh[edges[8]]; mesh[vertices[5]].edge = &mesh[edges[9]]; mesh[vertices[6]].edge = &mesh[edges[11]]; mesh[vertices[7]].edge = &mesh[edges[10]]; } } } #ifndef NDEBUG mesh.CheckAll(); #endif return mesh; }
34.978868
80
0.608762
paulmiller
7adc771d4ad2194a9a2a255551fb24ac549e72b7
1,136
cpp
C++
dll/src/EngineAPI/Color.cpp
Dingf/GDCommunityLauncher
43ca2d6fa8024dffad1e0919c609b0d48a3427b7
[ "MIT" ]
null
null
null
dll/src/EngineAPI/Color.cpp
Dingf/GDCommunityLauncher
43ca2d6fa8024dffad1e0919c609b0d48a3427b7
[ "MIT" ]
null
null
null
dll/src/EngineAPI/Color.cpp
Dingf/GDCommunityLauncher
43ca2d6fa8024dffad1e0919c609b0d48a3427b7
[ "MIT" ]
null
null
null
#include "EngineAPI/Color.h" namespace EngineAPI { const Color Color::BLUE(0.224f, 0.667f, 0.808f, 1.0f); const Color Color::GREEN(0.063f, 0.918f, 0.365f, 1.0f); const Color Color::RED(1.000f, 0.258f, 0.000f, 1.0f); const Color Color::WHITE(1.000f, 1.000f, 1.000f, 1.0f); const Color Color::YELLOW(1.000f, 0.960f, 0.170f, 1.0f); const Color Color::PURPLE(0.738f, 0.579f, 0.776f, 1.0f); const Color Color::ORANGE(0.950f, 0.640f, 0.300f, 1.0f); const Color Color::SILVER(0.600f, 0.600f, 0.600f, 1.0f); const Color Color::FUSHIA(1.000f, 0.411f, 0.705f, 1.0f); const Color Color::CYAN(0.000f, 1.000f, 1.000f, 1.0f); const Color Color::INDIGO(0.350f, 0.010f, 0.600f, 1.0f); const Color Color::AQUA(0.500f, 1.000f, 0.831f, 1.0f); const Color Color::MAROON(0.500f, 0.000f, 0.000f, 1.0f); const Color Color::KHAKI(0.941f, 0.901f, 0.549f, 1.0f); const Color Color::DARK_GRAY(0.100f, 0.100f, 0.100f, 1.0f); const Color Color::TEAL(0.000f, 1.000f, 0.820f, 1.0f); const Color Color::OLIVE(0.570f, 0.797f, 0.000f, 1.0f); const Color Color::TAN(0.898f, 0.847f, 0.698f, 1.0f); }
49.391304
63
0.639965
Dingf
7add2ca114c004456a6b0bd40f20646ff4e1ea83
1,009
cpp
C++
Codes/Maths/sample-problems/LeetCode-216-combination-sum-ii-v2.cpp
fahimfarhan/FarCryCoding
ed9005194736c2b719823683c1295946bcb49910
[ "MIT" ]
null
null
null
Codes/Maths/sample-problems/LeetCode-216-combination-sum-ii-v2.cpp
fahimfarhan/FarCryCoding
ed9005194736c2b719823683c1295946bcb49910
[ "MIT" ]
null
null
null
Codes/Maths/sample-problems/LeetCode-216-combination-sum-ii-v2.cpp
fahimfarhan/FarCryCoding
ed9005194736c2b719823683c1295946bcb49910
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<vector<int>> combinationSum3(int k, int n) { this->k = k; this->n = n; this->ssf = 0; isVisited.resize(10, false); path.clear(); result.clear(); for(int i=1; i<10; i++) { backTrack(i, 1); } return result; } private: int k, n, ssf; vector<vector<int> > result; vector<int> path; vector<bool> isVisited; void backTrack(const int& u, int h) { if(h>k) { return; } push(u); if( (h == k) && (ssf == n) ) { vector<int> someClone(path); result.push_back(someClone); } else { int h1 = h + 1; for(int v=u+1; v<10; v++) { backTrack(v, h1); } } pop(u); } void push(const int& u) { isVisited[u] = true; path.push_back(u); ssf += u; } void pop(const int& u) { isVisited[u] = false; path.pop_back(); ssf-=u; } }; int main() { return 0; }
15.287879
55
0.49554
fahimfarhan
7ade4fcf23be7aa9cadc6ffe27b203ec1247194d
10,363
cpp
C++
src/apps/mplayerc/PlayerVolumeCtrl.cpp
chinajeffery/MPC-BE--1.2.3
2229fde5535f565ba4a496a7f73267bd2c1ad338
[ "MIT" ]
null
null
null
src/apps/mplayerc/PlayerVolumeCtrl.cpp
chinajeffery/MPC-BE--1.2.3
2229fde5535f565ba4a496a7f73267bd2c1ad338
[ "MIT" ]
1
2019-11-14T04:18:32.000Z
2019-11-14T04:18:32.000Z
src/apps/mplayerc/PlayerVolumeCtrl.cpp
chinajeffery/MPC-BE--1.2.3
2229fde5535f565ba4a496a7f73267bd2c1ad338
[ "MIT" ]
null
null
null
/* * $Id: VolumeCtrl.cpp 527 2012-06-10 13:47:31Z exodus8 $ * * (C) 2003-2006 Gabest * (C) 2006-2013 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * MPC-BE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include "MainFrm.h" #include "PlayerVolumeCtrl.h" // CVolumeCtrl IMPLEMENT_DYNAMIC(CVolumeCtrl, CSliderCtrl) CVolumeCtrl::CVolumeCtrl(bool fSelfDrawn) : m_fSelfDrawn(fSelfDrawn) { } CVolumeCtrl::~CVolumeCtrl() { } bool CVolumeCtrl::Create(CWnd* pParentWnd) { VERIFY(CSliderCtrl::Create(WS_CHILD|WS_VISIBLE|TBS_NOTICKS|TBS_HORZ|TBS_TOOLTIPS, CRect(0,0,0,0), pParentWnd, IDC_SLIDER1)); AppSettings& s = AfxGetAppSettings(); EnableToolTips(TRUE); SetRange(0, 100); SetPos(s.nVolume); SetPageSize(s.nVolumeStep); SetLineSize(0); iDisableXPToolbars = s.fDisableXPToolbars + 1; iThemeBrightness = s.nThemeBrightness; iThemeRed = s.nThemeRed; iThemeGreen = s.nThemeGreen; iThemeBlue = s.nThemeBlue; return TRUE; } void CVolumeCtrl::SetPosInternal(int pos) { SetPos(pos); GetParent()->PostMessage(WM_HSCROLL, MAKEWPARAM((short)pos, SB_THUMBPOSITION), (LPARAM)m_hWnd); } void CVolumeCtrl::IncreaseVolume() { // align volume up to step. recommend using steps 1, 2, 5 and 10 SetPosInternal(GetPos() + GetPageSize() - GetPos() % GetPageSize()); } void CVolumeCtrl::DecreaseVolume() { // align volume down to step. recommend using steps 1, 2, 5 and 10 int m = GetPos() % GetPageSize(); SetPosInternal(GetPos() - (m ? m : GetPageSize())); } BEGIN_MESSAGE_MAP(CVolumeCtrl, CSliderCtrl) ON_WM_ERASEBKGND() ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, OnNMCustomdraw) ON_WM_LBUTTONDOWN() ON_WM_SETFOCUS() ON_WM_HSCROLL_REFLECT() ON_WM_SETCURSOR() ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnToolTipNotify) END_MESSAGE_MAP() // CVolumeCtrl message handlers BOOL CVolumeCtrl::OnEraseBkgnd(CDC* pDC) { return TRUE; } void CVolumeCtrl::OnNMCustomdraw(NMHDR* pNMHDR, LRESULT* pResult) { LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR); LRESULT lr = CDRF_DODEFAULT; AppSettings& s = AfxGetAppSettings(); int R, G, B, R2, G2, B2; GRADIENT_RECT gr[1] = {{0, 1}}; if (m_fSelfDrawn) { switch (pNMCD->dwDrawStage) { case CDDS_PREPAINT: if (s.fDisableXPToolbars && (m_bmUnderCtrl.GetSafeHandle() == NULL || iDisableXPToolbars == 1 || iThemeBrightness != s.nThemeBrightness || iThemeRed != s.nThemeRed || iThemeGreen != s.nThemeGreen || iThemeBlue != s.nThemeBlue)) { CDC dc; dc.Attach(pNMCD->hdc); CRect r; GetClientRect(&r); InvalidateRect(&r); CDC memdc; int m_nHeight = ((CMainFrame*)AfxGetMainWnd())->m_wndToolBar.m_nButtonHeight; int m_nBMedian = m_nHeight - 3 - 0.5 * m_nHeight - 8; int height = r.Height() + m_nBMedian + 4; int fp = m_logobm.FileExists(CString(_T("background"))); if (NULL != fp) { ThemeRGB(s.nThemeRed, s.nThemeGreen, s.nThemeBlue, R, G, B); m_logobm.LoadExternalGradient("background", &dc, r, 22, s.nThemeBrightness, R, G, B); } else { ThemeRGB(50, 55, 60, R, G, B); ThemeRGB(20, 25, 30, R2, G2, B2); TRIVERTEX tv[2] = { {r.left, r.top - m_nBMedian, R*256, G*256, B*256, 255*256}, {r.Width(), height, R2*256, G2*256, B2*256, 255*256}, }; dc.GradientFill(tv, 2, gr, 1, GRADIENT_FILL_RECT_V); } memdc.CreateCompatibleDC(&dc); if (m_bmUnderCtrl.GetSafeHandle() != NULL) { m_bmUnderCtrl.DeleteObject(); } m_bmUnderCtrl.CreateCompatibleBitmap(&dc, r.Width(), r.Height()); CBitmap *bmOld = memdc.SelectObject(&m_bmUnderCtrl); if (iDisableXPToolbars == 1) { iDisableXPToolbars++; } memdc.BitBlt(r.left, r.top, r.Width(), r.Height(), &dc, r.left, r.top, SRCCOPY); dc.Detach(); DeleteObject(memdc.SelectObject(bmOld)); memdc.DeleteDC(); } lr = CDRF_NOTIFYITEMDRAW; if (m_fSetRedraw) { lr |= CDRF_NOTIFYPOSTPAINT; } break; case CDDS_ITEMPREPAINT: case CDDS_POSTPAINT: if (s.fDisableXPToolbars && m_bmUnderCtrl.GetSafeHandle() != NULL) { CDC dc; dc.Attach(pNMCD->hdc); CRect r; GetClientRect(&r); InvalidateRect(&r); CDC memdc; memdc.CreateCompatibleDC(&dc); CBitmap *bmOld = memdc.SelectObject(&m_bmUnderCtrl); if (iDisableXPToolbars == 0) { iDisableXPToolbars++; } iThemeBrightness = s.nThemeBrightness; iThemeRed = s.nThemeRed; iThemeGreen = s.nThemeGreen; iThemeBlue = s.nThemeBlue; int pa = 255 * 256; unsigned p1 = s.clrOutlineABGR, p2 = s.clrFaceABGR; int nVolume = GetPos(); if (nVolume <= GetPageSize()) { nVolume = 0; } int m_nVolPos = r.left + (nVolume * 0.43) + 4; int fp = m_logobm.FileExists(CString(_T("volume"))); if (NULL != fp) { m_logobm.LoadExternalGradient("volume", &dc, r, 0, -1, -1, -1, -1); } else { int ir1 = p1 * 256; int ig1 = (p1 >> 8) * 256; int ib1 = (p1 >> 16) * 256; int ir2 = p2 * 256; int ig2 = (p2 >> 8) * 256; int ib2 = (p2 >> 16) * 256; TRIVERTEX tv[2] = { {0, 0, ir1, ig1, ib1, pa}, {50, 1, ir2, ig2, ib2, pa}, }; dc.GradientFill(tv, 2, gr, 1, GRADIENT_FILL_RECT_H); } unsigned p3 = m_nVolPos > 30 ? dc.GetPixel(m_nVolPos, 0) : dc.GetPixel(30, 0); CPen penLeft(p2 == 0x00ff00ff ? PS_NULL : PS_SOLID, 0, p3); dc.BitBlt(0, 0, r.Width(), r.Height(), &memdc, 0, 0, SRCCOPY); DeleteObject(memdc.SelectObject(bmOld)); memdc.DeleteDC(); r.DeflateRect(4, 2, 9, 6); CopyRect(&pNMCD->rc, &r); CPen penRight(p1 == 0x00ff00ff ? PS_NULL : PS_SOLID, 0, p1); CPen *penOld = dc.SelectObject(&penRight); int nposx, nposy; for (int i = 4; i <= 44; i += 4) { nposx = r.left + i; nposy = r.bottom - (r.Height() * i) / (r.Width() + 6); i < m_nVolPos ? dc.SelectObject(penLeft) : dc.SelectObject(penRight); dc.MoveTo(nposx, nposy); //top_left dc.LineTo(nposx + 2, nposy); //top_right dc.LineTo(nposx + 2, r.bottom); //bottom_right dc.LineTo(nposx, r.bottom); //bottom_left dc.LineTo(nposx, nposy); //top_left if (!s.fMute) { dc.MoveTo(nposx + 1, nposy - 1); //top_middle dc.LineTo(nposx + 1, r.bottom + 2); //bottom_middle } } dc.SelectObject(penOld); dc.Detach(); lr = CDRF_SKIPDEFAULT; m_fSetRedraw = false; } else if (!s.fDisableXPToolbars && pNMCD->dwItemSpec == TBCD_CHANNEL) { if (m_bmUnderCtrl.GetSafeHandle() != NULL) { m_bmUnderCtrl.DeleteObject(); } CDC dc; dc.Attach(pNMCD->hdc); CRect r; GetClientRect(r); r.DeflateRect(8, 4, 10, 6); CopyRect(&pNMCD->rc, &r); CPen shadow(PS_SOLID, 1, GetSysColor(COLOR_3DSHADOW)); CPen light(PS_SOLID, 1, GetSysColor(COLOR_3DHILIGHT)); CPen* old = dc.SelectObject(&light); dc.MoveTo(pNMCD->rc.right, pNMCD->rc.top); dc.LineTo(pNMCD->rc.right, pNMCD->rc.bottom); dc.LineTo(pNMCD->rc.left, pNMCD->rc.bottom); dc.SelectObject(&shadow); dc.LineTo(pNMCD->rc.right, pNMCD->rc.top); dc.SelectObject(old); dc.Detach(); lr = CDRF_SKIPDEFAULT; } else if (!s.fDisableXPToolbars && pNMCD->dwItemSpec == TBCD_THUMB) { CDC dc; dc.Attach(pNMCD->hdc); pNMCD->rc.bottom--; CRect r(pNMCD->rc); r.DeflateRect(0, 0, 1, 0); COLORREF shadow = GetSysColor(COLOR_3DSHADOW); COLORREF light = GetSysColor(COLOR_3DHILIGHT); dc.Draw3dRect(&r, light, 0); r.DeflateRect(0, 0, 1, 1); dc.Draw3dRect(&r, light, shadow); r.DeflateRect(1, 1, 1, 1); dc.FillSolidRect(&r, GetSysColor(COLOR_BTNFACE)); dc.SetPixel(r.left + 7, r.top - 1, GetSysColor(COLOR_BTNFACE)); dc.Detach(); lr = CDRF_SKIPDEFAULT; } if (!s.fDisableXPToolbars) { iDisableXPToolbars = 0; } break; default: break; } } pNMCD->uItemState &= ~CDIS_FOCUS; *pResult = lr; } void CVolumeCtrl::OnLButtonDown(UINT nFlags, CPoint point) { CRect r; GetChannelRect(&r); if (r.left >= r.right) { return; } int start, stop; GetRange(start, stop); r.left += 3; r.right -= 4; if (point.x < r.left) { SetPos(start); } else if (point.x >= r.right) { SetPos(stop); } else if (start < stop) { int w = r.right - r.left - 4; SetPosInternal(start + ((stop - start) * (point.x - r.left) + (w / 2)) / w); } CSliderCtrl::OnLButtonDown(nFlags, point); } void CVolumeCtrl::OnSetFocus(CWnd* pOldWnd) { CSliderCtrl::OnSetFocus(pOldWnd); AfxGetMainWnd()->SetFocus(); } void CVolumeCtrl::HScroll(UINT nSBCode, UINT nPos) { int nVolMin, nVolMax; GetRange(nVolMin, nVolMax); if ((UINT)nVolMin <= nSBCode && nSBCode <= (UINT)nVolMax) { CRect r; GetClientRect(&r); InvalidateRect(&r); UpdateWindow(); AfxGetAppSettings().nVolume = GetPos(); CFrameWnd* pFrame = GetParentFrame(); if (pFrame && pFrame != GetParent()) { pFrame->PostMessage(WM_HSCROLL, MAKEWPARAM((short)nPos, nSBCode), (LPARAM)m_hWnd); } } } BOOL CVolumeCtrl::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { ::SetCursor(AfxGetApp()->LoadStandardCursor(IDC_HAND)); return TRUE; } BOOL CVolumeCtrl::OnToolTipNotify(UINT id, NMHDR* pNMHDR, LRESULT* pResult) { TOOLTIPTEXT *pTTT = reinterpret_cast<LPTOOLTIPTEXT>(pNMHDR); CString str; str.AppendFormat(_T("%d%%"), GetPos()); if (AfxGetAppSettings().fMute) { // TODO: remove i CString no_sound_str = ResStr(ID_VOLUME_MUTE_DISABLED); int i = no_sound_str.Find('\n'); if (i > 0) { no_sound_str = no_sound_str.Left(i); } str.AppendFormat(_T(" [%ws]"), no_sound_str); } _tcscpy_s(pTTT->szText, str); pTTT->hinst = NULL; *pResult = 0; return TRUE; }
25.842893
125
0.639583
chinajeffery
7ae00b38be1a91a34dc3e9154730c798086f9ab3
4,895
cpp
C++
src/mapleall/maple_be/src/cg/aarch64/aarch64_optimize_common.cpp
openmaple/MapleCompiler
1648e63144766563f1ec44a25e0b618415648627
[ "MulanPSL-1.0" ]
5
2019-09-02T04:44:52.000Z
2021-11-08T12:23:51.000Z
src/mapleall/maple_be/src/cg/aarch64/aarch64_optimize_common.cpp
openmaple/MapleCompiler
1648e63144766563f1ec44a25e0b618415648627
[ "MulanPSL-1.0" ]
2
2020-07-21T01:22:01.000Z
2021-12-06T08:07:16.000Z
src/mapleall/maple_be/src/cg/aarch64/aarch64_optimize_common.cpp
openmaple/MapleCompiler
1648e63144766563f1ec44a25e0b618415648627
[ "MulanPSL-1.0" ]
4
2019-09-02T04:46:52.000Z
2020-09-10T11:30:03.000Z
/* * Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "aarch64_optimize_common.h" #include "aarch64_isa.h" #include "aarch64_cgfunc.h" #include "cgbb.h" namespace maplebe { void AArch64InsnVisitor::ModifyJumpTarget(Operand &targetOperand, BB &bb) { if (bb.GetKind() == BB::kBBIgoto) { bool modified = false; for (Insn *insn = bb.GetLastInsn(); insn != nullptr; insn = insn->GetPrev()) { if (insn->GetMachineOpcode() == MOP_adrp_label) { LabelIdx labIdx = static_cast<LabelOperand&>(targetOperand).GetLabelIndex(); ImmOperand &immOpnd = static_cast<AArch64CGFunc *>(GetCGFunc())->CreateImmOperand(labIdx, k8BitSize, false); insn->SetOperand(1, immOpnd); modified = true; } } CHECK_FATAL(modified, "ModifyJumpTarget: Could not change jump target"); return; } else if (bb.GetKind() == BB::kBBGoto) { for (Insn *insn = bb.GetLastInsn(); insn != nullptr; insn = insn->GetPrev()) { if (insn->GetMachineOpcode() == MOP_adrp_label) { maple::LabelIdx labidx = static_cast<LabelOperand&>(targetOperand).GetLabelIndex(); LabelOperand &label = static_cast<AArch64CGFunc *>(GetCGFunc())->GetOrCreateLabelOperand(labidx); insn->SetOperand(1, label); break; } } // fallthru below to patch the branch insn } bb.GetLastInsn()->SetOperand(bb.GetLastInsn()->GetJumpTargetIdx(), targetOperand); } void AArch64InsnVisitor::ModifyJumpTarget(maple::LabelIdx targetLabel, BB &bb) { ModifyJumpTarget(static_cast<AArch64CGFunc*>(GetCGFunc())->GetOrCreateLabelOperand(targetLabel), bb); } void AArch64InsnVisitor::ModifyJumpTarget(BB &newTarget, BB &bb) { ModifyJumpTarget(newTarget.GetLastInsn()->GetOperand( static_cast<int32>(newTarget.GetLastInsn()->GetJumpTargetIdx())), bb); } Insn *AArch64InsnVisitor::CloneInsn(Insn &originalInsn) { MemPool *memPool = const_cast<MemPool*>(CG::GetCurCGFunc()->GetMemoryPool()); if (originalInsn.IsTargetInsn()) { if (!originalInsn.IsVectorOp()) { return memPool->Clone<AArch64Insn>(*static_cast<AArch64Insn*>(&originalInsn)); } else { AArch64VectorInsn *insn = memPool->Clone<AArch64VectorInsn>(*static_cast<AArch64VectorInsn*>(&originalInsn)); insn->SetRegSpecList(static_cast<AArch64VectorInsn&>(originalInsn).GetRegSpecList()); return insn; } } else if (originalInsn.IsCfiInsn()) { return memPool->Clone<cfi::CfiInsn>(*static_cast<cfi::CfiInsn*>(&originalInsn)); } else if (originalInsn.IsDbgInsn()) { return memPool->Clone<mpldbg::DbgInsn>(*static_cast<mpldbg::DbgInsn*>(&originalInsn)); } CHECK_FATAL(false, "Cannot clone"); return nullptr; } /* * Precondition: The given insn is a jump instruction. * Get the jump target label from the given instruction. * Note: MOP_xbr is a branching instruction, but the target is unknown at compile time, * because a register instead of label. So we don't take it as a branching instruction. */ LabelIdx AArch64InsnVisitor::GetJumpLabel(const Insn &insn) const { int operandIdx = static_cast<int>(insn.GetJumpTargetIdx()); if (insn.GetOperand(operandIdx).IsLabelOpnd()) { return static_cast<LabelOperand&>(insn.GetOperand(operandIdx)).GetLabelIndex(); } ASSERT(false, "Operand is not label"); return 0; } bool AArch64InsnVisitor::IsCompareInsn(const Insn &insn) const { switch (insn.GetMachineOpcode()) { case MOP_wcmpri: case MOP_wcmprr: case MOP_xcmpri: case MOP_xcmprr: case MOP_hcmperi: case MOP_hcmperr: case MOP_scmperi: case MOP_scmperr: case MOP_dcmperi: case MOP_dcmperr: case MOP_hcmpqri: case MOP_hcmpqrr: case MOP_scmpqri: case MOP_scmpqrr: case MOP_dcmpqri: case MOP_dcmpqrr: case MOP_wcmnri: case MOP_wcmnrr: case MOP_xcmnri: case MOP_xcmnrr: return true; default: return false; } } bool AArch64InsnVisitor::IsCompareAndBranchInsn(const Insn &insn) const { switch (insn.GetMachineOpcode()) { case MOP_wcbnz: case MOP_xcbnz: case MOP_wcbz: case MOP_xcbz: return true; default: return false; } } RegOperand *AArch64InsnVisitor::CreateVregFromReg(const RegOperand &pReg) { return &static_cast<AArch64CGFunc*>(GetCGFunc())->CreateRegisterOperandOfType( pReg.GetRegisterType(), pReg.GetSize() / k8BitSize); } } /* namespace maplebe */
35.992647
116
0.707252
openmaple
7ae204501b18372062674f5087090a50acaa0b7d
8,018
cpp
C++
CRAB/journal.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
11
2020-08-04T08:37:46.000Z
2022-03-31T22:35:15.000Z
CRAB/journal.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
1
2020-12-16T16:51:52.000Z
2020-12-18T06:35:38.000Z
Unrest-iOS/journal.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
7
2020-08-04T09:34:20.000Z
2021-09-11T03:00:16.000Z
#include "stdafx.h" #include "journal.h" using namespace pyrodactyl::image; using namespace pyrodactyl::ui; //------------------------------------------------------------------------ // Purpose: Load game //------------------------------------------------------------------------ void Journal::Load(const std::string &filename) { XMLDoc conf(filename); if (conf.ready()) { rapidxml::xml_node<char> *node = conf.Doc()->first_node("objectives"); if (NodeValid(node)) { if (NodeValid("bg", node)) bg.Load(node->first_node("bg")); if (NodeValid("map", node)) bu_map.Load(node->first_node("map")); if (NodeValid("category", node)) category.Load(node->first_node("category")); if (NodeValid("quest_list", node)) ref.Load(node->first_node("quest_list")); category.UseKeyboard(true); } } } //------------------------------------------------------------------------ // Purpose: Prepare a new character's journal //------------------------------------------------------------------------ void Journal::Init(const std::string &id) { int found = false; for (auto &i : journal) if (i.id == id) { found = true; break; } if (!found) { Group g; g.id = id; for (int i = 0; i < JE_TOTAL; ++i) { g.menu[i] = ref; g.menu[i].UseKeyboard(true); g.menu[i].AssignPaths(); } journal.push_back(g); } } //------------------------------------------------------------------------ // Purpose: Select a category //------------------------------------------------------------------------ void Journal::Select(const std::string &id, const int &choice) { for (unsigned int i = 0; i < category.element.size(); ++i) category.element.at(i).State(false); category.element.at(choice).State(true); select = choice; //Always find valid journal group first for (auto &jo : journal) if (jo.id == id) { jo.menu[choice].unread = false; break; } } //------------------------------------------------------------------------ // Purpose: Draw stuff //------------------------------------------------------------------------ void Journal::Draw(const std::string &id) { bg.Draw(); category.Draw(); //Always find valid journal group first for (auto &jo : journal) if (jo.id == id) { int count = 0; for (auto i = category.element.begin(); i != category.element.end() && count < JE_TOTAL; ++i, ++count) if (jo.menu[count].unread) gImageManager.NotifyDraw(i->x + i->w, i->y); if (select >= 0 && select < JE_TOTAL) jo.menu[select].Draw(bu_map); break; } } //------------------------------------------------------------------------ // Purpose: Handle user input //------------------------------------------------------------------------ bool Journal::HandleEvents(const std::string &id, const SDL_Event &Event) { int choice = category.HandleEvents(Event); if (choice >= 0 && choice < category.element.size()) Select(id, choice); //Check if select is valid if (select >= 0 && select < JE_TOTAL) { //Always find valid journal group first for (auto &jo : journal) if (jo.id == id) return jo.menu[select].HandleEvents(bu_map, marker_title, Event); } return false; } //------------------------------------------------------------------------ // Purpose: Add an entry to journal //------------------------------------------------------------------------ void Journal::Add(const std::string &id, const std::string &Category, const std::string &Title, const std::string &Text) { //Always find valid journal group first for (auto &jo : journal) if (jo.id == id) { if (Category == JE_CUR_NAME) { jo.menu[JE_CUR].Add(Title, Text); } else if (Category == JE_DONE_NAME) { jo.menu[JE_DONE].Add(Title, Text); } else if (Category == JE_PEOPLE_NAME) { jo.menu[JE_PEOPLE].Add(Title, Text); } else if (Category == JE_LOCATION_NAME){ jo.menu[JE_LOCATION].Add(Title, Text); } else if (Category == JE_HISTORY_NAME) { jo.menu[JE_HISTORY].Add(Title, Text); } break; } } //------------------------------------------------------------------------ // Purpose: Set the marker of a quest //------------------------------------------------------------------------ void Journal::Marker(const std::string &id, const std::string &Title, const bool &val) { //Always find valid journal group first for (auto &jo : journal) if (jo.id == id) { jo.menu[JE_CUR].Marker(Title, val); break; } } //------------------------------------------------------------------------ // Purpose: Move an entry from one category to another //------------------------------------------------------------------------ void Journal::Move(const std::string &id, const std::string &Title, const bool &completed) { JournalCategory source, destination; if (completed) { source = JE_CUR; destination = JE_DONE; } else { source = JE_DONE; destination = JE_CUR; } //Always find valid journal group first for (auto &jo : journal) if (jo.id == id) { //Find the quest chain in the source menu unsigned int index = 0; for (auto i = jo.menu[source].quest.begin(); i != jo.menu[source].quest.end(); ++i, ++index) if (i->title == Title) break; if (index < jo.menu[source].quest.size()) { jo.menu[destination].Add(jo.menu[source].quest.at(index)); jo.menu[source].Erase(index); } break; } } //------------------------------------------------------------------------ // Purpose: Open a specific entry in the journal //------------------------------------------------------------------------ void Journal::Open(const std::string &id, const JournalCategory &Category, const std::string &Title) { //Always find valid journal group first for (auto &jo : journal) if (jo.id == id) { if (Category >= 0 && Category < category.element.size()) { //If category passes the valid check, select it Select(id, Category); //Perform validity check on select, just in case if (select > 0 && select < JE_TOTAL) { //Search for the title with same name for (unsigned int num = 0; num < jo.menu[select].quest.size(); ++num) if (jo.menu[select].quest[num].title == Title) { //Found it, switch to this jo.menu[select].Select(num); break; } } } break; } } //------------------------------------------------------------------------ // Purpose: Load save game stuff //------------------------------------------------------------------------ void Journal::SaveState(rapidxml::xml_document<> &doc, rapidxml::xml_node<char> *root) { for (auto &m : journal) { rapidxml::xml_node<char> *child = doc.allocate_node(rapidxml::node_element, "journal"); child->append_attribute(doc.allocate_attribute("id", m.id.c_str())); m.menu[JE_CUR].SaveState(doc, child, JE_CUR_NAME); m.menu[JE_DONE].SaveState(doc, child, JE_DONE_NAME); m.menu[JE_PEOPLE].SaveState(doc, child, JE_PEOPLE_NAME); m.menu[JE_LOCATION].SaveState(doc, child, JE_LOCATION_NAME); m.menu[JE_HISTORY].SaveState(doc, child, JE_HISTORY_NAME); root->append_node(child); } } void Journal::LoadState(rapidxml::xml_node<char> *node) { for (rapidxml::xml_node<char> *n = node->first_node("journal"); n != NULL; n = n->next_sibling("journal")) { std::string id; LoadStr(id, "id", n); Init(id); for (auto &i : journal) if (i.id == id) { i.menu[JE_CUR].LoadState(n->first_node(JE_CUR_NAME)); i.menu[JE_DONE].LoadState(n->first_node(JE_DONE_NAME)); i.menu[JE_PEOPLE].LoadState(n->first_node(JE_PEOPLE_NAME)); i.menu[JE_LOCATION].LoadState(n->first_node(JE_LOCATION_NAME)); i.menu[JE_HISTORY].LoadState(n->first_node(JE_HISTORY_NAME)); } } } //------------------------------------------------------------------------ // Purpose: Adjust UI elements //------------------------------------------------------------------------ void Journal::SetUI() { bg.SetUI(); category.SetUI(); ref.SetUI(); for (auto &m : journal) for (auto i = 0; i < JE_TOTAL; ++i) m.menu[i].SetUI(); }
28.432624
120
0.514343
arvindrajayadav
7ae81b78415046d120da9add591a41dd5c23c326
463
hpp
C++
src/renderpass.hpp
nicokoch/vkBasalt
39cec21d26e096f0dd4d0c3d446f82e20841d365
[ "Zlib" ]
null
null
null
src/renderpass.hpp
nicokoch/vkBasalt
39cec21d26e096f0dd4d0c3d446f82e20841d365
[ "Zlib" ]
null
null
null
src/renderpass.hpp
nicokoch/vkBasalt
39cec21d26e096f0dd4d0c3d446f82e20841d365
[ "Zlib" ]
null
null
null
#ifndef RENDERPASS_HPP_INCLUDED #define RENDERPASS_HPP_INCLUDED #include <vector> #include <fstream> #include <string> #include <iostream> #include <vector> #include "vulkan/vulkan.h" #include "vulkan/vk_layer.h" #include "vulkan/vk_layer_dispatch_table.h" namespace vkBasalt { void createRenderPass(const VkDevice& device, const VkLayerDispatchTable& dispatchTable, const VkFormat& format, VkRenderPass& renderPass); } #endif // RENDERPASS_HPP_INCLUDED
22.047619
143
0.794816
nicokoch
7aeacb01491a4f23aa39b4ba127bef6c872744eb
14,682
hh
C++
net.ssa/xrLC/OpenMesh/Core/Mesh/Kernels/Common/AttribKernelT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
xrLC/OpenMesh/Core/Mesh/Kernels/Common/AttribKernelT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
xrLC/OpenMesh/Core/Mesh/Kernels/Common/AttribKernelT.hh
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2003 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * * * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*===========================================================================*/ #ifndef OPENMESH_ATTRIBKERNEL_HH #define OPENMESH_ATTRIBKERNEL_HH //== INCLUDES ================================================================= #include <OpenMesh/Core/Attributes/Attributes.hh> #include <OpenMesh/Core/Mesh/Kernels/Common/BaseKernel.hh> #include <OpenMesh/Core/Utils/GenProg.hh> #include <OpenMesh/Core/Utils/vector_traits.hh> #include <vector> //== NAMESPACES =============================================================== namespace OpenMesh { //== CLASS DEFINITION ========================================================= /// This class adds the standard properties to the mesh type. /// /// The attribute kernel adds all standard properties to the kernel. Therefore /// the functions/types defined here provide a subset of the kernel /// interface as described in Concepts::KernelT. /// /// \see Concepts::KernelT template <class MeshItems> class AttribKernelT : public BaseKernel { public: //---------------------------------------------------------------- item types typedef typename MeshItems::Vertex Vertex; typedef typename MeshItems::Halfedge Halfedge; typedef typename MeshItems::Edge Edge; typedef typename MeshItems::Face Face; typedef typename MeshItems::Point Point; typedef typename MeshItems::Normal Normal; typedef typename MeshItems::Color Color; typedef typename MeshItems::TexCoord TexCoord; typedef typename MeshItems::Scalar Scalar; typedef Attributes::StatusInfo StatusInfo; enum Attribs { VAttribs = MeshItems::VAttribs, HAttribs = MeshItems::HAttribs, EAttribs = MeshItems::EAttribs, FAttribs = MeshItems::FAttribs, }; typedef GenProg::Bool2Type<(bool)(HAttribs & Attributes::PrevHalfedge)> HasPrevHalfedge; //-------------------------------------------------- constructor / destructor AttribKernelT() : refcount_vnormals_(0), refcount_vcolors_(0), refcount_vtexcoords_(0), refcount_vstatus_(0), refcount_hstatus_(0), refcount_estatus_(0), refcount_fnormals_(0), refcount_fcolors_(0), refcount_fstatus_(0) { add_property( points_, "v:points" ); if (VAttribs & Attributes::Normal) request_vertex_normals(); if (VAttribs & Attributes::Color) request_vertex_colors(); if (VAttribs & Attributes::TexCoord) request_vertex_texcoords(); if (VAttribs & Attributes::Status) request_vertex_status(); if (HAttribs & Attributes::Status) request_halfedge_status(); if (EAttribs & Attributes::Status) request_edge_status(); if (FAttribs & Attributes::Normal) request_face_normals(); if (FAttribs & Attributes::Color) request_face_colors(); if (FAttribs & Attributes::Status) request_face_status(); } ~AttribKernelT() { // should remove properties, but this will be done in // BaseKernel's destructor anyway... } // -------------------------------------------------------- copy & assignment AttribKernelT(const AttribKernelT& _rhs) : BaseKernel(_rhs) { operator=(_rhs); } AttribKernelT& operator=(const AttribKernelT& _rhs) { // remove old properties remove_property(points_); remove_property(vertex_normals_); remove_property(vertex_colors_); remove_property(vertex_texcoords_); remove_property(vertex_status_); remove_property(halfedge_status_); remove_property(edge_status_); remove_property(face_normals_); remove_property(face_colors_); remove_property(face_status_); // parent deep-copies properties BaseKernel::operator=(_rhs); // copy property handles points_ = _rhs.points_; vertex_normals_ = _rhs.vertex_normals_; vertex_colors_ = _rhs.vertex_colors_; vertex_texcoords_ = _rhs.vertex_texcoords_; vertex_status_ = _rhs.vertex_status_; halfedge_status_ = _rhs.halfedge_status_; edge_status_ = _rhs.edge_status_; face_normals_ = _rhs.face_normals_; face_colors_ = _rhs.face_colors_; face_status_ = _rhs.face_status_; // copy ref-counts refcount_vnormals_ = _rhs.refcount_vnormals_; refcount_vcolors_ = _rhs.refcount_vcolors_; refcount_vtexcoords_ = _rhs.refcount_vtexcoords_; refcount_vstatus_ = _rhs.refcount_vstatus_; refcount_hstatus_ = _rhs.refcount_hstatus_; refcount_estatus_ = _rhs.refcount_estatus_; refcount_fnormals_ = _rhs.refcount_fnormals_; refcount_fcolors_ = _rhs.refcount_fcolors_; refcount_fstatus_ = _rhs.refcount_fstatus_; return *this; } //-------------------------------------------------------------------- points const Point* points() const { return property(points_).data(); } const Point& point(VertexHandle _vh) const { return property(points_, _vh); } Point& point(VertexHandle _vh) { return property(points_, _vh); } void set_point(VertexHandle _vh, const Point& _p) { property(points_, _vh) = _p; } //------------------------------------------------------------ vertex normals const Normal* vertex_normals() const { return property(vertex_normals_).data(); } const Normal& normal(VertexHandle _vh) const { return property(vertex_normals_, _vh); } void set_normal(VertexHandle _vh, const Normal& _n) { property(vertex_normals_, _vh) = _n; } //------------------------------------------------------------- vertex colors const Color* vertex_colors() const { return property(vertex_colors_).data(); } const Color& color(VertexHandle _vh) const { return property(vertex_colors_, _vh); } void set_color(VertexHandle _vh, const Color& _c) { property(vertex_colors_, _vh) = _c; } //---------------------------------------------------------- vertex texcoords const TexCoord* texcoords() const { return property(vertex_texcoords_).data(); } const TexCoord& texcoord(VertexHandle _vh) const { return property(vertex_texcoords_, _vh); } void set_texcoord(VertexHandle _vh, const TexCoord& _t) { property(vertex_texcoords_, _vh) = _t; } //------------------------------------------------------------ vertex status const StatusInfo& status(VertexHandle _vh) const { return property(vertex_status_, _vh); } StatusInfo& status(VertexHandle _vh) { return property(vertex_status_, _vh); } //----------------------------------------------------------- halfedge status const StatusInfo& status(HalfedgeHandle _hh) const { return property(halfedge_status_, _hh); } StatusInfo& status(HalfedgeHandle _hh) { return property(halfedge_status_, _hh); } //--------------------------------------------------------------- edge status const StatusInfo& status(EdgeHandle _eh) const { return property(edge_status_, _eh); } StatusInfo& status(EdgeHandle _eh) { return property(edge_status_, _eh); } //--------------------------------------------------------------- face status const StatusInfo& status(FaceHandle _fh) const { return property(face_status_, _fh); } StatusInfo& status(FaceHandle _fh) { return property(face_status_, _fh); } //-------------------------------------------------------------- face normals const Normal& normal(FaceHandle _fh) const { return property(face_normals_, _fh); } void set_normal(FaceHandle _fh, const Normal& _n) { property(face_normals_, _fh) = _n; } //--------------------------------------------------------------- face colors const Color& color(FaceHandle _fh) const { return property(face_colors_, _fh); } void set_color(FaceHandle _fh, const Color& _c) { property(face_colors_, _fh) = _c; } //------------------------------------------------ request / alloc properties void request_vertex_normals() { if (!refcount_vnormals_++) add_property( vertex_normals_, "v:normals" ); } void request_vertex_colors() { if (!refcount_vcolors_++) add_property( vertex_colors_, "v:colors" ); } void request_vertex_texcoords() { if (!refcount_vtexcoords_++) add_property( vertex_texcoords_, "v:texcoords" ); } void request_vertex_status() { if (!refcount_vstatus_++) add_property( vertex_status_, "v:status" ); } void request_halfedge_status() { if (!refcount_hstatus_++) add_property( halfedge_status_, "h:status" ); } void request_edge_status() { if (!refcount_estatus_++) add_property( edge_status_, "e:status" ); } void request_face_normals() { if (!refcount_fnormals_++) add_property( face_normals_, "f:normals" ); } void request_face_colors() { if (!refcount_fcolors_++) add_property( face_colors_, "f:colors" ); } void request_face_status() { if (!refcount_fstatus_++) add_property( face_status_, "f:status" ); } //------------------------------------------------- release / free properties void release_vertex_normals() { if ((refcount_vnormals_ > 0) && (! --refcount_vnormals_)) remove_property(vertex_normals_); } void release_vertex_colors() { if ((refcount_vcolors_ > 0) && (! --refcount_vcolors_)) remove_property(vertex_colors_); } void release_vertex_texcoords() { if ((refcount_vtexcoords_ > 0) && (! --refcount_vtexcoords_)) remove_property(vertex_texcoords_); } void release_vertex_status() { if ((refcount_vstatus_ > 0) && (! --refcount_vstatus_)) remove_property(vertex_status_); } void release_halfedge_status() { if ((refcount_hstatus_ > 0) && (! --refcount_hstatus_)) remove_property(halfedge_status_); } void release_edge_status() { if ((refcount_estatus_ > 0) && (! --refcount_estatus_)) remove_property(edge_status_); } void release_face_normals() { if ((refcount_fnormals_ > 0) && (! --refcount_fnormals_)) remove_property(face_normals_); } void release_face_colors() { if ((refcount_fcolors_ > 0) && (! --refcount_fcolors_)) remove_property(face_colors_); } void release_face_status() { if ((refcount_fstatus_ > 0) && (! --refcount_fstatus_)) remove_property(face_status_); } //---------------------------------------------- dynamic check for properties bool has_vertex_normals() const { return vertex_normals_.is_valid(); } bool has_vertex_colors() const { return vertex_colors_.is_valid(); } bool has_vertex_texcoords() const { return vertex_texcoords_.is_valid(); } bool has_vertex_status() const { return vertex_status_.is_valid(); } bool has_halfedge_status() const { return halfedge_status_.is_valid(); } bool has_edge_status() const { return edge_status_.is_valid(); } bool has_face_normals() const { return face_normals_.is_valid(); } bool has_face_colors() const { return face_colors_.is_valid(); } bool has_face_status() const { return face_status_.is_valid(); } static bool has_prev_halfedge() { return (HAttribs & Attributes::PrevHalfedge); } protected: VPropHandleT<Point> points_; VPropHandleT<Normal> vertex_normals_; VPropHandleT<Color> vertex_colors_; VPropHandleT<TexCoord> vertex_texcoords_; VPropHandleT<StatusInfo> vertex_status_; HPropHandleT<StatusInfo> halfedge_status_; EPropHandleT<StatusInfo> edge_status_; FPropHandleT<Normal> face_normals_; FPropHandleT<Color> face_colors_; FPropHandleT<StatusInfo> face_status_; unsigned int refcount_vnormals_; unsigned int refcount_vcolors_; unsigned int refcount_vtexcoords_; unsigned int refcount_vstatus_; unsigned int refcount_hstatus_; unsigned int refcount_estatus_; unsigned int refcount_fnormals_; unsigned int refcount_fcolors_; unsigned int refcount_fstatus_; }; //============================================================================= } // namespace OpenMesh //============================================================================= #endif // OPENMESH_ATTRIBKERNEL_HH defined //=============================================================================
31.040169
80
0.551424
ixray-team
7aec20a3863be1448d380a37dd1ff7381a4ef18e
1,141
cpp
C++
test/0005_specifers.pp.cpp
WCIofQMandRA/global-variable
62e6b3f6e2f714f6e0de06027b2d48716635d109
[ "FSFAP" ]
4
2021-02-03T03:28:21.000Z
2021-12-08T05:39:53.000Z
test/0005_specifers.pp.cpp
WCIofQMandRA/global-variable
62e6b3f6e2f714f6e0de06027b2d48716635d109
[ "FSFAP" ]
null
null
null
test/0005_specifers.pp.cpp
WCIofQMandRA/global-variable
62e6b3f6e2f714f6e0de06027b2d48716635d109
[ "FSFAP" ]
null
null
null
//Author: 张子辰 //This file is in public domain. #include <fstream> #include <string> #include <vector> #include <algorithm> #include <random> using namespace std; int main() { vector<string> spec={"extern","static","const","volatile","thread_local"}; mt19937_64 rand64; rand64.seed(random_device()()); ofstream test("0005.pp.cpp",ios_base::binary),ans("0005.pp.ans",ios_base::binary); test<<R"(//This file is generated by 0005_specifers.pp.gen.cpp. #define ____SGV_SHOW_PP_RESULT #include <global_variable.hpp> ____SGV_PP_CHECK_BEGIN)"<<endl; for(uint32_t i=0;i<32;++i) { vector<string> s; ans<<"____SGV_GV"; for(int j=0;j<5;++j) { if(i&1<<j) { s.emplace_back(spec[j]); ans<<'1'; } else ans<<'0'; } shuffle(s.begin(),s.end(),rand64); test<<"global_variable("; if(s.size()) { test<<s[0]; for(auto j=s.begin()+1;j!=s.end();++j) test<<(rand64()%2?" ":"\t")<<*j; test<<","; } if(rand64()%2) { test<<"int,a)\n"; ans<<"_ARG2(int,a)\n"; } else { test<<"int,a,1)\n"; ans<<"_ARG3(int,a,1)\n"; } } test<<"____SGV_PP_CHECK_END"<<endl; test.close(); ans.close(); }
20.017544
83
0.606486
WCIofQMandRA
7aeeb54238745c41d5f0c5d81c5ee58d49ab7969
2,386
cc
C++
packages/mccomponents/tests/libmccomponents/kernels/sample/diffraction/test_SingleCrystalDiffractionKernel.cc
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
5
2017-01-16T03:59:47.000Z
2020-06-23T02:54:19.000Z
packages/mccomponents/tests/libmccomponents/kernels/sample/diffraction/test_SingleCrystalDiffractionKernel.cc
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
293
2015-10-29T17:45:52.000Z
2022-01-07T16:31:09.000Z
packages/mccomponents/tests/libmccomponents/kernels/sample/diffraction/test_SingleCrystalDiffractionKernel.cc
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
1
2019-05-25T00:53:31.000Z
2019-05-25T00:53:31.000Z
// -*- C++ -*- // // Jiao Lin <jiao.lin@gmail.com> // #include <iostream> #include <cassert> #include <algorithm> #include "mccomponents/math/random.h" #include "mccomponents/kernels/sample/diffraction/SingleCrystalDiffractionKernel.h" #ifdef DEBUG #include "journal/debug.h" #endif void test1() { using namespace mccomponents::kernels; using namespace std; using namespace mccomponents::math; using namespace mcni::neutron_units_conversion; using mcni::PI; typedef SingleCrystalDiffractionKernel::K_t K_t; typedef SingleCrystalDiffractionKernel::R_t R_t; typedef SingleCrystalDiffractionKernel::hkllist_t hkllist_t; typedef SingleCrystalDiffractionKernel::hkl_t hkl_t; typedef SingleCrystalDiffractionKernel::float_t float_t; typedef std::pair<int, hkl_t> p_i_hkl_t; // std::cout << "test_SingleCrystalDiffractionKernel: Running test1" << std::endl; // lattice R_t a(3.0, 0., 0.), b(0., 3.0, 0.), c(0., 0., 3.0); SingleCrystalDiffractionKernel::lattice_t lattice(a, b, c); // hkl list sorted vector<p_i_hkl_t> vp; for (int h=-5; h<6; h++) for (int k=-5; k<6; k++) for (int l=-5; l<6; l++) { if (h==0 && k==0 && l==0) continue; hkl_t hkl = {h,k,l, 1.}; int r2 = h*h+k*k+l*l; vp.push_back(make_pair(r2, hkl)); } sort(vp.begin(), vp.end()); hkllist_t hkllist; for (int i=0; i<vp.size(); i++) hkllist.push_back(vp[i].second); float_t mosaic=5./60/180*PI, delta_d_d=1e-4, absorption_cross_section=10.; SingleCrystalDiffractionKernel kernel(lattice, hkllist, mosaic, delta_d_d, absorption_cross_section); mcni::Neutron::Event ev; typedef mcni::Vector3<double> V_t; K_t ki = lattice.rc*3; V_t vi = ki*k2v; for (int i=0; i<100; i++) { // double vx=5.0*random(-1,1), vy=5.0*random(-1,1), vz=random(1000.0, 3000.0); //cout << "vx, vy, vz before scattering: " << vx <<" "<< vy << " "<< vz << endl; ev.state.velocity = vi; std::cout << "incident neutron " << ev << std::endl; kernel.scatter(ev); std::cout << "scattered neutron " << ev << std::endl; std::cout << std::endl; } std::cout << "test_SingleCrystalDiffractionKernel: Done" << std::endl; } int main() { #ifdef DEBUG //journal::debug_t("HomogeneousNeutronScatterer").activate(); journal::debug_t("SingleCrystalDiffractionKernel").activate(); #endif test1(); return 0; } // End of file
30.202532
103
0.660101
mcvine
7aeeff2f924b6bb37decd3dab1920be1b084cf55
401
hpp
C++
include/amy/detail/mariadb_types.hpp
finito/amy
58d97d443a0dd3165da42e02b1608a52b874afa0
[ "MIT" ]
null
null
null
include/amy/detail/mariadb_types.hpp
finito/amy
58d97d443a0dd3165da42e02b1608a52b874afa0
[ "MIT" ]
null
null
null
include/amy/detail/mariadb_types.hpp
finito/amy
58d97d443a0dd3165da42e02b1608a52b874afa0
[ "MIT" ]
null
null
null
#ifndef __AMY_DETAIL_MARIADB_TYPES_HPP__ #define __AMY_DETAIL_MARIADB_TYPES_HPP__ #include <amy/detail/mysql_types.hpp> namespace amy { namespace detail { const int progress_callback = MYSQL_PROGRESS_CALLBACK; const int nonblock = MYSQL_OPT_NONBLOCK; } // namespace detail } // namespace amy #endif // __AMY_DETAIL_MARIADB_TYPES_HPP__ // vim:ft=cpp sw=4 ts=4 tw=80 et
22.277778
63
0.745636
finito
7af045997ffc90272d7bb2c725cd29db3b211da8
760
cpp
C++
qt_course/examples/01_trivial/05_string/main.cpp
matus-chochlik/various
2a9f5eddd964213f7d1e1ce8328e2e0b2a8e998b
[ "MIT" ]
1
2020-10-25T12:28:50.000Z
2020-10-25T12:28:50.000Z
qt_course/examples/01_trivial/05_string/main.cpp
matus-chochlik/various
2a9f5eddd964213f7d1e1ce8328e2e0b2a8e998b
[ "MIT" ]
null
null
null
qt_course/examples/01_trivial/05_string/main.cpp
matus-chochlik/various
2a9f5eddd964213f7d1e1ce8328e2e0b2a8e998b
[ "MIT" ]
null
null
null
#include <QString> #include <QDebug> int main(void) { QString str("ABCDEFGHIJKL"); qDebug() << str; qDebug() << str.size(); qDebug() << str.capacity(); qDebug() << str.contains("XYZ"); qDebug() << str.contains("DEF"); qDebug() << str.indexOf("DEF"); qDebug() << str.indexOf("DEF", 4); qDebug() << str.startsWith("ABC"); qDebug() << str.endsWith("IJK"); qDebug() << str.left(3); qDebug() << str.mid(5, 3); qDebug() << str.right(3); str.chop(9); for(int i=0, n=str.length(); i<n; ++i) { qDebug() << str[i]; } str.append('X'); foreach(QChar c, str) { qDebug() << c; } QString format("Iteration %1 of %2 - %3 %"); for(int i=0, n=10; i<=n; ++i) { qDebug() << format.arg(i, 2).arg(n, 2).arg(100*float(i)/n, 3); } return 0; }
17.674419
64
0.551316
matus-chochlik
7af2b34683dc4d05a3b0c63fa95999d929d276ac
863
cpp
C++
src/apps/debuganalyzer/gui/AbstractGeneralPage.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/apps/debuganalyzer/gui/AbstractGeneralPage.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/apps/debuganalyzer/gui/AbstractGeneralPage.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de. * Distributed under the terms of the MIT License. */ #include "AbstractGeneralPage.h" #include <GridLayoutBuilder.h> #include <GroupLayoutBuilder.h> AbstractGeneralPage::AbstractGeneralPage() : BGroupView(B_VERTICAL), fDataView(NULL) { SetName("General"); GroupLayout()->SetInsets(10, 10, 10, 10); BGroupLayoutBuilder(this) .Add(fDataView = new BGridView(10, 5)) .AddGlue() ; } AbstractGeneralPage::~AbstractGeneralPage() { } /*! Throws std::bad_alloc. */ TextDataView* AbstractGeneralPage::AddDataView(const char* label, const char* text) { BGridLayout* layout = fDataView->GridLayout(); int32 row = layout->CountRows(); layout->AddView(new LabelView(label), 0, row); TextDataView* dataView = new TextDataView(text); layout->AddView(dataView, 1, row); return dataView; }
18.361702
69
0.725377
Kirishikesan
7af358287abdc714a16480a634a1d12e692301c1
1,657
cpp
C++
products/BellHybrid/apps/application-bell-settings/models/alarm_settings/AlarmSettingsModel.cpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
1
2021-11-11T22:56:43.000Z
2021-11-11T22:56:43.000Z
products/BellHybrid/apps/application-bell-settings/models/alarm_settings/AlarmSettingsModel.cpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
null
null
null
products/BellHybrid/apps/application-bell-settings/models/alarm_settings/AlarmSettingsModel.cpp
bitigchi/MuditaOS
425d23e454e09fd6ae274b00f8d19c57a577aa94
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include <models/alarm_settings/AlarmSettingsModel.hpp> #include <apps-common/ApplicationCommon.hpp> #include <db/SystemSettings.hpp> namespace app::bell_settings { void AlarmToneModel::setValue(UTF8 value) { settings.setValue(bell::settings::Alarm::tone, value, settings::SettingsScope::Global); } UTF8 AlarmToneModel::getValue() const { return settings.getValue(bell::settings::Alarm::tone, settings::SettingsScope::Global); } void AlarmVolumeModel::setValue(std::uint8_t value) { const auto valStr = std::to_string(value); audioModel.setVolume(value, AbstractAudioModel::PlaybackType::Alarm, {}); } std::uint8_t AlarmVolumeModel::getValue() const { return defaultValue; } void AlarmVolumeModel::restoreDefault() { setValue(defaultValue); } AlarmVolumeModel::AlarmVolumeModel(AbstractAudioModel &audioModel) : audioModel{audioModel} { defaultValue = audioModel.getVolume(AbstractAudioModel::PlaybackType::Alarm).value_or(0); } void AlarmLightOnOffModel::setValue(bool value) { const auto valStr = std::to_string(value); settings.setValue(bell::settings::Alarm::lightActive, valStr, settings::SettingsScope::Global); } bool AlarmLightOnOffModel::getValue() const { const auto str = settings.getValue(bell::settings::Alarm::lightActive, settings::SettingsScope::Global); return std::stoi(str); } } // namespace app::bell_settings
31.865385
112
0.694025
bitigchi
7af3e09b74f907712fbd78a40a5af788bf75162b
31,478
hpp
C++
include/sdsl/csa_alphabet_strategy.hpp
wolfee001/sdsl-lite
3061a0b64f75f070bb8f4a1f91e570fcfc7ebe75
[ "BSD-3-Clause" ]
54
2017-03-23T23:10:40.000Z
2022-03-22T14:25:11.000Z
include/sdsl/csa_alphabet_strategy.hpp
wolfee001/sdsl-lite
3061a0b64f75f070bb8f4a1f91e570fcfc7ebe75
[ "BSD-3-Clause" ]
65
2017-05-09T05:28:43.000Z
2021-12-16T13:02:25.000Z
include/sdsl/csa_alphabet_strategy.hpp
wolfee001/sdsl-lite
3061a0b64f75f070bb8f4a1f91e570fcfc7ebe75
[ "BSD-3-Clause" ]
23
2017-03-23T23:11:44.000Z
2022-02-20T22:36:33.000Z
// Copyright (c) 2016, the SDSL Project Authors. All rights reserved. // Please see the AUTHORS file for details. Use of this source code is governed // by a BSD license that can be found in the LICENSE file. /*!\file csa_alphabet_strategy.hpp * \brief csa_alphabet_strategy.hpp includes different strategy classes for representing an alphabet of a CSA. * \author Simon Gog */ #ifndef INCLUDED_CSA_ALPHABET_STRATEGY #define INCLUDED_CSA_ALPHABET_STRATEGY // TODO: Strategy with 1-to-1 mapping and C_array type as template parameter // This can be also used for a integer based CSA. /* A alphabet strategy provides the following features: * * Member `sigma` which contains the size (=number of unique symbols) of the alphabet. * * Container `char2comp` which maps a symbol to a number [0..sigma-1]. The alphabetic * order is preserved. * * Container `comp2char` which is the inverse mapping of char2comp. * * Container `C` contains the cumulative counts of occurrences. C[i] is the cumulative * count of occurrences of symbols `comp2char[0]` to `comp2char[i-1]` in the text. * C is of size `sigma+1`. * * Typedefs for the four above members: * * char2comp_type * * comp2char_type * * C_type * * sigma_type * * Constructor. Takes a int_vector_buffer<8> for byte-alphabets * and int_vector_buffer<0> for integer-alphabets. * * \par Note * sigma_type has to be large enough to represent the alphabet size 2*sigma, * since there is code which will perform a binary search on array `C`. */ #include <string> #include <sdsl/config.hpp> #include <sdsl/int_vector.hpp> #include <sdsl/rank_support.hpp> #include <sdsl/sd_vector.hpp> #include <sdsl/sdsl_concepts.hpp> #include <sdsl/select_support.hpp> namespace sdsl { // forward declarations class byte_alphabet; template <class bit_vector_type = bit_vector, class rank_support_type = rank_support_scan<>, class select_support_type = select_support_scan<>, class C_array_type = int_vector<>> class succinct_byte_alphabet; template <class bit_vector_type = sd_vector<>, class rank_support_type = typename bit_vector_type::rank_1_type, class select_support_type = typename bit_vector_type::select_1_type, class C_array_type = int_vector<>> class int_alphabet; template <uint8_t int_width> constexpr const char * key_text() { return conf::KEY_TEXT_INT; } template <uint8_t int_width> constexpr const char * key_bwt() { return conf::KEY_BWT_INT; } template <> inline constexpr const char * key_text<8>() { return conf::KEY_TEXT; } template <> inline constexpr const char * key_bwt<8>() { return conf::KEY_BWT; } template <class t_alphabet_strategy> struct alphabet_trait { typedef byte_alphabet type; }; template <> struct alphabet_trait<int_alphabet_tag> { typedef int_alphabet<> type; }; // see // http://stackoverflow.com/questions/13514587/c-check-for-nested-typedef-of-a-template-parameter-to-get-its-scalar-base-type // for the next three functions template <class t_wt, class t_enable = void> struct wt_alphabet_trait { typedef t_enable type; }; template <class t_wt> struct wt_alphabet_trait<t_wt, typename enable_if_type<typename t_wt::alphabet_category>::type> { using type = typename alphabet_trait<typename t_wt::alphabet_category>::type; }; //! A simple space greedy representation for byte alphabets. /*! * \par Space consumption: * At least: 2.5 kB * Details: char2comp + comp2char take 2*256 + 2*8 bytes * m_C takes 257*8 bytes * m_sigma takes 2 bytes */ class byte_alphabet { public: typedef int_vector<>::size_type size_type; typedef int_vector<8> char2comp_type; typedef int_vector<8> comp2char_type; typedef int_vector<64> C_type; typedef uint16_t sigma_type; typedef uint8_t char_type; typedef uint8_t comp_char_type; typedef std::string string_type; enum { int_width = 8 }; typedef byte_alphabet_tag alphabet_category; const char2comp_type & char2comp; const comp2char_type & comp2char; const C_type & C; const sigma_type & sigma; private: char2comp_type m_char2comp; // Mapping from a character into the compact alphabet. comp2char_type m_comp2char; // Inverse mapping of m_char2comp. C_type m_C; // Cumulative counts for the compact alphabet [0..sigma]. sigma_type m_sigma; // Effective size of the alphabet. public: //! Default constructor byte_alphabet() : char2comp(m_char2comp) , comp2char(m_comp2char) , C(m_C) , sigma(m_sigma) , m_sigma(0) {} //! Construct from a byte-stream /*! * \param text_buf Byte stream. * \param len Length of the byte stream. */ byte_alphabet(int_vector_buffer<8> & text_buf, int_vector_size_type len) : char2comp(m_char2comp) , comp2char(m_comp2char) , C(m_C) , sigma(m_sigma) { m_sigma = 0; if (0 == len or 0 == text_buf.size()) return; assert(len <= text_buf.size()); // initialize vectors m_C = int_vector<64>(257, 0); m_char2comp = int_vector<8>(256, 0); m_comp2char = int_vector<8>(256, 0); // count occurrences of each symbol for (size_type i = 0; i < len; ++i) { ++m_C[text_buf[i]]; } assert(1 == m_C[0]); // null-byte should occur exactly once m_sigma = 0; for (int i = 0; i < 256; ++i) if (m_C[i]) { m_char2comp[i] = m_sigma; m_comp2char[sigma] = i; m_C[m_sigma] = m_C[i]; ++m_sigma; } m_comp2char.resize(m_sigma); m_C.resize(m_sigma + 1); for (int i = (int)m_sigma; i > 0; --i) m_C[i] = m_C[i - 1]; m_C[0] = 0; for (int i = 1; i <= (int)m_sigma; ++i) m_C[i] += m_C[i - 1]; assert(C[sigma] == len); } byte_alphabet(const byte_alphabet & bas) : char2comp(m_char2comp) , comp2char(m_comp2char) , C(m_C) , sigma(m_sigma) , m_char2comp(bas.m_char2comp) , m_comp2char(bas.m_comp2char) , m_C(bas.m_C) , m_sigma(bas.m_sigma) {} byte_alphabet(byte_alphabet && bas) : char2comp(m_char2comp) , comp2char(m_comp2char) , C(m_C) , sigma(m_sigma) , m_char2comp(std::move(bas.m_char2comp)) , m_comp2char(std::move(bas.m_comp2char)) , m_C(std::move(bas.m_C)) , m_sigma(bas.m_sigma) {} byte_alphabet & operator=(const byte_alphabet & bas) { if (this != &bas) { byte_alphabet tmp(bas); *this = std::move(tmp); } return *this; } byte_alphabet & operator=(byte_alphabet && bas) { if (this != &bas) { m_char2comp = std::move(bas.m_char2comp); m_comp2char = std::move(bas.m_comp2char); m_C = std::move(bas.m_C); m_sigma = std::move(bas.m_sigma); } return *this; } size_type serialize(std::ostream & out, structure_tree_node * v, std::string name = "") const { structure_tree_node * child = structure_tree::add_child(v, name, util::class_name(*this)); size_type written_bytes = 0; written_bytes += m_char2comp.serialize(out, child, "m_char2comp"); written_bytes += m_comp2char.serialize(out, child, "m_comp2char"); written_bytes += m_C.serialize(out, child, "m_C"); written_bytes += write_member(m_sigma, out, child, "m_sigma"); structure_tree::add_size(child, written_bytes); return written_bytes; } void load(std::istream & in) { m_char2comp.load(in); m_comp2char.load(in); m_C.load(in); read_member(m_sigma, in); } //! Equality operator. bool operator==(byte_alphabet const & other) const noexcept { return (m_char2comp == other.m_char2comp) && (m_comp2char == other.m_comp2char) && (m_C == other.m_C) && (m_sigma == other.m_sigma); } //! Inequality operator. bool operator!=(byte_alphabet const & other) const noexcept { return !(*this == other); } template <typename archive_t> void CEREAL_SAVE_FUNCTION_NAME(archive_t & ar) const { ar(CEREAL_NVP(m_char2comp)); ar(CEREAL_NVP(m_comp2char)); ar(CEREAL_NVP(m_C)); ar(CEREAL_NVP(m_sigma)); } template <typename archive_t> void CEREAL_LOAD_FUNCTION_NAME(archive_t & ar) { ar(CEREAL_NVP(m_char2comp)); ar(CEREAL_NVP(m_comp2char)); ar(CEREAL_NVP(m_C)); ar(CEREAL_NVP(m_sigma)); } }; //! A space-efficient representation for byte alphabets. /*! * The mapping `char2comp` and its inverse `comp2char` is realized internally * by a bitvector of size 256 bits and a rank and a select structure. The rank * structure is used to calculate `char2comp`; the select structure is used to * calculate `comp2char`. Array `C` is represented by a bit-compressed * `int_vector` and `sigma` by a uint16_t. * The types to represent `char2comp`, `comp2char`, and `C` can be specified * by template parameters. */ template <class bit_vector_type, class rank_support_type, class select_support_type, class C_array_type> class succinct_byte_alphabet { public: class char2comp_wrapper; class comp2char_wrapper; friend class char2comp_wrapper; friend class comp2char_wrapper; typedef int_vector<>::size_type size_type; typedef char2comp_wrapper char2comp_type; typedef comp2char_wrapper comp2char_type; typedef C_array_type C_type; typedef uint16_t sigma_type; typedef uint8_t char_type; typedef uint8_t comp_char_type; typedef std::string string_type; typedef byte_alphabet_tag alphabet_category; enum { int_width = 8 }; //! Helper class for the char2comp mapping class char2comp_wrapper { private: const succinct_byte_alphabet * m_strat; public: char2comp_wrapper(const succinct_byte_alphabet * strat) : m_strat(strat) {} comp_char_type operator[](char_type c) const { if (c >= m_strat->m_char.size() or !m_strat->m_char[c]) return (comp_char_type)0; return (comp_char_type)m_strat->m_char_rank((size_type)c); } }; //! Helper class for the comp2char mapping class comp2char_wrapper { private: const succinct_byte_alphabet * m_strat; public: comp2char_wrapper(const succinct_byte_alphabet * strat) : m_strat(strat) {} char_type operator[](comp_char_type c) const { return (char_type)m_strat->m_char_select(((size_type)c) + 1); } }; const char2comp_type char2comp; const comp2char_type comp2char; const C_type & C; const sigma_type & sigma; private: bit_vector_type m_char; // `m_char[i]` indicates if character with code i is present or not rank_support_type m_char_rank; // rank data structure for `m_char` to answer char2comp select_support_type m_char_select; // select data structure for `m_char` to answer comp2char C_type m_C; // cumulative counts for the compact alphabet [0..sigma] sigma_type m_sigma; // effective size of the alphabet public: //! Default constructor succinct_byte_alphabet() : char2comp(this) , comp2char(this) , C(m_C) , sigma(m_sigma) , m_sigma(0) {} //! Construct from a byte-stream /*! * \param text_buf Byte stream. * \param len Length of the byte stream. */ succinct_byte_alphabet(int_vector_buffer<8> & text_buf, int_vector_size_type len) : char2comp(this) , comp2char(this) , C(m_C) , sigma(m_sigma) { m_sigma = 0; if (0 == len or 0 == text_buf.size()) return; assert(len <= text_buf.size()); // initialize vectors int_vector<64> D(257, 0); bit_vector tmp_char(256, 0); // count occurrences of each symbol for (size_type i = 0; i < len; ++i) { ++D[text_buf[i]]; } assert(1 == D[0]); // null-byte should occur exactly once m_sigma = 0; for (int i = 0; i < 256; ++i) if (D[i]) { tmp_char[i] = 1; // mark occurring character D[m_sigma] = D[i]; // compactify m_C ++m_sigma; } // resize to sigma+1, since CSAs also need the sum of all elements m_C = C_type(m_sigma + 1, 0, bits::hi(len) + 1); for (int i = (int)m_sigma; i > 0; --i) m_C[i] = D[i - 1]; m_C[0] = 0; for (int i = 1; i <= (int)m_sigma; ++i) m_C[i] = m_C[i] + m_C[i - 1]; assert(m_C[sigma] == len); m_char = tmp_char; util::init_support(m_char_rank, &m_char); util::init_support(m_char_select, &m_char); } //! Copy constructor succinct_byte_alphabet(const succinct_byte_alphabet & strat) : char2comp(this) , comp2char(this) , C(m_C) , sigma(m_sigma) , m_char(strat.m_char) , m_char_rank(strat.m_char_rank) , m_char_select(strat.m_char_select) , m_C(strat.m_C) , m_sigma(strat.m_sigma) { m_char_rank.set_vector(&m_char); m_char_select.set_vector(&m_char); } //! Move constructor succinct_byte_alphabet(succinct_byte_alphabet && strat) : char2comp(this) , comp2char(this) , C(m_C) , sigma(m_sigma) , m_char(std::move(strat.m_char)) , m_char_rank(std::move(strat.m_char_rank)) , m_char_select(std::move(strat.m_char_select)) , m_C(std::move(strat.m_C)) , m_sigma(std::move(strat.m_sigma)) { m_char_rank.set_vector(&m_char); m_char_select.set_vector(&m_char); } succinct_byte_alphabet & operator=(const succinct_byte_alphabet & strat) { if (this != &strat) { succinct_byte_alphabet tmp(strat); *this = std::move(tmp); } return *this; } succinct_byte_alphabet & operator=(succinct_byte_alphabet && strat) { if (this != &strat) { m_char = std::move(strat.m_char); m_char_rank = std::move(strat.m_char_rank); m_char_rank.set_vector(&m_char); m_char_select = std::move(strat.m_char_select); m_char_select.set_vector(&m_char); m_C = std::move(strat.m_C); m_sigma = std::move(strat.m_sigma); } return *this; } //! Serialize method size_type serialize(std::ostream & out, structure_tree_node * v = nullptr, std::string name = "") const { structure_tree_node * child = structure_tree::add_child(v, name, util::class_name(*this)); size_type written_bytes = 0; written_bytes += m_char.serialize(out, child, "m_char"); written_bytes += m_char_rank.serialize(out, child, "m_char_rank"); written_bytes += m_char_select.serialize(out, child, "m_char_select"); written_bytes += m_C.serialize(out, child, "m_C"); written_bytes += write_member(m_sigma, out, child, "m_sigma"); structure_tree::add_size(child, written_bytes); return written_bytes; } //! Load method void load(std::istream & in) { m_char.load(in); m_char_rank.load(in); m_char_rank.set_vector(&m_char); m_char_select.load(in); m_char_select.set_vector(&m_char); m_C.load(in); read_member(m_sigma, in); } //! Equality operator. bool operator==(succinct_byte_alphabet const & other) const noexcept { return (m_char == other.m_char) && (m_char_rank == other.m_char_rank) && (m_char_select == other.m_char_select) && (m_C == other.m_C) && (m_sigma == other.m_sigma); } //! Inequality operator. bool operator!=(succinct_byte_alphabet const & other) const noexcept { return !(*this == other); } template <typename archive_t> void CEREAL_SAVE_FUNCTION_NAME(archive_t & ar) const { ar(CEREAL_NVP(m_char)); ar(CEREAL_NVP(m_char_rank)); ar(CEREAL_NVP(m_char_select)); ar(CEREAL_NVP(m_C)); ar(CEREAL_NVP(m_sigma)); } template <typename archive_t> void CEREAL_LOAD_FUNCTION_NAME(archive_t & ar) { ar(CEREAL_NVP(m_char)); ar(CEREAL_NVP(m_char_rank)); m_char_rank.set_vector(&m_char); ar(CEREAL_NVP(m_char_select)); m_char_select.set_vector(&m_char); ar(CEREAL_NVP(m_C)); ar(CEREAL_NVP(m_sigma)); } }; template <typename bit_vector_type, typename size_type> void init_char_bitvector(bit_vector_type & char_bv, const std::map<size_type, size_type> & D) { // note: the alphabet has at least size 1, so the following is safe: auto largest_symbol = (--D.end())->first; bit_vector tmp_char(largest_symbol + 1, 0); for (const auto & x : D) { tmp_char[x.first] = 1; } char_bv = tmp_char; } template <typename t_hi_bit_vector, typename t_select_1, typename t_select_0, typename size_type> void init_char_bitvector(sd_vector<t_hi_bit_vector, t_select_1, t_select_0> & char_bv, const std::map<size_type, size_type> & D) { auto largest_symbol = (--D.end())->first; sd_vector_builder builder(largest_symbol + 1, D.size()); for (const auto & x : D) { builder.set(x.first); } char_bv = std::move(sd_vector<t_hi_bit_vector, t_select_1, t_select_0>(builder)); } /*!\brief Provides an alphabet mapping that implements an identity map (i.e. each character is mapped to its rank). * \details This mapping is faster for FM indices and should always be used for ranges containing all characters of the * underlying alphabet type. Indices based on a text not containing all characters of its alphabet type will * have a much higher memory footprint using this alphabet mapping. */ class plain_byte_alphabet { public: //! Helper class for the char2comp and comp2char mapping. class mapping_wrapper; typedef int_vector<>::size_type size_type; typedef mapping_wrapper char2comp_type; typedef mapping_wrapper comp2char_type; typedef int_vector<64> C_type; typedef uint16_t sigma_type; typedef uint8_t char_type; typedef uint8_t comp_char_type; typedef std::string string_type; typedef byte_alphabet_tag alphabet_category; enum { int_width = 8 }; //! Helper class for the char2comp and comp2char mapping. class mapping_wrapper { public: //! Default constructor. mapping_wrapper() = default; //! Random access operator. constexpr char_type operator[](char_type const c) const noexcept { return c; } }; const char2comp_type char2comp{}; const comp2char_type comp2char{}; const C_type & C; const sigma_type & sigma; private: C_type m_C; // Cumulative counts for the compact alphabet [0..sigma]. sigma_type m_sigma; // Effective size of the alphabet. public: //! Default constructor. plain_byte_alphabet() : C(m_C) , sigma(m_sigma) , m_sigma(0) {} /*! Construct from a byte-stream. * \param text_buf Byte stream. * \param len Length of the byte stream. */ plain_byte_alphabet(int_vector_buffer<8> & text_buf, int_vector_size_type len) : C(m_C) , sigma(m_sigma) { m_sigma = 0; if (0 == len || 0 == text_buf.size()) return; assert(len <= text_buf.size()); // initialize vectors m_C = int_vector<64>(257, 0); // count occurrences of each symbol for (size_type i = 0; i < len; ++i) ++m_C[text_buf[i]]; assert(1 == m_C[0]); // null-byte should occur exactly once m_sigma = 255; for (int i = 0; i < 256; ++i) { if (m_C[i]) { m_sigma = i + 1; // m_C[m_sigma] = m_C[i]; // ++m_sigma; } } // m_C.resize(m_sigma + 1); for (int i = (int)256; i > 0; --i) m_C[i] = m_C[i - 1]; m_C[0] = 0; for (int i = 1; i <= (int)256; ++i) m_C[i] += m_C[i - 1]; assert(C[sigma] == len); } //! Copy constructor. plain_byte_alphabet(plain_byte_alphabet const & strat) : C(m_C) , sigma(m_sigma) , m_C(strat.m_C) , m_sigma(strat.m_sigma) {} //! Move constructor. plain_byte_alphabet(plain_byte_alphabet && strat) noexcept : C(m_C) , sigma(m_sigma) , m_C(std::move(strat.m_C)) , m_sigma(strat.m_sigma) {} //! Copy assignment. plain_byte_alphabet & operator=(plain_byte_alphabet const & strat) { if (this != &strat) { plain_byte_alphabet tmp(strat); *this = std::move(tmp); } return *this; } //! Move assignment. plain_byte_alphabet & operator=(plain_byte_alphabet && strat) noexcept { if (this != &strat) { m_C = std::move(strat.m_C); m_sigma = strat.m_sigma; } return *this; } //!\cond size_type serialize(std::ostream & out, structure_tree_node * v, std::string const & name = "") const { structure_tree_node * child = structure_tree::add_child(v, name, util::class_name(*this)); size_type written_bytes = 0; written_bytes += m_C.serialize(out, child, "m_C"); written_bytes += write_member(m_sigma, out, child, "m_sigma"); structure_tree::add_size(child, written_bytes); return written_bytes; } void load(std::istream & in) { m_C.load(in); read_member(m_sigma, in); } template <typename archive_t> void CEREAL_SAVE_FUNCTION_NAME(archive_t & ar) const { ar(CEREAL_NVP(m_C)); ar(CEREAL_NVP(m_sigma)); } template <typename archive_t> void CEREAL_LOAD_FUNCTION_NAME(archive_t & ar) { ar(CEREAL_NVP(m_C)); ar(CEREAL_NVP(m_sigma)); } bool operator==(plain_byte_alphabet const & other) const noexcept { return (m_C == other.m_C) && (m_sigma == other.m_sigma); } bool operator!=(plain_byte_alphabet const & other) const noexcept { return !(*this == other); } //!\endcond }; //! A space-efficient representation for byte alphabets. /*! * The mapping `char2comp` and its inverse `comp2char` is realized internally * by a bitvector of size sigma bits and a rank and a select structure, if the * alphabet contains not all symbols in the range [0..sigma-1]. If it contains * all symbols, i.e. the alphabet is continuous, then we map the symbols * directly and no extra space is used. * * The types to represent `char2comp`, `comp2char`, and `C` can be specified * by template parameters. */ template <class bit_vector_type, class rank_support_type, class select_support_type, class C_array_type> class int_alphabet { public: class char2comp_wrapper; class comp2char_wrapper; friend class char2comp_wrapper; friend class comp2char_wrapper; typedef int_vector<>::size_type size_type; typedef char2comp_wrapper char2comp_type; typedef comp2char_wrapper comp2char_type; typedef C_array_type C_type; typedef uint64_t sigma_type; typedef uint64_t char_type; typedef uint64_t comp_char_type; typedef std::vector<char_type> string_type; typedef int_alphabet_tag alphabet_category; enum { int_width = 0 }; //! Helper class for the char2comp mapping class char2comp_wrapper { private: const int_alphabet * m_strat; public: char2comp_wrapper(const int_alphabet * strat) : m_strat(strat) {} comp_char_type operator[](char_type c) const { if (m_strat->m_char.size() > 0) { // if alphabet is not continuous if (c >= m_strat->m_char.size() or !m_strat->m_char[c]) return (comp_char_type)0; return (comp_char_type)m_strat->m_char_rank((size_type)c); } else { // direct map if it is continuous if (c >= m_strat->m_sigma) return 0; return (comp_char_type)c; } return 0; } }; //! Helper class for the comp2char mapping class comp2char_wrapper { private: const int_alphabet * m_strat; public: comp2char_wrapper(const int_alphabet * strat) : m_strat(strat) {} char_type operator[](comp_char_type c) const { if (m_strat->m_char.size() > 0) { // if alphabet is not continuous return (char_type)m_strat->m_char_select(((size_type)c) + 1); } else { // direct map if it is continuous return (char_type)c; } } }; const char2comp_type char2comp; const comp2char_type comp2char; const C_type & C; const sigma_type & sigma; private: bit_vector_type m_char; // `m_char[i]` indicates if character with code i is present or not rank_support_type m_char_rank; // rank data structure for `m_char` to answer char2comp select_support_type m_char_select; // select data structure for `m_char` to answer comp2char C_type m_C; // cumulative counts for the compact alphabet [0..sigma] sigma_type m_sigma; // effective size of the alphabet //! Check if the alphabet is continuous. bool is_continuous_alphabet(std::map<size_type, size_type> & D) { if (D.size() == 0) { // an empty alphabet is continuous return true; } else { // max key + 1 == size of map return ((--D.end())->first + 1) == D.size(); } } public: //! Default constructor int_alphabet() : char2comp(this) , comp2char(this) , C(m_C) , sigma(m_sigma) , m_sigma(0) {} //! Construct from a byte-stream /*! * \param text_buf Byte stream. * \param len Length of the byte stream. */ int_alphabet(int_vector_buffer<0> & text_buf, int_vector_size_type len) : char2comp(this) , comp2char(this) , C(m_C) , sigma(m_sigma) { m_sigma = 0; if (0 == len or 0 == text_buf.size()) return; assert(len <= text_buf.size()); // initialize vectors std::map<size_type, size_type> D; // count occurrences of each symbol for (size_type i = 0; i < len; ++i) { D[text_buf[i]]++; } m_sigma = D.size(); if (is_continuous_alphabet(D)) { // do not initialize m_char, m_char_rank and m_char_select since we can map directly } else { init_char_bitvector(m_char, D); } assert(D.find(0) != D.end() and 1 == D[0]); // null-byte should occur exactly once // resize to sigma+1, since CSAs also need the sum of all elements m_C = C_type(m_sigma + 1, 0, bits::hi(len) + 1); size_type sum = 0, idx = 0; for (std::map<size_type, size_type>::const_iterator it = D.begin(), end = D.end(); it != end; ++it) { m_C[idx++] = sum; sum += it->second; } m_C[idx] = sum; // insert sum of all elements } //! Copy constructor int_alphabet(const int_alphabet & strat) : char2comp(this) , comp2char(this) , C(m_C) , sigma(m_sigma) , m_char(strat.m_char) , m_char_rank(strat.m_char_rank) , m_char_select(strat.m_char_select) , m_C(strat.m_C) , m_sigma(strat.m_sigma) { m_char_rank.set_vector(&m_char); m_char_select.set_vector(&m_char); } //! Copy constructor int_alphabet(int_alphabet && strat) : char2comp(this) , comp2char(this) , C(m_C) , sigma(m_sigma) , m_char(std::move(strat.m_char)) , m_char_rank(std::move(strat.m_char_rank)) , m_char_select(std::move(strat.m_char_select)) , m_C(std::move(strat.m_C)) , m_sigma(std::move(strat.m_sigma)) { m_char_rank.set_vector(&m_char); m_char_select.set_vector(&m_char); } int_alphabet & operator=(const int_alphabet & strat) { if (this != &strat) { int_alphabet tmp(strat); *this = std::move(tmp); } return *this; } int_alphabet & operator=(int_alphabet && strat) { if (this != &strat) { m_char = std::move(strat.m_char); m_char_rank = std::move(strat.m_char_rank); m_char_rank.set_vector(&m_char); m_char_select = std::move(strat.m_char_select); m_char_select.set_vector(&m_char); m_C = std::move(strat.m_C); m_sigma = std::move(strat.m_sigma); } return *this; } //! Serialize method size_type serialize(std::ostream & out, structure_tree_node * v = nullptr, std::string name = "") const { structure_tree_node * child = structure_tree::add_child(v, name, util::class_name(*this)); size_type written_bytes = 0; written_bytes += m_char.serialize(out, child, "m_char"); written_bytes += m_char_rank.serialize(out, child, "m_char_rank"); written_bytes += m_char_select.serialize(out, child, "m_char_select"); written_bytes += m_C.serialize(out, child, "m_C"); written_bytes += write_member(m_sigma, out, child, "m_sigma"); structure_tree::add_size(child, written_bytes); return written_bytes; } //! Load method void load(std::istream & in) { m_char.load(in); m_char_rank.load(in); m_char_rank.set_vector(&m_char); m_char_select.load(in); m_char_select.set_vector(&m_char); m_C.load(in); read_member(m_sigma, in); } //! Equality operator. bool operator==(int_alphabet const & other) const noexcept { return (m_char == other.m_char) && (m_char_rank == other.m_char_rank) && (m_char_select == other.m_char_select) && (m_C == other.m_C) && (m_sigma == other.m_sigma); } //! Inequality operator. bool operator!=(int_alphabet const & other) const noexcept { return !(*this == other); } template <typename archive_t> void CEREAL_SAVE_FUNCTION_NAME(archive_t & ar) const { ar(CEREAL_NVP(m_char)); ar(CEREAL_NVP(m_char_rank)); ar(CEREAL_NVP(m_char_select)); ar(CEREAL_NVP(m_C)); ar(CEREAL_NVP(m_sigma)); } template <typename archive_t> void CEREAL_LOAD_FUNCTION_NAME(archive_t & ar) { ar(CEREAL_NVP(m_char)); ar(CEREAL_NVP(m_char_rank)); m_char_rank.set_vector(&m_char); ar(CEREAL_NVP(m_char_select)); m_char_select.set_vector(&m_char); ar(CEREAL_NVP(m_C)); ar(CEREAL_NVP(m_sigma)); } }; } // end namespace sdsl #endif
31.446553
125
0.612904
wolfee001
7af466f9820e60fd0c05d3e29504c9955c7c9f57
1,947
hpp
C++
gui/include/windows/PokerWin.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
1
2021-12-10T06:27:47.000Z
2021-12-10T06:27:47.000Z
gui/include/windows/PokerWin.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
null
null
null
gui/include/windows/PokerWin.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "IWindow.hpp" #include "Mapping.hpp" #include "LayoutConfig.hpp" #include "GuiPokerInterface.hpp" #include "PlaceBetWin.hpp" #include "WhoWonWin.hpp" #include "NextRoundWin.hpp" namespace gui { /** \ingroup gui * @class PokerWin * @author Julian Massing (julimassing@gmail.com) * @brief Window showing information concerning the poker game. * * @version 1.0 * @date 2020-11-21 * * @copyright Copyright (c) 2020 * */ class PokerWin: public IWindow { private: Mapping mapping_; LayoutConfig& layout_settings_; std::shared_ptr<GuiPokerInterface>& poker_if_; PlaceBetWin place_bet_win_; WhoWonWin who_won_win_; NextRoundWin next_round_win_; bool show_place_bet_win_; bool show_who_won_win_; bool show_next_round_win_; public: void draw() override; PokerWin( const std::string& name, bool& show, LayoutConfig& layout_settings, std::shared_ptr<GuiPokerInterface>& poker_if, const int& flag = 0 ): IWindow(name, show, flag), mapping_{}, layout_settings_{layout_settings}, poker_if_(poker_if), show_place_bet_win_(false), show_who_won_win_(false), show_next_round_win_(false), place_bet_win_("", this->show_place_bet_win_, poker_if, ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysAutoResize), who_won_win_("", this->show_who_won_win_, poker_if, ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysAutoResize), next_round_win_("", this->show_next_round_win_, poker_if, ImGuiWindowFlags_::ImGuiWindowFlags_AlwaysAutoResize) {}; virtual ~PokerWin() {}; // Using default copy and move constructors. PokerWin(const PokerWin& other) = default; PokerWin& operator=(const PokerWin& other) = default; PokerWin(PokerWin&& other) noexcept = default; PokerWin& operator=(PokerWin&& other) noexcept = default; }; } // namespace gui
27.422535
118
0.70416
JMassing
7af8fa1daa6a3d5140a6a87d1af39c6c630dd43b
18,881
cpp
C++
Server/Source/Worker.cpp
ppenguin/audiogridder
4b83a99618f35d7421cd3be36454fe397a5babd3
[ "MIT" ]
null
null
null
Server/Source/Worker.cpp
ppenguin/audiogridder
4b83a99618f35d7421cd3be36454fe397a5babd3
[ "MIT" ]
null
null
null
Server/Source/Worker.cpp
ppenguin/audiogridder
4b83a99618f35d7421cd3be36454fe397a5babd3
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Andreas Pohl * Licensed under MIT (https://github.com/apohl79/audiogridder/blob/master/COPYING) * * Author: Andreas Pohl */ #include "Worker.hpp" #include "KeyAndMouse.hpp" #include "Defaults.hpp" #include "NumberConversion.hpp" #include "App.hpp" #include "CPUInfo.hpp" #ifdef JUCE_MAC #include <sys/socket.h> #endif namespace e47 { std::atomic_uint32_t Worker::count{0}; std::atomic_uint32_t Worker::runCount{0}; Worker::Worker(StreamingSocket* clnt) : Thread("Worker"), LogTag("worker"), m_client(clnt), m_audio(std::make_shared<AudioWorker>(this)), m_screen(std::make_shared<ScreenWorker>(this)), m_msgFactory(this) { traceScope(); initAsyncFunctors(); count++; } Worker::~Worker() { traceScope(); stopAsyncFunctors(); if (nullptr != m_client && m_client->isConnected()) { m_client->close(); } waitForThreadAndLog(this, this); count--; } void Worker::run() { traceScope(); runCount++; Handshake cfg; std::unique_ptr<StreamingSocket> sock; int len; len = m_client->read(&cfg, sizeof(cfg), true); if (len > 0) { setLogTagExtra("client:" + String::toHexString(cfg.clientId)); logln(" version = " << cfg.version); logln(" clientId = " << String::toHexString(cfg.clientId)); logln(" clientPort = " << cfg.clientPort); logln(" channelsIn = " << cfg.channelsIn); logln(" channelsOut = " << cfg.channelsOut); logln(" rate = " << cfg.rate); logln(" samplesPerBlock = " << cfg.samplesPerBlock); logln(" doublePrecission = " << static_cast<int>(cfg.doublePrecission)); // start audio processing sock = std::make_unique<StreamingSocket>(); #ifdef JUCE_MAC setsockopt(sock->getRawSocketHandle(), SOL_SOCKET, SO_NOSIGPIPE, nullptr, 0); #endif if (sock->connect(m_client->getHostName(), cfg.clientPort)) { m_audio->init(std::move(sock), cfg.channelsIn, cfg.channelsOut, cfg.rate, cfg.samplesPerBlock, cfg.doublePrecission); m_audio->startThread(Thread::realtimeAudioPriority); } else { logln("failed to establish audio connection to " << m_client->getHostName() << ":" << cfg.clientPort); } // start screen capturing sock = std::make_unique<StreamingSocket>(); #ifdef JUCE_MAC setsockopt(sock->getRawSocketHandle(), SOL_SOCKET, SO_NOSIGPIPE, nullptr, 0); #endif if (sock->connect(m_client->getHostName(), cfg.clientPort)) { m_screen->init(std::move(sock)); m_screen->startThread(); } else { logln("failed to establish screen connection to " << m_client->getHostName() << ":" << cfg.clientPort); } // send list of plugins auto& pluginList = getApp()->getPluginList(); String list; for (auto& plugin : pluginList.getTypes()) { bool inputMatch = false; // exact match is fine inputMatch = (cfg.channelsIn == plugin.numInputChannels) || inputMatch; // hide plugins with no inputs if we have inputs inputMatch = (cfg.channelsIn > 0 && plugin.numInputChannels > 0) || inputMatch; // for instruments (no inputs) allow any plugin with the isInstrument flag inputMatch = (cfg.channelsIn == 0 && plugin.isInstrument) || inputMatch; if (inputMatch) { list += AGProcessor::createString(plugin) + "\n"; } } Message<PluginList> msgPL(this); PLD(msgPL).setString(list); if (!msgPL.send(m_client.get())) { logln("failed to send plugin list"); m_client->close(); signalThreadShouldExit(); } // enter message loop logln("command processor started"); while (!currentThreadShouldExit() && nullptr != m_client && m_client->isConnected() && m_audio->isThreadRunning() && m_screen->isThreadRunning()) { MessageHelper::Error e; auto msg = m_msgFactory.getNextMessage(m_client.get(), &e); if (nullptr != msg) { switch (msg->getType()) { case Quit::Type: handleMessage(Message<Any>::convert<Quit>(msg)); break; case AddPlugin::Type: handleMessage(Message<Any>::convert<AddPlugin>(msg)); break; case DelPlugin::Type: handleMessage(Message<Any>::convert<DelPlugin>(msg)); break; case EditPlugin::Type: handleMessage(Message<Any>::convert<EditPlugin>(msg)); break; case HidePlugin::Type: handleMessage(Message<Any>::convert<HidePlugin>(msg)); break; case Mouse::Type: handleMessage(Message<Any>::convert<Mouse>(msg)); break; case Key::Type: handleMessage(Message<Any>::convert<Key>(msg)); break; case GetPluginSettings::Type: handleMessage(Message<Any>::convert<GetPluginSettings>(msg)); break; case SetPluginSettings::Type: handleMessage(Message<Any>::convert<SetPluginSettings>(msg)); break; case BypassPlugin::Type: handleMessage(Message<Any>::convert<BypassPlugin>(msg)); break; case UnbypassPlugin::Type: handleMessage(Message<Any>::convert<UnbypassPlugin>(msg)); break; case ExchangePlugins::Type: handleMessage(Message<Any>::convert<ExchangePlugins>(msg)); break; case RecentsList::Type: handleMessage(Message<Any>::convert<RecentsList>(msg)); break; case Preset::Type: handleMessage(Message<Any>::convert<Preset>(msg)); break; case ParameterValue::Type: handleMessage(Message<Any>::convert<ParameterValue>(msg)); break; case GetParameterValue::Type: handleMessage(Message<Any>::convert<GetParameterValue>(msg)); break; case GetAllParameterValues::Type: handleMessage(Message<Any>::convert<GetAllParameterValues>(msg)); break; case UpdateScreenCaptureArea::Type: handleMessage(Message<Any>::convert<UpdateScreenCaptureArea>(msg)); break; case Rescan::Type: handleMessage(Message<Any>::convert<Rescan>(msg)); break; case Restart::Type: handleMessage(Message<Any>::convert<Restart>(msg)); break; case CPULoad::Type: handleMessage(Message<Any>::convert<CPULoad>(msg)); break; default: logln("unknown message type " << msg->getType()); } } else if (e.code != MessageHelper::E_TIMEOUT) { logln("failed to get next message: " << e.toString()); break; } } } else { logln("handshake error with client " << m_client->getHostName()); } shutdown(); m_audio->waitForThreadToExit(-1); m_audio.reset(); m_screen->waitForThreadToExit(-1); m_screen.reset(); logln("command processor terminated"); runCount--; } void Worker::shutdown() { traceScope(); if (m_shutdown) { return; } m_shutdown = true; if (m_shouldHideEditor) { m_screen->hideEditor(); } if (nullptr != m_audio) { m_audio->shutdown(); } if (nullptr != m_screen) { m_screen->shutdown(); } signalThreadShouldExit(); } void Worker::handleMessage(std::shared_ptr<Message<Quit>> /* msg */) { traceScope(); shutdown(); } void Worker::handleMessage(std::shared_ptr<Message<AddPlugin>> msg) { traceScope(); auto id = pPLD(msg).getString(); logln("adding plugin " << id << "..."); String err; bool success = m_audio->addPlugin(id, err); logln("..." << (success ? "ok" : "failed")); if (!success) { m_msgFactory.sendResult(m_client.get(), -1, err); return; } // send new updated latency samples back if (!m_msgFactory.sendResult(m_client.get(), m_audio->getLatencySamples())) { logln("failed to send result"); m_client->close(); return; } logln("sending presets..."); auto proc = m_audio->getProcessor(m_audio->getSize() - 1)->getPlugin(); String presets; bool first = true; for (int i = 0; i < proc->getNumPrograms(); i++) { if (first) { first = false; } else { presets << "|"; } presets << proc->getProgramName(i); } Message<Presets> msgPresets; msgPresets.payload.setString(presets); if (!msgPresets.send(m_client.get())) { logln("failed to send Presets message"); m_client->close(); return; } logln("...ok"); logln("sending parameters..."); json jparams = json::array(); for (auto& param : proc->getParameters()) { json jparam = {{"idx", param->getParameterIndex()}, {"name", param->getName(32).toStdString()}, {"defaultValue", param->getDefaultValue()}, {"currentValue", param->getValue()}, {"category", param->getCategory()}, {"label", param->getLabel().toStdString()}, {"numSteps", param->getNumSteps()}, {"isBoolean", param->isBoolean()}, {"isDiscrete", param->isDiscrete()}, {"isMeta", param->isMetaParameter()}, {"isOrientInv", param->isOrientationInverted()}, {"minValue", param->getText(0.0f, 20).toStdString()}, {"maxValue", param->getText(1.0f, 20).toStdString()}}; jparam["allValues"] = json::array(); for (auto& val : param->getAllValueStrings()) { jparam["allValues"].push_back(val.toStdString()); } if (jparam["allValues"].size() == 0 && param->isDiscrete() && param->getNumSteps() < 64) { // try filling values manually float step = 1.0f / (param->getNumSteps() - 1); for (int i = 0; i < param->getNumSteps(); i++) { auto val = param->getText(step * i, 32); if (val.isEmpty()) { break; } jparam["allValues"].push_back(val.toStdString()); } } jparams.push_back(jparam); } Message<Parameters> msgParams(this); msgParams.payload.setJson(jparams); if (!msgParams.send(m_client.get())) { logln("failed to send Parameters message"); m_client->close(); return; } logln("...ok"); logln("reading plugin settings..."); Message<PluginSettings> msgSettings(this); MessageHelper::Error e; if (!msgSettings.read(m_client.get(), &e, 10000)) { logln("failed to read PluginSettings message:" << e.toString()); m_client->close(); return; } if (*msgSettings.payload.size > 0) { MemoryBlock block; block.append(msgSettings.payload.data, as<size_t>(*msgSettings.payload.size)); proc->setStateInformation(block.getData(), static_cast<int>(block.getSize())); } logln("...ok"); m_audio->addToRecentsList(id, m_client->getHostName()); } void Worker::handleMessage(std::shared_ptr<Message<DelPlugin>> msg) { traceScope(); m_audio->delPlugin(pPLD(msg).getNumber()); // send new updated latency samples back m_msgFactory.sendResult(m_client.get(), m_audio->getLatencySamples()); } void Worker::handleMessage(std::shared_ptr<Message<EditPlugin>> msg) { traceScope(); auto proc = m_audio->getProcessor(pPLD(msg).getNumber()); if (nullptr != proc) { m_screen->showEditor(proc); m_shouldHideEditor = true; } } void Worker::handleMessage(std::shared_ptr<Message<HidePlugin>> /* msg */) { traceScope(); m_screen->hideEditor(); m_shouldHideEditor = false; } void Worker::handleMessage(std::shared_ptr<Message<Mouse>> msg) { traceScope(); auto ev = *pDATA(msg); runOnMsgThreadAsync([this, ev] { traceScope(); auto point = getApp()->localPointToGlobal(Point<float>(ev.x, ev.y)); if (ev.type == MouseEvType::WHEEL) { mouseScrollEvent(point.x, point.y, ev.deltaX, ev.deltaY, ev.isSmooth); } else { uint64_t flags = 0; if (ev.isShiftDown) { setShiftKey(flags); } if (ev.isCtrlDown) { setControlKey(flags); } if (ev.isAltDown) { setAltKey(flags); } mouseEvent(ev.type, point.x, point.y, flags); } }); } void Worker::handleMessage(std::shared_ptr<Message<Key>> msg) { traceScope(); runOnMsgThreadAsync([this, msg] { traceScope(); auto* codes = pPLD(msg).getKeyCodes(); auto num = pPLD(msg).getKeyCount(); uint16_t key = 0; uint64_t flags = 0; for (int i = 0; i < num; i++) { if (isShiftKey(codes[i])) { setShiftKey(flags); } else if (isControlKey(codes[i])) { setControlKey(flags); } else if (isAltKey(codes[i])) { setAltKey(flags); } else { key = codes[i]; } } keyEventDown(key, flags); keyEventUp(key, flags); }); } void Worker::handleMessage(std::shared_ptr<Message<GetPluginSettings>> msg) { traceScope(); auto proc = m_audio->getProcessor(pPLD(msg).getNumber()); if (nullptr != proc) { MemoryBlock block; proc->getStateInformation(block); Message<PluginSettings> ret(this); ret.payload.setData(block.begin(), static_cast<int>(block.getSize())); ret.send(m_client.get()); } } void Worker::handleMessage(std::shared_ptr<Message<SetPluginSettings>> msg) { traceScope(); auto proc = m_audio->getProcessor(pPLD(msg).getNumber()); if (nullptr != proc) { Message<PluginSettings> msgSettings(this); if (!msgSettings.read(m_client.get())) { logln("failed to read PluginSettings message"); m_client->close(); return; } if (*msgSettings.payload.size > 0) { MemoryBlock block; block.append(msgSettings.payload.data, as<size_t>(*msgSettings.payload.size)); proc->setStateInformation(block.getData(), static_cast<int>(block.getSize())); } } } void Worker::handleMessage(std::shared_ptr<Message<BypassPlugin>> msg) { traceScope(); auto proc = m_audio->getProcessor(pPLD(msg).getNumber()); if (nullptr != proc) { proc->suspendProcessing(true); } } void Worker::handleMessage(std::shared_ptr<Message<UnbypassPlugin>> msg) { traceScope(); auto proc = m_audio->getProcessor(pPLD(msg).getNumber()); if (nullptr != proc) { proc->suspendProcessing(false); } } void Worker::handleMessage(std::shared_ptr<Message<ExchangePlugins>> msg) { traceScope(); m_audio->exchangePlugins(pDATA(msg)->idxA, pDATA(msg)->idxB); } void Worker::handleMessage(std::shared_ptr<Message<RecentsList>> msg) { traceScope(); auto list = m_audio->getRecentsList(m_client->getHostName()); pPLD(msg).setString(list); msg->send(m_client.get()); } void Worker::handleMessage(std::shared_ptr<Message<Preset>> msg) { traceScope(); auto p = m_audio->getProcessor(pDATA(msg)->idx)->getPlugin(); if (nullptr != p) { p->setCurrentProgram(pDATA(msg)->preset); } } void Worker::handleMessage(std::shared_ptr<Message<ParameterValue>> msg) { traceScope(); auto p = m_audio->getProcessor(pDATA(msg)->idx)->getPlugin(); if (nullptr != p) { for (auto* param : p->getParameters()) { if (pDATA(msg)->paramIdx == param->getParameterIndex()) { param->setValue(pDATA(msg)->value); return; } } } } void Worker::handleMessage(std::shared_ptr<Message<GetParameterValue>> msg) { traceScope(); Message<ParameterValue> ret(this); DATA(ret)->idx = pDATA(msg)->idx; DATA(ret)->paramIdx = pDATA(msg)->paramIdx; DATA(ret)->value = m_audio->getParameterValue(pDATA(msg)->idx, pDATA(msg)->paramIdx); ret.send(m_client.get()); } void Worker::handleMessage(std::shared_ptr<Message<GetAllParameterValues>> msg) { traceScope(); auto p = m_audio->getProcessor(pPLD(msg).getNumber())->getPlugin(); if (nullptr != p) { for (auto* param : p->getParameters()) { Message<ParameterValue> ret(this); DATA(ret)->idx = pPLD(msg).getNumber(); DATA(ret)->paramIdx = param->getParameterIndex(); DATA(ret)->value = param->getValue(); ret.send(m_client.get()); } } } void Worker::handleMessage(std::shared_ptr<Message<UpdateScreenCaptureArea>> msg) { traceScope(); getApp()->updateScreenCaptureArea(pPLD(msg).getNumber()); } void Worker::handleMessage(std::shared_ptr<Message<Rescan>> msg) { traceScope(); bool wipe = pPLD(msg).getNumber() == 1; runOnMsgThreadAsync([this, wipe] { traceScope(); if (wipe) { getApp()->getServer().getPluginList().clear(); getApp()->getServer().saveKnownPluginList(); } getApp()->restartServer(true); }); } void Worker::handleMessage(std::shared_ptr<Message<Restart>> /*msg*/) { traceScope(); runOnMsgThreadAsync([this] { traceScope(); getApp()->prepareShutdown(App::EXIT_RESTART); }); } void Worker::handleMessage(std::shared_ptr<Message<CPULoad>> msg) { traceScope(); pPLD(msg).setFloat(CPUInfo::getUsage()); msg->send(m_client.get()); } } // namespace e47
35.827324
115
0.554949
ppenguin
bb007be11e3c8aadc5be9eb5736b21a7ec5e0359
1,021
cpp
C++
solutions/LeetCode/C++/190.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/190.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/190.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 4 ms submission class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t ret=0; for(int i=0;i<32;i++){ ret<<=1; if(n&1) ret++; n>>=1; } return ret; } }; __________________________________________________________________________________________________ sample 7728 kb submission class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t result = 0; uint32_t pos = 1; uint32_t temp; for(int i=0; i<32; ++i){ if( (n & pos) > 0 ) temp = 1; else temp = 0; result = result << 1; result = result + temp; pos = pos << 1; //cout << result << endl; } return result; } }; __________________________________________________________________________________________________
28.361111
98
0.596474
timxor
bb03e1887066a1960615a1707d8aeed136896f60
245
hpp
C++
Sources/Dynamics/py_dynamics.hpp
tvieijra/netket
ef3ff32b242f25b6a6ae0f08db1aada85775a2ea
[ "Apache-2.0" ]
10
2019-11-29T02:51:53.000Z
2021-08-14T18:52:33.000Z
Sources/Dynamics/py_dynamics.hpp
tvieijra/netket
ef3ff32b242f25b6a6ae0f08db1aada85775a2ea
[ "Apache-2.0" ]
2
2018-11-04T14:38:01.000Z
2018-11-08T16:56:10.000Z
Sources/Dynamics/py_dynamics.hpp
tvieijra/netket
ef3ff32b242f25b6a6ae0f08db1aada85775a2ea
[ "Apache-2.0" ]
6
2019-12-02T07:29:01.000Z
2021-04-04T21:55:21.000Z
#ifndef NETKET_DYNAMICS_PY_DYNAMICS_HPP #define NETKET_DYNAMICS_PY_DYNAMICS_HPP #include <pybind11/pybind11.h> namespace netket { void AddDynamicsModule(pybind11::module m); } // namespace netket #endif // NETKET_DYNAMICS_PY_DYNAMICS_HPP
18.846154
43
0.816327
tvieijra
bb058adb6b8b268f2c74b06fa0dc1e3069839fc0
704
hpp
C++
pycppad/adfun.hpp
utke1/pycppad
0713cd0fbbce5f4475934adc55a42eac56e4fbb6
[ "Unlicense" ]
15
2015-09-09T04:50:57.000Z
2022-01-18T00:54:33.000Z
pycppad/adfun.hpp
utke1/pycppad
0713cd0fbbce5f4475934adc55a42eac56e4fbb6
[ "Unlicense" ]
1
2016-11-21T03:36:05.000Z
2016-11-23T14:10:46.000Z
pycppad/adfun.hpp
utke1/pycppad
0713cd0fbbce5f4475934adc55a42eac56e4fbb6
[ "Unlicense" ]
7
2016-11-13T02:43:59.000Z
2021-01-11T16:31:04.000Z
# ifndef PYCPPAD_ADFUN_INCLUDED # define PYCPPAD_ADFUN_INCLUDED # include "environment.hpp" namespace pycppad { // ------------------------------------------------------------- // class ADFun<Base> template <class Base> class ADFun{ private: CppAD::ADFun<Base> f_; public: // python constructor call ADFun(array& x_array, array& y_array); // member functions int Domain(void); int Range(void); array Forward(int p, array& xp); int CompareChange(void); array Reverse(int p, array& w); array Jacobian(array& x); array Hessian(array& x, array& w); void optimize(void); }; typedef ADFun<double> ADFun_double; typedef ADFun<AD_double> ADFun_AD_double; } # endif
22
65
0.636364
utke1
bb079fa2509fe771a068f58806656df9f279ad0c
2,387
hpp
C++
exa/internal/exa/detail/io_task.hpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
exa/internal/exa/detail/io_task.hpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
exa/internal/exa/detail/io_task.hpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
#pragma once #include <exa/task.hpp> #include <exa/enum_flag.hpp> #include <future> #include <any> #include <tuple> namespace exa { namespace detail { class io_task { public: template <class Result, class Function, class = std::enable_if_t<!std::is_void_v<Result>>> static std::future<Result> run(Function&& callback) { static_assert(std::is_invocable_v<Function>); auto promise = std::make_shared<std::promise<Result>>(); task::push(std::bind(&io_task::run_internal, [callback, promise] { bool done = false; std::any result; try { std::tie(done, result) = callback(); if (done) { promise->set_value(std::any_cast<Result>(result)); return true; } } catch (...) { promise->set_exception(std::current_exception()); return true; } return false; })); return promise->get_future(); } template <class Result, class Function, class = std::enable_if_t<std::is_void_v<Result>>> static std::future<void> run(Function&& callback) { static_assert(std::is_invocable_v<Function>); auto promise = std::make_shared<std::promise<void>>(); task::push(std::bind(&io_task::run_internal, [callback, promise] { try { if (callback()) { promise->set_value(); return true; } } catch (...) { promise->set_exception(std::current_exception()); return true; } return false; })); return promise->get_future(); } private: static void run_internal(std::function<bool()> callback); }; } }
28.759036
102
0.408463
chronos38
bb0b6025e027ae40999759fb880597e0c98f416a
15,325
cpp
C++
D&D Wrath of Silumgar/Motor2D/ctSettings.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
3
2019-06-21T04:40:16.000Z
2020-07-07T13:09:53.000Z
D&D Wrath of Silumgar/Motor2D/ctSettings.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
56
2018-05-07T10:30:08.000Z
2018-05-15T08:27:06.000Z
D&D Wrath of Silumgar/Motor2D/ctSettings.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
3
2019-01-03T17:24:57.000Z
2019-05-04T08:49:12.000Z
#include "ctDefs.h" #include "ctLog.h" #include "ctApp.h" #include "ctInput.h" #include "ctTextures.h" #include "ctAudio.h" #include "ctRender.h" #include "ctWindow.h" #include "ctEntities.h" #include "ctSettings.h" #include "ctFadeToBlack.h" #include "ctMainMenu.h" ctSettings::ctSettings() : ctModule() { name = "settings"; } // Destructor ctSettings::~ctSettings() {} // Called before render is available bool ctSettings::Awake() { LOG("Loading Main Menu"); bool ret = true; return ret; } // Called before the first frame bool ctSettings::Start() { bool ret = true; uint music_num = NumberToPercentage(music_volume_value, max_volume); char music_volume_char[(((sizeof music_num) * CHAR_BIT) + 2) / 3 + 2]; sprintf_s(music_volume_char, "%d", music_num); uint fx_num = NumberToPercentage(fx_volume_value, max_volume); char fx_volume_char[(((sizeof fx_num) * CHAR_BIT) + 2) / 3 + 2]; sprintf_s(fx_volume_char, "%d", fx_num); background = App->gui->AddUIImage(0, 0, { 337, 479, 800, 450 }, this); labels_bg = App->gui->AddUIImage(15, -1, { 314, 1046, 160, 135 }, this); music_volume_label = App->gui->AddUILabel(35, 10, "Music Volume", { 255,255,255,255 }, 25, this); music_volume = App->gui->AddUILabel(150, 10, music_volume_char, { 255,255,255,255 }, 25, this); fx_volume_label = App->gui->AddUILabel(35, 30, "Fx Volume", { 255,255,255,255 }, 25, this); fx_volume = App->gui->AddUILabel(150, 30, fx_volume_char, { 255,255,255,255 }, 25, this); controls_label = App->gui->AddUILabel(35, 50, "Controls:", { 255,255,255,255 }, 25, this); select_button_label = App->gui->AddUILabel(55, 70, "Select ", { 255,255,255,255 }, 25, this); select_button_image = App->gui->AddUIImage(125, 70, { 1360, 224, 17, 17 }, this); back_button_label = App->gui->AddUILabel(55, 90, "Back ", { 255,255,255,255 }, 25, this); back_button_image = App->gui->AddUIImage(125, 90, { 1342, 242, 17, 17 }, this); back_label = App->gui->AddUILabel(35, 110, "Back to Menu", { 255,255,255,255 }, 25, this); arrow = App->gui->AddUIImage(-10, 0, { 1333, 272, 7, 14 }, this); music_volume_label->current_state = STATE_FOCUSED; arrow->SetParent(music_volume_label); labels.push_back(music_volume_label); labels.push_back(fx_volume_label); labels.push_back(select_button_label); labels.push_back(back_button_label); labels.push_back(back_label); if(App->main_menu->key_select == 0) select_button_image = App->gui->AddUIImage(125, 70, { 1360, 224, 17, 17 }, this); else if(App->main_menu->key_select == 1) select_button_image = App->gui->AddUIImage(125, 70, { 1342, 242, 17, 17 }, this); else if (App->main_menu->key_select == 2) select_button_image = App->gui->AddUIImage(125, 70, { 1324, 224, 17, 17 }, this); else if (App->main_menu->key_select == 3) select_button_image = App->gui->AddUIImage(125, 70, { 1342, 206, 17, 17 }, this); if (App->main_menu->key_back == 0) back_button_image = App->gui->AddUIImage(125, 90, { 1360, 224, 17, 17 }, this); else if (App->main_menu->key_back == 1) back_button_image = App->gui->AddUIImage(125, 90, { 1342, 242, 17, 17 }, this); else if (App->main_menu->key_back == 2) back_button_image = App->gui->AddUIImage(125, 90, { 1324, 224, 17, 17 }, this); else if (App->main_menu->key_back == 3) back_button_image = App->gui->AddUIImage(125, 90, { 1342, 206, 17, 17 }, this); if (!App->audio->PlayMusic(App->audio->SettingsBSO.c_str(), 1)) { LOG("Error playing music in ctMainMenu Start"); } return ret; } // Called each loop iteration bool ctSettings::PreUpdate() { return true; } // Called each loop iteration bool ctSettings::Update(float dt) { //Go down if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_DOWN || App->input->gamepad.CROSS_DOWN == GAMEPAD_STATE::PAD_BUTTON_DOWN || App->input->gamepad.JOYSTICK_DOWN == GAMEPAD_STATE::PAD_BUTTON_DOWN) { App->audio->PlayFx(App->audio->mm_movement_fx); NavigateDown(labels); } //Go up if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_DOWN || App->input->gamepad.CROSS_UP == GAMEPAD_STATE::PAD_BUTTON_DOWN || App->input->gamepad.JOYSTICK_UP == GAMEPAD_STATE::PAD_BUTTON_DOWN) { App->audio->PlayFx(App->audio->mm_movement_fx); NavigateUp(labels); } //Execute if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN || App->input->GetGamepadButton(App->main_menu->key_select) == GAMEPAD_STATE::PAD_BUTTON_DOWN) { /*App->audio->PlayFx(menu_select_fx);*/ if ((*select_button_label).current_state == STATE_NORMAL && (*back_button_label).current_state == STATE_NORMAL) { ExecuteComand(labels); } } //Change Controlls if (App->input->gamepad.A == GAMEPAD_STATE::PAD_BUTTON_DOWN) { if ((*select_button_label).current_state == STATE_FOCUSED) { App->main_menu->key_select = 0; ChangeControlImages(select_button_image); if (App->main_menu->key_select == App->main_menu->key_back) { App->main_menu->key_back = 1; ChangeControlImages(back_button_image); } } else if ((*back_button_label).current_state == STATE_FOCUSED) { App->main_menu->key_back = 0; ChangeControlImages(back_button_image); if (App->main_menu->key_select == App->main_menu->key_back) { App->main_menu->key_select = 1; ChangeControlImages(select_button_image); } } } if (App->input->gamepad.B == GAMEPAD_STATE::PAD_BUTTON_DOWN) { if ((*select_button_label).current_state == STATE_FOCUSED) { App->main_menu->key_select = 1; ChangeControlImages(select_button_image); if (App->main_menu->key_select == App->main_menu->key_back) { App->main_menu->key_back = 0; ChangeControlImages(back_button_image); } } else if ((*back_button_label).current_state == STATE_FOCUSED) { App->main_menu->key_back = 1; ChangeControlImages(back_button_image); if (App->main_menu->key_select == App->main_menu->key_back) { App->main_menu->key_select = 0; ChangeControlImages(select_button_image); } } } if (App->input->gamepad.X == GAMEPAD_STATE::PAD_BUTTON_DOWN) { if ((*select_button_label).current_state == STATE_FOCUSED) { App->main_menu->key_select = 3; ChangeControlImages(select_button_image); if (App->main_menu->key_select == App->main_menu->key_back) { App->main_menu->key_back = 1; ChangeControlImages(back_button_image); } } else if ((*back_button_label).current_state == STATE_FOCUSED) { App->main_menu->key_back = 3; ChangeControlImages(back_button_image); if (App->main_menu->key_select == App->main_menu->key_back) { App->main_menu->key_select = 0; ChangeControlImages(select_button_image); } } } if (App->input->gamepad.Y == GAMEPAD_STATE::PAD_BUTTON_DOWN) { if ((*select_button_label).current_state == STATE_FOCUSED) { App->main_menu->key_select = 2; ChangeControlImages(select_button_image); if (App->main_menu->key_select == App->main_menu->key_back) { App->main_menu->key_back = 1; ChangeControlImages(back_button_image); } } else if ((*back_button_label).current_state == STATE_FOCUSED) { App->main_menu->key_back = 2; ChangeControlImages(back_button_image); if (App->main_menu->key_select == App->main_menu->key_back) { App->main_menu->key_select = 0; ChangeControlImages(select_button_image); } } } //TurnUp volume if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input->gamepad.CROSS_RIGHT == GAMEPAD_STATE::PAD_BUTTON_REPEAT || App->input->gamepad.JOYSTICK_RIGHT == GAMEPAD_STATE::PAD_BUTTON_REPEAT) { //App->audio->PlayFx(App->audio->mm_movement_fx); TurnUp(labels); } //TurnDownVolume if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input->gamepad.CROSS_LEFT == GAMEPAD_STATE::PAD_BUTTON_REPEAT || App->input->gamepad.JOYSTICK_LEFT == GAMEPAD_STATE::PAD_BUTTON_REPEAT) { //App->audio->PlayFx(App->audio->mm_movement_fx); TurnDown(labels); } if (App->input->GetKey(SDL_SCANCODE_BACKSPACE) == KEY_DOWN /*|| App->input->gamepad.B == GAMEPAD_STATE::PAD_BUTTON_DOWN*/) { fx_volume_label->current_state = STATE_NORMAL; back_label->current_state = STATE_EXECUTED; ExecuteComand(labels); } return true; } // Called each loop iteration bool ctSettings::PostUpdate() { bool ret = true; if (quit_pressed || App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool ctSettings::CleanUp() { LOG("Freeing main_menu"); App->audio->PauseMusic(); App->gui->DeleteUIElement(*background); background = nullptr; App->gui->DeleteUIElement(*music_volume_label); music_volume_label = nullptr; App->gui->DeleteUIElement(*fx_volume_label); fx_volume_label = nullptr; App->gui->DeleteUIElement(*back_label); back_label = nullptr; App->gui->DeleteUIElement(*music_volume); music_volume = nullptr; App->gui->DeleteUIElement(*fx_volume); fx_volume = nullptr; App->gui->DeleteUIElement(*arrow); arrow = nullptr; App->gui->DeleteUIElement(*controls_label); controls_label = nullptr; App->gui->DeleteUIElement(*select_button_image); select_button_image = nullptr; App->gui->DeleteUIElement(*back_button_image); back_button_image = nullptr; App->gui->DeleteUIElement(*labels_bg); labels_bg = nullptr; for (int i = 0; i < labels.size(); i++) { App->gui->DeleteUIElement(*labels[i]); } labels.clear(); App->gui->DeleteAllUIElements(); return true; } bool ctSettings::Load(pugi::xml_node& load) { bool ret = true; return ret; } bool ctSettings::Save(pugi::xml_node& save) const { bool ret = true; return ret; } void ctSettings::OnUITrigger(UIElement* elementTriggered, UI_State ui_state) { } void ctSettings::NavigateDown(std::vector<UIElement*> &current_vector) { std::vector<UIElement*>::const_iterator it_vector = current_vector.begin(); while (it_vector != current_vector.end()) { if ((*it_vector)->current_state == STATE_FOCUSED) { if ((*it_vector) != current_vector.back()) { (*it_vector)->current_state = STATE_NORMAL; it_vector++; (*it_vector)->current_state = STATE_FOCUSED; arrow->SetParent((*it_vector)); break; } else { (*it_vector)->current_state = STATE_NORMAL; it_vector = current_vector.begin(); (*it_vector)->current_state = STATE_FOCUSED; arrow->SetParent((*it_vector)); } } it_vector++; } } void ctSettings::NavigateUp(std::vector<UIElement*> &current_vector) { std::vector<UIElement*>::const_iterator it_vector = current_vector.begin(); while (it_vector != current_vector.end()) { if ((*it_vector)->current_state == STATE_FOCUSED) { if ((*it_vector) != current_vector.front()) { (*it_vector)->current_state = STATE_NORMAL; it_vector--; (*it_vector)->current_state = STATE_FOCUSED; arrow->SetParent((*it_vector)); break; } else { (*it_vector)->current_state = STATE_NORMAL; it_vector = current_vector.end() - 1; (*it_vector)->current_state = STATE_FOCUSED; arrow->SetParent((*it_vector)); } } it_vector++; } } void ctSettings::ExecuteComand(std::vector<UIElement*> &current_vector) { for (int i = 0; i < current_vector.size(); i++) { if (current_vector.at(i)->current_state == STATE_FOCUSED) { current_vector.at(i)->current_state = STATE_EXECUTED; } } if (music_volume_label->current_state == STATE_EXECUTED) { LOG("music_volume_label pressed"); music_volume_label->current_state = STATE_FOCUSED; } if (fx_volume_label->current_state == STATE_EXECUTED) { LOG("fx_volume_label pressed"); fx_volume_label->current_state = STATE_FOCUSED; } if (back_label->current_state == STATE_EXECUTED) { LOG("back_label pressed"); App->audio->PlayFx(App->audio->mm_select_fx); if(App->fadeToBlack->FadeIsOver()) App->fadeToBlack->FadeToBlackBetweenModules(this, App->main_menu, 1.0f); } } void ctSettings::TurnUp(std::vector<UIElement*> &current_vector) { if (music_volume_label->current_state == STATE_FOCUSED) { if (music_volume_value <= 127) { music_volume_value += 1; uint music_num = NumberToPercentage(music_volume_value, max_volume); char music_volume_char[(((sizeof music_num) * CHAR_BIT) + 2) / 3 + 2]; sprintf_s(music_volume_char, "%d", music_num); App->gui->DeleteUIElement(*music_volume); music_volume = App->gui->AddUILabel(150, 10, music_volume_char, { 255,255,255,255 }, 25, this); } Mix_VolumeMusic(music_volume_value); } else if (fx_volume_label->current_state == STATE_FOCUSED) { if (fx_volume_value <= 127) { fx_volume_value += 1; uint fx_num = NumberToPercentage(fx_volume_value, max_volume); char fx_volume_char[(((sizeof fx_num) * CHAR_BIT) + 2) / 3 + 2]; sprintf_s(fx_volume_char, "%d", fx_num); App->gui->DeleteUIElement(*fx_volume); fx_volume = App->gui->AddUILabel(150, 30, fx_volume_char, { 255,255,255,255 }, 25, this); } Mix_Volume(-1, fx_volume_value); } } void ctSettings::TurnDown(std::vector<UIElement*> &current_vector) { if (music_volume_label->current_state == STATE_FOCUSED) { if (music_volume_value >= 1) { music_volume_value -= 1; uint music_num = NumberToPercentage(music_volume_value, max_volume); char music_volume_char[(((sizeof music_num) * CHAR_BIT) + 2) / 3 + 2]; sprintf_s(music_volume_char, "%d", music_num); App->gui->DeleteUIElement(*music_volume); music_volume = App->gui->AddUILabel(150, 10, music_volume_char, { 255,255,255,255 }, 25, this); } Mix_VolumeMusic(music_volume_value); } else if (fx_volume_label->current_state == STATE_FOCUSED) { if (fx_volume_value >= 1) { fx_volume_value -= 1; uint fx_num = NumberToPercentage(fx_volume_value, max_volume); char fx_volume_char[(((sizeof fx_num) * CHAR_BIT) + 2) / 3 + 2]; sprintf_s(fx_volume_char, "%d", fx_num); App->gui->DeleteUIElement(*fx_volume); fx_volume = App->gui->AddUILabel(150, 30, fx_volume_char, { 255,255,255,255 }, 25, this); } Mix_Volume(-1, fx_volume_value); } } uint ctSettings::NumberToPercentage(uint num, uint max_num) { uint percentage; percentage = (num * 100) / max_num; return percentage; } void ctSettings::ChangeControlImages(UIElement* control) { if (control == select_button_image) { if (select_button_image != nullptr) { App->gui->DeleteUIElement(*select_button_image); } if (App->main_menu->key_select == 0) { select_button_image = App->gui->AddUIImage(125, 70, { 1360, 224, 17, 17 }, this); } else if (App->main_menu->key_select == 1) { select_button_image = App->gui->AddUIImage(125, 70, { 1342, 242, 17, 17 }, this); } else if (App->main_menu->key_select == 2) { select_button_image = App->gui->AddUIImage(125, 70, { 1324, 224, 17, 17 }, this); } else if (App->main_menu->key_select == 3) { select_button_image = App->gui->AddUIImage(125, 70, { 1342, 206, 17, 17 }, this); } } else if (control == back_button_image) { if (back_button_image != nullptr) { App->gui->DeleteUIElement(*back_button_image); } if (App->main_menu->key_back == 0) { back_button_image = App->gui->AddUIImage(125, 90, { 1360, 224, 17, 17 }, this); } else if (App->main_menu->key_back == 1) { back_button_image = App->gui->AddUIImage(125, 90, { 1342, 242, 17, 17 }, this); } else if (App->main_menu->key_back == 2) { back_button_image = App->gui->AddUIImage(125, 90, { 1324, 224, 17, 17 }, this); } else if (App->main_menu->key_back == 3) { back_button_image = App->gui->AddUIImage(125, 90, { 1342, 206, 17, 17 }, this); } } }
33.904867
205
0.697292
Wilhelman
bb0b8185eea9ed69c2601096250e6c0930675b53
3,675
cpp
C++
Tools/ResourcerDoc/DocumentOptions.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
32
2016-05-22T23:09:19.000Z
2022-03-13T03:32:27.000Z
Tools/ResourcerDoc/DocumentOptions.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
2
2016-05-30T19:45:58.000Z
2018-01-24T22:29:51.000Z
Tools/ResourcerDoc/DocumentOptions.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
17
2016-05-27T11:01:42.000Z
2022-03-13T03:32:30.000Z
// DocumentOptions.cpp : implementation file // #include "stdafx.h" #include "Resource.h" #include "DocumentOptions.h" #include "DirDialog.h" #include "System/LocalizedString.h" #include <io.h> // _access ///////////////////////////////////////////////////////////////////////////// // DocumentOptions dialog DocumentOptions::DocumentOptions(CResourcerDoc *pDoc, CWnd* pParent /*=NULL*/) : CDialog(DocumentOptions::IDD, pParent), m_pDoc(pDoc) { //{{AFX_DATA_INIT(DocumentOptions) m_SourceDirectory = _T(""); m_Output = _T(""); m_MirrorServer = _T(""); m_Port = 0; m_UID = _T(""); m_PW = _T(""); m_sLocaleFile = _T(""); //}}AFX_DATA_INIT } void DocumentOptions::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(DocumentOptions) DDX_Text(pDX, IDC_EDIT1, m_SourceDirectory); DDX_Text(pDX, IDC_EDIT3, m_Output); DDX_Text(pDX, IDC_EDIT2, m_MirrorServer); DDX_Text(pDX, IDC_EDIT4, m_Port); DDX_Text(pDX, IDC_EDIT5, m_UID); DDX_Text(pDX, IDC_EDIT6, m_PW); DDX_Text(pDX, IDC_EDIT7, m_sLocaleFile); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(DocumentOptions, CDialog) //{{AFX_MSG_MAP(DocumentOptions) ON_BN_CLICKED(IDC_BUTTON1, OnBrowseSourceDirectory) ON_BN_CLICKED(IDC_BUTTON3, OnBrowseOutput) ON_BN_CLICKED(IDC_BUTTON2, OnBrowseLocaleFile) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // DocumentOptions message handlers void DocumentOptions::OnBrowseSourceDirectory() { UpdateData(TRUE); CDirDialog dialog; dialog.m_strWindowTitle = _T("Port Folder"); dialog.m_strTitle = _T("Port Folder?"); if ( dialog.DoBrowse() ) { m_SourceDirectory = dialog.m_strPath; if ( m_SourceDirectory[ m_SourceDirectory.GetLength() - 1 ] != '\\') m_SourceDirectory += "\\"; UpdateData(FALSE); } } void DocumentOptions::OnBrowseOutput() { UpdateData(TRUE); CDirDialog dialog; dialog.m_strWindowTitle = _T("Output Folder"); dialog.m_strTitle = _T("Output WOB Files?"); if ( dialog.DoBrowse() ) { m_Output = dialog.m_strPath; if ( m_Output[ m_Output.GetLength() - 1 ] != '\\') m_Output += '\\'; UpdateData(FALSE); } } BOOL DocumentOptions::OnInitDialog() { CDialog::OnInitDialog(); m_SourceDirectory = m_pDoc->m_RootDirectory; m_Output = m_pDoc->m_BrokerFolder; m_MirrorServer = m_pDoc->m_MirrorServer; m_Port = m_pDoc->m_MirrorServerPort; m_UID = m_pDoc->m_UID; m_PW = m_pDoc->m_PW; m_sLocaleFile = m_pDoc->m_sLocaleFile; UpdateData( FALSE ); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void DocumentOptions::OnOK() { UpdateData( TRUE ); if ( m_SourceDirectory.IsEmpty() || _taccess( m_SourceDirectory, 0 ) ) { MessageBox(_T("Source directory is invalid")); return; } if ( m_Output.IsEmpty() || _taccess( m_Output, 0 ) ) { MessageBox(_T("Output directory is invalid")); return; } m_pDoc->m_RootDirectory = m_SourceDirectory; m_pDoc->m_BrokerFolder = m_Output; m_pDoc->m_MirrorServer = m_MirrorServer; m_pDoc->m_MirrorServerPort = m_Port; m_pDoc->m_UID = m_UID; m_pDoc->m_PW = m_PW; m_pDoc->m_sLocaleFile = m_sLocaleFile; // load in the locale file, do not clear the existing text.. LocalizedString::locale().load( m_sLocaleFile, false ); //m_pDoc->SetModifiedFlag(); CDialog::OnOK(); } void DocumentOptions::OnBrowseLocaleFile() { UpdateData(TRUE); CFileDialog dialog(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("Locale Files (*.txt)|*.txt||")); if ( dialog.DoModal() == IDOK ) { m_sLocaleFile = dialog.GetPathName(); UpdateData( FALSE ); } }
23.113208
81
0.683265
CarysT
bb0df2c453d0fc87eca6787520d9f2f1a809d580
178
cpp
C++
src/solver/embed.cpp
ChristopherKotthoff/Aphros-with-GraphContraction
18af982a50e350a8bf6979ae5bd25b2ef4d3792a
[ "MIT" ]
252
2020-06-03T16:01:59.000Z
2022-03-30T14:06:32.000Z
src/solver/embed.cpp
ChristopherKotthoff/Aphros-with-GraphContraction
18af982a50e350a8bf6979ae5bd25b2ef4d3792a
[ "MIT" ]
4
2021-03-13T11:13:55.000Z
2022-03-31T15:11:22.000Z
src/solver/embed.cpp
ChristopherKotthoff/Aphros-with-GraphContraction
18af982a50e350a8bf6979ae5bd25b2ef4d3792a
[ "MIT" ]
27
2020-09-18T04:12:03.000Z
2022-03-30T04:22:42.000Z
// Created by Petr Karnakov on 11.02.2020 // Copyright 2020 ETH Zurich #include "embed.ipp" #define X(dim) template class Embed<MeshCartesian<double, dim>>; MULTIDIMX #undef X
19.777778
64
0.747191
ChristopherKotthoff
bb0ebdbfb40ba9c6fa7affc13b0afa31658d2b8a
1,117
cpp
C++
Online-Judges/UVa/10101_Bangla_Numbers.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
3
2021-06-15T01:19:23.000Z
2022-03-16T18:23:53.000Z
Online-Judges/UVa/10101_Bangla_Numbers.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
Online-Judges/UVa/10101_Bangla_Numbers.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int llint; #define endn '\n' void ot(llint n) { if (n <= 0) return; llint tmp = n % 10000000; n /= 10000000; ot(n); string str; int tmp2 = tmp % 100; if (tmp2) str = " " + to_string(tmp2); tmp /= 100; if (tmp > 0) { tmp2 = tmp % 10; if (tmp2) str = " " + to_string(tmp2) + " shata" + str; tmp /= 10; } if (tmp > 0) { tmp2 = tmp % 100; if (tmp2) str = " " + to_string(tmp2) + " hajar" + str; tmp /= 100; } if (tmp > 0) { tmp2 = tmp % 100; if (tmp2) str = " " + to_string(tmp2) + " lakh" + str; tmp /= 100; } if (n > 0) { str = " kuti" + str; } cout << str; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); llint n; int i = 1; while (cin >> n) { cout << setfill(' ') << setw(4) << i << "."; if (n == 0) cout << " 0"; ot(n); cout << endn; i++; } } // Solved By: shihab4t // Tuesday, August 24, 2021 | 02:50:10 AM (+06)
21.480769
63
0.442256
shihab4t
bb119acc860c8087b6c7dfb2c2a44e333452c2a5
5,039
hpp
C++
Array/Array.hpp
PrathameshThorat008/Advance-ADT
d89ccc777624bf8cfcb7144980c14efce919084f
[ "MIT" ]
null
null
null
Array/Array.hpp
PrathameshThorat008/Advance-ADT
d89ccc777624bf8cfcb7144980c14efce919084f
[ "MIT" ]
1
2022-01-23T06:53:08.000Z
2022-03-18T06:41:02.000Z
Array/Array.hpp
PrathameshThorat008/Advance-ADT
d89ccc777624bf8cfcb7144980c14efce919084f
[ "MIT" ]
null
null
null
#pragma once #include <stdlib.h> #include <algorithm> #include <iostream> using namespace std; template <class T> class Array { private: T *arr; public: int length; Array() : length(0), arr((T *)malloc(sizeof(T) * length)){}; Array(Array<T> *arr2) : length(0), arr((T *)malloc(sizeof(T) * length)) { for (int i = 0; i < arr2->length; i++) this->add(arr2->operator[](i)); }; void add(T el) { length++; arr = (T *)realloc(arr, sizeof(T) * length); arr[length - 1] = el; } void add(T el, int index) { length++; arr = (T *)realloc(arr, sizeof(T) * length); for (int i = length - 1; i > index; i--) { arr[i] = arr[i - 1]; } arr[index] = el; } void operator<<(T el) { add(el); } void remove() { length--; arr = (T *)realloc(arr, sizeof(T) * length); } void remove(int index) { length--; for (int i = index; i < length; i++) { arr[i] = arr[i + 1]; } arr = (T *)realloc(arr, sizeof(T) * length); } void update(T el, int index) { arr[index] = el; } int linearSearch(T el) { int index = -1; for (int i = 0; i < length; i++) { if (arr[i] == el) { index = i; break; } } return index; } int binarySearch(T el) { int index = -1; int s = 0, e = length; while (1) { int mid = (s + e) / 2; if (arr[mid] == el) { index = mid; break; } else if (arr[s] == el) { index = s; break; } else if (arr[e] == el) { index = e; break; } else if (arr[mid] < el) s = mid + 1; else if (arr[mid] > el) e = mid - 1; } return index; } void rotate(int noOfElements) { noOfElements %= length; int gcd = __gcd(length, noOfElements); for (int i = 0; i < gcd; i++) { T temp = arr[i]; int j = i; while (1) { int k = j + noOfElements; if (k >= length) k = k - length; if (k == i) break; arr[j] = arr[k]; j = k; } arr[j] = temp; } } void sort() { for (int i = 0; i < length; i++) { for (int j = i; j < length; j++) { if (arr[j] < arr[i]) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } T &get(int index) { return arr[index]; } T &operator[](int index) { return arr[index]; } string join(string connector) { string str; for (int i = 0; i < length; i++) { if (i < length - 1) str += to_string(arr[i]) + connector; else str += to_string(arr[i]); } return str; } Array<T> operator+(Array<T> arr2) { Array<T> x(this); for (int i = 0; i < arr2.length; i++) x.add(arr2[i]); return x; } void operator+=(Array<T> arr2) { for (int i = 0; i < arr2.length; i++) add(arr2[i]); } Array<T> map(T (*callback)(T)) { Array<T> newArr; for (int i = 0; i < this->length; i++) { T data = callback(arr[i]); newArr.add(data); } return newArr; } Array<T> map(T (*callback)(T, int)) { Array<T> newArr; for (int i = 0; i < this->length; i++) { T data = callback(arr[i], i); newArr.add(data); } return newArr; } Array<T> map(T (*callback)(T, int, Array<T> *)) { Array<T> newArr; for (int i = 0; i < this->length; i++) { T data = callback(arr[i], i, this); newArr.add(data); } return newArr; } ~Array() { free(arr); } }; template <> string Array<char>::join(string connector) { string str; for (int i = 0; i < length; i++) { if (i < length - 1) str += arr[i] + connector; else str += arr[i]; } return str; } template <> string Array<string>::join(string connector) { string str; for (int i = 0; i < length; i++) { if (i < length - 1) str += arr[i] + connector; else str += arr[i]; } return str; }
18.732342
64
0.372495
PrathameshThorat008
bb11f90a51d53f666ca45a600bf9500d1b7f425e
222
hpp
C++
lib/CManager/src/cmd_analog.hpp
sinanislekdemir/minik
cde6f228e20c51d96cdb3c84e8ae4c85a5b2f4fb
[ "BSD-3-Clause" ]
8
2022-01-01T19:36:06.000Z
2022-01-25T15:57:28.000Z
lib/CManager/src/cmd_analog.hpp
sinanislekdemir/minik
cde6f228e20c51d96cdb3c84e8ae4c85a5b2f4fb
[ "BSD-3-Clause" ]
4
2022-01-17T15:45:39.000Z
2022-02-27T19:52:42.000Z
lib/CManager/src/cmd_analog.hpp
sinanislekdemir/minik
cde6f228e20c51d96cdb3c84e8ae4c85a5b2f4fb
[ "BSD-3-Clause" ]
null
null
null
#ifndef _cmd_analog_hpp #define _cmd_analog_hpp #include "program.hpp" int command_analogread(command c, program *p); int command_analogwrite(command c, program *p); int command_analogref(command c, program *p); #endif
20.181818
47
0.788288
sinanislekdemir
bb144a48837ce3d7314a9db645fa243a4980301d
1,721
cpp
C++
test/local_search/2_local_search/2_local_search_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
test/local_search/2_local_search/2_local_search_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
test/local_search/2_local_search/2_local_search_test.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
1
2021-02-24T06:23:56.000Z
2021-02-24T06:23:56.000Z
//======================================================================= // Copyright (c) // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= /** * @file 2_local_search_test.cpp * @brief * @author Piotr Wygocki * @version 1.0 * @date 2013-09-20 */ #include "test_utils/sample_graph.hpp" #include "test_utils/logger.hpp" #include "test_utils/2_local_search_logger.hpp" #include "paal/local_search/2_local_search/2_local_search.hpp" #include "paal/data_structures/cycle/simple_cycle.hpp" #include <boost/test/unit_test.hpp> #include <vector> #include <string> using std::string; using std::vector; using namespace paal::local_search; using namespace paal; BOOST_AUTO_TEST_CASE(two_local_search_test) { //! [Two Local Search Example] // sample data typedef sample_graphs_metrics SGM; auto gm = SGM::get_graph_metric_small(); const int size = gm.size(); std::vector<int> v(size); std::iota(v.begin(), v.end(), 0); // create random solution std::random_shuffle(v.begin(), v.end()); typedef data_structures::simple_cycle<int> Cycle; Cycle cycle(v.begin(), v.end()); // creating local search components auto lsc = get_default_two_local_components(gm); // printing LOGLN("Length \t" << get_cycle_length(gm, cycle)); // setting logger auto logger = utils::make_two_ls_logger(gm, 100); // search two_local_search(cycle, local_search::first_improving_strategy{}, logger, utils::always_false(), lsc); //! [Two Local Search Example] }
28.683333
77
0.63742
Kommeren
bb1a1c710bace271469ed546b4ceb4e039e0539e
2,487
cpp
C++
framework/src/manager/TReadoutBoard.cpp
AudreyFrancisco/MultiLadderOperation
fd6fefd616d73487835c31bc9916bbd8490d1864
[ "BSD-4-Clause" ]
null
null
null
framework/src/manager/TReadoutBoard.cpp
AudreyFrancisco/MultiLadderOperation
fd6fefd616d73487835c31bc9916bbd8490d1864
[ "BSD-4-Clause" ]
null
null
null
framework/src/manager/TReadoutBoard.cpp
AudreyFrancisco/MultiLadderOperation
fd6fefd616d73487835c31bc9916bbd8490d1864
[ "BSD-4-Clause" ]
null
null
null
#include <exception> #include <stdexcept> #include "TChipConfig.h" #include "TBoardConfig.h" #include "TReadoutBoard.h" using namespace std; //___________________________________________________________________ TReadoutBoard::TReadoutBoard() : TVerbosity() { } //___________________________________________________________________ TReadoutBoard::TReadoutBoard( shared_ptr<TBoardConfig> config ) { if ( !config ) { throw runtime_error( "TReadoutBoard::TReadoutBoard() - board config. is a nullptr !" ); } } //___________________________________________________________________ TReadoutBoard::~TReadoutBoard() { fChipPositions.clear(); } //___________________________________________________________________ void TReadoutBoard::AddChipConfig( shared_ptr<TChipConfig> newChipConfig ) { if ( !newChipConfig ) { throw invalid_argument( "TReadoutBoard::AddChipConfig() - null pointer"); } for ( unsigned int ii = 0; ii < fChipPositions.size() ; ii++ ) { shared_ptr<TChipConfig> sp_chip = (fChipPositions.at(ii)).lock(); if ( newChipConfig->GetChipId() == sp_chip->GetChipId() ) { throw invalid_argument( "TReadoutBoard::AddChipConfig() - duplicate chip id" ); } } fChipPositions.push_back( newChipConfig ); } //___________________________________________________________________ int TReadoutBoard::GetControlInterface( const uint8_t chipId ) const { int chip = GetChipById( chipId ); shared_ptr<TChipConfig> sp_chip = (fChipPositions.at(chip)).lock(); return sp_chip->GetControlInterface(); } //___________________________________________________________________ int TReadoutBoard::GetChipById( const uint8_t chipId ) const { bool found = false; int position = TChipConfigData::kInitValue; for ( unsigned int i = 0; i < fChipPositions.size(); i++ ) { shared_ptr<TChipConfig> sp_chip = (fChipPositions.at(i)).lock(); if ( sp_chip->GetChipId() == chipId ) { position = i; found = true; break; } } if ( !found ) { throw invalid_argument( "TReadoutBoard::GetChipById() - non existing chip" ); } return position; } //___________________________________________________________________ int TReadoutBoard::GetReceiver( const uint8_t chipId ) const { int chip = GetChipById( chipId ); shared_ptr<TChipConfig> sp_chip = (fChipPositions.at(chip)).lock(); return sp_chip->GetReceiver(); }
31.481013
95
0.71532
AudreyFrancisco
bb1d10516e634fb98b369a62d7b4a3ed741e5018
40,219
cpp
C++
source/Library/System/Environment.cpp
dracc/VCMP-SqMod
d3e6adea147f5b2cae5119ddd6028833aa625c09
[ "MIT" ]
null
null
null
source/Library/System/Environment.cpp
dracc/VCMP-SqMod
d3e6adea147f5b2cae5119ddd6028833aa625c09
[ "MIT" ]
null
null
null
source/Library/System/Environment.cpp
dracc/VCMP-SqMod
d3e6adea147f5b2cae5119ddd6028833aa625c09
[ "MIT" ]
null
null
null
// ------------------------------------------------------------------------------------------------ #include "Library/System/Environment.hpp" // ------------------------------------------------------------------------------------------------ #include <cctype> #include <cstdlib> #include <cstring> #include <utility> // ------------------------------------------------------------------------------------------------ #ifdef SQMOD_OS_WINDOWS #include <windows.h> #include <shlobj.h> #else #include <linux/limits.h> #include <sys/utsname.h> #include <unistd.h> #include <pwd.h> #endif // ------------------------------------------------------------------------------------------------ namespace SqMod { // ------------------------------------------------------------------------------------------------ #ifdef SQMOD_OS_WINDOWS // Maximum path size in characters #define SQMOD_MAX_PATH (sizeof(TCHAR) * MAX_PATH) // Character to be used when working with path typedef TCHAR PChar; #else // Maximum path size in characters #define SQMOD_MAX_PATH (PATH_MAX) // Character to be used when working with path typedef CharT PChar; #endif // SQMOD_OS_WINDOWS // ------------------------------------------------------------------------------------------------ void SysEnv::Get(Buffer & b, CCStr name, CCStr fallback) { // Make sure the requested variable name is valid if (name && *name != 0) { // Is there a buffer to work with? if (!b) { // Acquire a moderately sized buffer b = Buffer(128); } #ifdef SQMOD_OS_WINDOWS // Retrieve the variable contents into the buffer that we have DWORD len = GetEnvironmentVariableA(name, &b.Cursor(), b.Remaining()); // If the returned length is 0 then the variable doesn't exist if (!len) { // Write the fall-back value into the buffer instead len = b.WriteS(b.Position(), fallback); } // Did we have enough space left in the buffer? else if (len > b.Remaining()) { // Acquire a new buffer with a more appropriate capacity this time b.Grow(len - b.Remaining() + 2); // Attempt to retrieve the variable contents one more time len = GetEnvironmentVariableA(name, &b.Cursor(), b.Remaining()); } // Move the edit cursor to the end of the appended data b.Advance(len); #else // Retrieve the pointer to the variable contents CSStr val = getenv(name); // If the returned pointer is null then the variable doesn't exist if (!val) { // Write the fall-back value into the buffer instead b.AppendS(fallback); } else { // Write the variable contents to the buffer b.AppendS(val); } #endif } // Make sure that whatever string is in the buffer is null terminated b.Cursor() = '\0'; } // ------------------------------------------------------------------------------------------------ bool SysEnv::Has(CCStr name) { #ifdef SQMOD_OS_WINDOWS return (GetEnvironmentVariableA(name, nullptr, 0) > 0); #else return (getenv(name) != 0); #endif } // ------------------------------------------------------------------------------------------------ bool SysEnv::Has(const String & name) { #ifdef SQMOD_OS_WINDOWS return (GetEnvironmentVariableA(name.c_str(), nullptr, 0) > 0); #else return (getenv(name.c_str()) != 0); #endif } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::Get(CCStr name, CCStr fallback) { // Allocate a moderately sized buffer Buffer b(128); // Forward the call to the shared function Get(b, name, fallback); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ bool SysEnv::Set(CCStr name, CCStr value) { #ifdef SQMOD_OS_WINDOWS // Set the specified environment variable and return the result return (SetEnvironmentVariableA(name, value) != 0); #else // Allocated a moderately sized buffer Buffer b(256); // Generate the necessary set command b.WriteF(0, "%s=%s", name, value); // Set the resulted environment variable and return the result return (putenv(b.Data()) == 0); #endif } // ------------------------------------------------------------------------------------------------ bool SysEnv::Set(const String & name, const String & value) { #ifdef SQMOD_OS_WINDOWS // Set the specified environment variable and return the result return (SetEnvironmentVariableA(name.c_str(), value.c_str()) != 0); #else // Obtain a temporary buffer capable of holding the set command Buffer b(name.size() + value.size() + 2); // Generate the necessary set command b.WriteF(0, "%s=%s", name.c_str(), value.c_str()); // Set the resulted environment variable and return the result return (putenv(b.Data()) == 0); #endif } // ------------------------------------------------------------------------------------------------ String SysEnv::OSName() { #ifdef SQMOD_OS_WINDOWS // Prepare the structure in which the OS information is retrieved OSVERSIONINFO vi; // Specify the size of the structure vi.dwOSVersionInfoSize = sizeof(vi); // Attempt to populate the previously created structure with information if (GetVersionEx(&vi) == 0) { return "Unknown Windows"; } // Identify the platform from the obtained information switch (vi.dwPlatformId) { case VER_PLATFORM_WIN32s: return "Windows 3.x"; case VER_PLATFORM_WIN32_WINDOWS: return vi.dwMinorVersion == 0 ? "Windows 95" : "Windows 98"; case VER_PLATFORM_WIN32_NT: return "Windows NT"; default: return "Windows [Unknown]"; } #else // Prepare the structure in which the OS information is retrieved struct utsname uts; // Attempt to populate the previously created structure with information if (uname(&uts) < 0) { return String("Unknown Unix"); } // Return the requested information return uts.sysname; #endif } // ------------------------------------------------------------------------------------------------ String SysEnv::OSDisplayName() { #ifdef SQMOD_OS_WINDOWS // Prepare the structure in which the OS information is retrieved OSVERSIONINFO vi; // Specify the size of the structure vi.dwOSVersionInfoSize = sizeof(vi); // Attempt to populate the previously created structure with information if (GetVersionEx(&vi) == 0) { return "Unknown Windows"; } // Identify the platform from the obtained information switch(vi.dwMajorVersion) { case 6: switch (vi.dwMinorVersion) { case 0: return "Windows Vista/Server 2008"; case 1: return "Windows 7/Server 2008 R2"; case 2: return "Windows 8/Server 2012"; default: return "Windows 6.x [Unknown]"; } case 5: switch (vi.dwMinorVersion) { case 0: return "Windows 2000"; case 1: return "Windows XP"; case 2: return "Windows Server 2003/Windows Server 2003 R2"; default: return "Windows 5.x [Unknown]"; } case 4: switch (vi.dwMinorVersion) { case 0: return "Windows 95/Windows NT 4.0"; case 10: return "Windows 98"; case 90: return "Windows ME"; default: return "Windows 4.x [Unknown]"; } default: return "Windows [Unknown]"; } #else // Use the same same output from OSName return OSName(); #endif } // ------------------------------------------------------------------------------------------------ String SysEnv::OSVersion() { #ifdef SQMOD_OS_WINDOWS // Prepare the structure in which the OS information is retrieved OSVERSIONINFO vi; // Specify the size of the structure vi.dwOSVersionInfoSize = sizeof(vi); // Attempt to populate the previously created structure with information if (GetVersionEx(&vi) == 0) { String("Unknown"); } // Obtain a temporary buffer capable of holding the version string Buffer b(128); // The amount of data written to the buffer Uint32 sz = 0; // Generate the version string with the received information if (vi.szCSDVersion[0]) { sz = b.WriteF(0, "%lu.%lu (Build %lu : %s)", vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber, vi.szCSDVersion); } else { sz = b.WriteF(0, "%lu.%lu (Build %lu)", vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber); } // Return a string with the buffer contents and leave the buffer clean after itself return String(b.Get< String::value_type >(), sz); #else // Prepare the structure in which the OS information is retrieved struct utsname uts; // Attempt to populate the previously created structure with information if (uname(&uts) < 0) { return String("Unknown"); } // Return the requested information return uts.release; #endif } // ------------------------------------------------------------------------------------------------ String SysEnv::OSArchitecture() { #ifdef SQMOD_OS_WINDOWS // Prepare the structure in which the system information is retrieved SYSTEM_INFO si; // Attempt to populate the previously created structure with information GetSystemInfo(&si); // Identify the architecture from the obtained information switch (si.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_INTEL: return "IA32"; case PROCESSOR_ARCHITECTURE_MIPS: return "MIPS"; case PROCESSOR_ARCHITECTURE_ALPHA: return "ALPHA"; case PROCESSOR_ARCHITECTURE_PPC: return "PPC"; case PROCESSOR_ARCHITECTURE_IA64: return "IA64"; #ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: return "IA64/32"; #endif #ifdef PROCESSOR_ARCHITECTURE_AMD64 case PROCESSOR_ARCHITECTURE_AMD64: return "AMD64"; #endif default: return "Unknown"; } #else // Prepare the structure in which the OS information is retrieved struct utsname uts; // Attempt to populate the previously created structure with information if (uname(&uts) < 0) { return String("Unknown"); } // Return the requested information return uts.machine; #endif } // ------------------------------------------------------------------------------------------------ String SysEnv::NodeName() { #ifdef SQMOD_OS_WINDOWS // Obtain a temporary buffer capable of holding the node name string Buffer b(MAX_COMPUTERNAME_LENGTH + 1); // Used to tell the size of our buffer and the size of data written to it DWORD size = b.Size< TCHAR >(); // Attempt to obtain the requested information if (GetComputerNameA(b.Data(), &size) == 0) { return String(); } // Return a string with the buffer contents and leave the buffer clean after itself return String(b.Get< String::value_type >(), size); #else // Prepare the structure in which the OS information is retrieved struct utsname uts; // Attempt to populate the previously created structure with information if (uname(&uts) < 0) { return String("Unknown"); } // Return the requested information return uts.nodename; #endif } // ------------------------------------------------------------------------------------------------ Uint32 SysEnv::ProcessorCount() { #ifdef SQMOD_OS_WINDOWS // Prepare the structure in which the system information is retrieved SYSTEM_INFO si; // Attempt to populate the previously created structure with information GetSystemInfo(&si); // Return the requested information return si.dwNumberOfProcessors; #elif defined(_SC_NPROCESSORS_ONLN) // Attempt to obtain the number of processors available on the system const Int32 count = sysconf(_SC_NPROCESSORS_ONLN); // Validate the result and return the appropriate value return (count < 0) ? 1 : static_cast< Uint32 >(count); #else // Obviously at least one processor should be available return 1; #endif } // ------------------------------------------------------------------------------------------------ void SysEnv::TerminatePath(Buffer & b) { // Is there any path to terminate? if (!b) { return; } // Make sure that the path contains a trailing slash if necessary else if (b.Cursor() == 0 && b.Before() != SQMOD_DIRSEP_CHAR) { b.Push(SQMOD_DIRSEP_CHAR); } // Make sure that whatever string is in the buffer, if any, is null terminated b.Cursor() = '\0'; } // ------------------------------------------------------------------------------------------------ void SysEnv::ExpandVars(Buffer & b, CCStr pos, CCStr end) { // Let's have a string to store the extracted variable name and value String var; // Extract the remaining directories from the specified path while (pos != end) { // Should we start looking for a variable name? if (*pos == '$') { // Clear previous name, if any var.clear(); // Where the name of the variable starts and where it ends CCStr start = ++pos, stop = pos; // Is this variable name enclosed within curly braces? if (*start == '{') { // Find the closing brace stop = strchr(start, '}'); // Was there a closing brace? if (!stop) { // Append the rest of the string to the buffer b.AppendS(pos - 1, end - pos + 1); // Stop parsing here break; } // Is there anything between the brace? else if ((stop - start) >= 1) { // Slice the variable name var.assign(start + 1, stop - start - 1); // Skip the ending brace ++stop; } } // Is the dollar character followed by a character allowed in variable names? else if (isalnum(*start) != 0 || *start == '_') { // Find the first character that isn't allowed in variable names while (stop != end && (isalnum(*stop) != 0 || *stop == '_')) { ++stop; } // Have we found anything? if (start != stop) { // Slice the variable name var.assign(start, stop - start); } } else { // Just add the character to the buffer as is b.Push('$'); // Skip to the next character continue; } // Update the position pos = stop; // Do we have a valid variable name and does it exist? if (!var.empty() && Has(var)) { // Append the variable contents to our buffer Get(b, var.c_str(), nullptr); } } // Just add the character to the buffer as is else { b.Push(*(pos++)); } } // Make sure the string in the buffer is null terminated b.Cursor() = '\0'; } // ------------------------------------------------------------------------------------------------ void SysEnv::ExpandPath(Buffer & b, CCStr pos, CCStr end) { // Does the path even contain something to be expanded? if (pos == end || *pos == '\0') { return; // Nothing to expand! } // If the path starts with the tilde character then the home directory was requested else if (*pos == '~') { // To be expanded, the tilde character must be followed by a slash if (*(++pos) == SQMOD_DIRSEP_CHAR) { // Let's expand this tilde to the home directory HomeDir(b); // Let's skip the slash as well ++pos; } // Go back to the previous character and use it literally else { --pos; } } // The remaining string can be expanded normally ExpandVars(b, pos, end); } // ------------------------------------------------------------------------------------------------ void SysEnv::ExpandVars(Buffer & b, CCStr str) { // Do we have anything to expand? if (!str || *str == '\0') { // Make sure the string in the specified buffer, if any, is null terminated if (b) { b.Cursor() = '\0'; } // Nothing to expand! return; } // Calculate the size of the specified string const Uint32 len = strlen(str); // Forward the call to the internal function ExpandVars(b, str, str + len); } // ------------------------------------------------------------------------------------------------ void SysEnv::ExpandVars(Buffer & b, const String & str) { // Do we have anything to expand? if (str.empty()) { // Make sure the string in the specified buffer, if any, is null terminated if (b) { b.Cursor() = '\0'; } // Nothing to expand! return; } // Forward the call to the internal function ExpandVars(b, str.c_str(), str.c_str() + str.size()); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::ExpandVars(CCStr str) { // Do we have anything to expand? if (!str || *str == '\0') { return Buffer(); // Nothing to expand! } // Calculate the size of the specified string const Uint32 len = strlen(str); // Allocate a moderately sized buffer Buffer b(len + 128); // Forward the call to the internal function ExpandVars(b, str, str + len); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::ExpandVars(const String & str) { // Do we have anything to expand? if (str.empty()) { return Buffer(); // Nothing to expand! } // Allocate a moderately sized buffer Buffer b(str.size() + 128); // Forward the call to the internal function ExpandVars(b, str.c_str(), str.c_str() + str.size()); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::ExpandPath(Buffer & b, CCStr path) { // Do we have anything to expand? if (!path || *path == '\0') { // Make sure the string in the specified buffer, if any, is null terminated if (b) { b.Cursor() = '\0'; } // Nothing to expand! return; } // Calculate the size of the specified string const Uint32 len = strlen(path); // Forward the call to the internal function ExpandPath(b, path, path + len); } // ------------------------------------------------------------------------------------------------ void SysEnv::ExpandPath(Buffer & b, const String & path) { // Do we have anything to expand? if (path.empty()) { // Make sure the string in the specified buffer, if any, is null terminated if (b) { b.Cursor() = '\0'; } // Nothing to expand! return; } // Forward the call to the internal function ExpandPath(b, path.c_str(), path.c_str() + path.size()); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::ExpandPath(CCStr path) { // Do we have anything to expand? if (!path || *path == '\0') { return Buffer(); // Nothing to expand! } // Calculate the size of the specified string const Uint32 len = strlen(path); // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the internal function ExpandPath(b, path, path + len); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::ExpandPath(const String & path) { // Do we have anything to expand? if (path.empty()) { return Buffer(); // Nothing to expand! } // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the internal function ExpandPath(b, path.c_str(), path.c_str() + path.size()); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::WorkingDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Is there a buffer to work with? if (!b) { // Allocate buffer capable of storing a full path b = Buffer(SQMOD_MAX_PATH); } // Retrieve the current directory for the current process DWORD len = GetCurrentDirectoryA(b.Remaining(), &b.Cursor()); // Did we have enough space left in the buffer? if (len > b.Remaining()) { // Acquire a new buffer with a more appropriate capacity this time b.Grow(len - b.Remaining() + 2); // Attempt to retrieve the working directory one more time len = GetCurrentDirectoryA(b.Remaining(), &b.Cursor()); // ^ On failure the null terminator is included in the length } // Move the edit cursor to the end of the appended data b.Advance(len); #else // Do we have enough space to store a full path? if (b.Remaining() < SQMOD_MAX_PATH) { b.Grow(SQMOD_MAX_PATH - b.Remaining() + 2); } // Attempt to retrieve the current working directory and validate result if (getcwd(&b.Cursor(), b.Remaining())) { // Move the edit cursor to the end of the appended data b.Advance(strlen(&b.Cursor())); } #endif // SQMOD_OS_WINDOWS // Make sure that the path is properly terminated TerminatePath(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::WorkingDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function WorkingDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::HomeDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Do we have enough space to store a full path? if (b.Remaining() < SQMOD_MAX_PATH) { b.Grow(SQMOD_MAX_PATH - b.Remaining() + 2); } // Try the primary method of retrieving the home directory if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_PROFILE, nullptr, 0, &b.Cursor()))) { // Move the edit cursor to the end of the appended data b.Advance(strlen(&b.Cursor())); } // Try the secondary method of retrieving the home directory else if (Has("USERPROFILE")) { // Append the contents of the USERPROFILE environment variable Get(b, "USERPROFILE", nullptr); } else if (Has("HOMEDRIVE") && Has("HOMEPATH")) { // Append the contents of the HOMEDRIVE environment variable Get(b, "HOMEDRIVE", nullptr); // Append the contents of the HOMEPATH environment variable Get(b, "HOMEPATH", nullptr); } #else // Try the primary method of retrieving the home directory struct passwd * pwd = getpwuid(getuid()); // Validate the success of the previous operation if (pwd) { // Append the path to our buffer b.AppendS(pwd->pw_dir); } else { // Try the secondary method of retrieving the home directory pwd = getpwuid(geteuid()); // Validate the success of the previous operation if (pwd) { // Write the path to our buffer and store the size b.AppendS(pwd->pw_dir); } // Fall back to the system environment variables else if (Has("HOME")) { // Append the contents of the HOME environment variable Get(b, "HOME", nullptr); } } #endif // SQMOD_OS_WINDOWS // Make sure that the path is properly terminated TerminatePath(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::HomeDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function HomeDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::ConfigHomeDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Is there a buffer to work with? if (!b) { // Allocate buffer capable of storing a full path b = Buffer(SQMOD_MAX_PATH); } // Does the APPDATA environment variable exist? if (Has("APPDATA")) { // Obtain the contents of the APPDATA environment variable Get(b, "APPDATA", nullptr); } else { // Default to the home directory HomeDir(b); } #else // Obtain the home directory path (should contain a trailing slash) HomeDir(b); // Use the home directory and append the ".config" sub folder b.AppendS(".config"); #endif // SQMOD_OS_WINDOWS // Make sure that the path is properly terminated TerminatePath(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::ConfigHomeDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function ConfigHomeDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::DataHomeDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Is there a buffer to work with? if (!b) { // Allocate buffer capable of storing a full path b = Buffer(SQMOD_MAX_PATH); } // Does the LOCALAPPDATA environment variable exist? if (Has("LOCALAPPDATA")) { // Obtain the contents of the LOCALAPPDATA environment variable return Get(b, "LOCALAPPDATA", nullptr); } // Default to the home config directory return ConfigHomeDir(b); #else // Obtain the home directory path (should contain a trailing slash) HomeDir(b); // Use the home directory and append the ".local/share" sub folder b.AppendS(".config/share"); #endif // SQMOD_OS_WINDOWS // Make sure that the path is properly terminated TerminatePath(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::DataHomeDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function DataHomeDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::TempHomeDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Use the regular temp directory TempDir(b); #else // Obtain the home directory path (should contain a trailing slash) HomeDir(b); // Use the home directory and append the ".local/tmp" folder b.AppendS(".local/tmp"); // Make sure that the path is properly terminated TerminatePath(b); #endif // SQMOD_OS_WINDOWS } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::TempHomeDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function TempHomeDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::CacheHomeDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Use the regular temp directory TempDir(b); #else // Obtain the home directory path (should contain a trailing slash) HomeDir(b); // Use the home directory and append the ".cache" folder b.AppendS(".cache"); // Make sure that the path is properly terminated TerminatePath(b); #endif // SQMOD_OS_WINDOWS } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::CacheHomeDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function CacheHomeDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::TempDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Is there a buffer to work with? if (!b) { // Allocate buffer capable of storing a full path b = Buffer(SQMOD_MAX_PATH); } // Retrieve the path of the directory designated for temporary files DWORD len = GetTempPathA(b.Remaining(), &b.Cursor()); // Did we failed to retrieve the path? if (len == 0) { return; // Unable to retrieve the path! } // Did we have enough space left in the buffer? else if (len > b.Remaining()) { // Acquire a new buffer with a more appropriate capacity this time b.Grow(len - b.Remaining() + 2); // Attempt to retrieve the temporary directory one more time len = GetTempPathA(b.Remaining(), &b.Cursor()); // ^ On failure the null terminator is included in the length } // Convert the acquired path to its long form len = GetLongPathNameA(&b.Cursor(), &b.Cursor(), b.Remaining()); // Did we failed to convert the path? if (len == 0) { return; // Unable to convert the path! } // Did we have enough space left in the buffer? else if (len > b.Remaining()) { // Acquire a new buffer with a more appropriate capacity this time b.Grow(len - b.Remaining() + 2); // Attempt to retrieve the temporary directory again because we reused the buffer GetTempPathA(b.Remaining(), &b.Cursor()); // Attempt to convert the acquired path to its long form one more time len = GetLongPathNameA(&b.Cursor(), &b.Cursor(), b.Remaining()); // ^ On failure the null terminator is included in the length } // Move the edit cursor to the end of the appended data b.Advance(len); #else // Does the TMPDIR environment variable exist? if (SysEnv::Has("TMPDIR")) { // Obtain the contents of the TMPDIR environment variable Get(b, "TMPDIR", nullptr); } else { // Default to the "/tmp" directory b.AppendS("/tmp/"); } #endif // SQMOD_OS_WINDOWS // Make sure that the path is properly terminated TerminatePath(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::TempDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function TempDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::ConfigDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Is there a buffer to work with? if (!b) { // Allocate buffer capable of storing a full path b = Buffer(SQMOD_MAX_PATH); } // Does the PROGRAMDATA environment variable exist? if (Has("PROGRAMDATA")) { // Obtain the contents of the PROGRAMDATA environment variable Get(b, "PROGRAMDATA", nullptr); } else { // Make sure that whatever string is in the buffer, if any, is null terminated b.Cursor() = '\0'; // Unable to retrieve the path! return; } #else // Default to "/etc" directory b.AppendS("/etc/"); #endif // SQMOD_OS_WINDOWS // Make sure that the path is properly terminated TerminatePath(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::ConfigDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function ConfigDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::SystemDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS // Is there a buffer to work with? if (!b) { // Allocate buffer capable of storing a full path b = Buffer(SQMOD_MAX_PATH); } // Retrieve the path of the system directory DWORD len = GetSystemDirectoryA(&b.Cursor(), b.Remaining()); // Did we failed to retrieve the path? if (len == 0) { return; // Unable to retrieve the path! } // Did we have enough space left in the buffer? else if (len > b.Remaining()) { // Acquire a new buffer with a more appropriate capacity this time b.Grow(len - b.Remaining() + 2); // Attempt to retrieve the path of the system directory one more time len = GetSystemDirectoryA(&b.Cursor(), b.Remaining()); // ^ On failure the null terminator is included in the length } // Move the edit cursor to the end of the appended data b.Advance(len); #else // Use a dummy directory for now b.AppendS("/sys/"); #endif // SQMOD_OS_WINDOWS // Make sure that the path is properly terminated TerminatePath(b); } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::SystemDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Forward the call to the regular function SystemDir(b); // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ void SysEnv::NullDir(Buffer & b) { #ifdef SQMOD_OS_WINDOWS b.AppendS("NUL:"); #else b.AppendS("/dev/null/"); #endif // SQMOD_OS_WINDOWS // Make sure that whatever string is in the buffer, if any, is null terminated b.Cursor() = '\0'; } // ------------------------------------------------------------------------------------------------ Buffer SysEnv::NullDir() { // Allocate buffer capable of storing a full path Buffer b(SQMOD_MAX_PATH); // Append the null path #ifdef SQMOD_OS_WINDOWS b.AppendS("NUL:"); #else b.AppendS("/dev/null/"); #endif // SQMOD_OS_WINDOWS // Make sure that whatever string is in the buffer, if any, is null terminated b.Cursor() = '\0'; // Return ownership of the buffer return std::move(b); } // ------------------------------------------------------------------------------------------------ static bool SqEnv_Has(CCStr name) { return SysEnv::Has(name); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_Get(CCStr name) { return BufferToStrObj(SysEnv::Get(name, nullptr)); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_GetOr(CCStr name, CCStr fallback) { return BufferToStrObj(SysEnv::Get(name, fallback)); } // ------------------------------------------------------------------------------------------------ static void SqEnv_Set(CCStr name, CCStr value) { SysEnv::Set(name, value); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_ExpandVars(CCStr str) { return BufferToStrObj(SysEnv::ExpandVars(str)); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_ExpandPath(CCStr path) { return BufferToStrObj(SysEnv::ExpandPath(path)); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_WorkingDir() { return BufferToStrObj(SysEnv::WorkingDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_HomeDir() { return BufferToStrObj(SysEnv::HomeDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_ConfigHomeDir() { return BufferToStrObj(SysEnv::ConfigHomeDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_DataHomeDir() { return BufferToStrObj(SysEnv::DataHomeDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_TempHomeDir() { return BufferToStrObj(SysEnv::TempHomeDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_CacheHomeDir() { return BufferToStrObj(SysEnv::CacheHomeDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_TempDir() { return BufferToStrObj(SysEnv::TempDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_ConfigDir() { return BufferToStrObj(SysEnv::ConfigDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_SystemDir() { return BufferToStrObj(SysEnv::SystemDir()); } // ------------------------------------------------------------------------------------------------ static Object SqEnv_NullDir() { return BufferToStrObj(SysEnv::NullDir()); } // ================================================================================================ void Register_SysEnv(HSQUIRRELVM vm) { Table sens(vm); sens.Func(_SC("Has"), &SqEnv_Has); sens.Func(_SC("Get"), &SqEnv_Get); sens.Func(_SC("GetOr"), &SqEnv_GetOr); sens.Func(_SC("Set"), &SqEnv_Set); sens.Func(_SC("OSName"), &SysEnv::OSName); sens.Func(_SC("OSDisplayName"), &SysEnv::OSDisplayName); sens.Func(_SC("OSVersion"), &SysEnv::OSVersion); sens.Func(_SC("OSArchitecture"), &SysEnv::OSArchitecture); sens.Func(_SC("NodeName"), &SysEnv::NodeName); sens.Func(_SC("ProcessorCount"), &SysEnv::ProcessorCount); sens.Func(_SC("ExpandVars"), &SqEnv_ExpandVars); sens.Func(_SC("ExpandPath"), &SqEnv_ExpandPath); sens.Func(_SC("WorkingDir"), &SqEnv_WorkingDir); sens.Func(_SC("HomeDir"), &SqEnv_HomeDir); sens.Func(_SC("ConfigHomeDir"), &SqEnv_ConfigHomeDir); sens.Func(_SC("DataHomeDir"), &SqEnv_DataHomeDir); sens.Func(_SC("TempHomeDir"), &SqEnv_TempHomeDir); sens.Func(_SC("CacheHomeDir"), &SqEnv_CacheHomeDir); sens.Func(_SC("TempDir"), &SqEnv_TempDir); sens.Func(_SC("ConfigDir"), &SqEnv_ConfigDir); sens.Func(_SC("SystemDir"), &SqEnv_SystemDir); sens.Func(_SC("NullDir"), &SqEnv_NullDir); RootTable(vm).Bind(_SC("SqSysEnv"), sens); } } // Namespace:: SqMod
33.266336
104
0.520823
dracc
bb1eb41d93a007996849ded2f45c54f258c57a7b
15,113
cpp
C++
ds/security/csps/cryptoflex/slbcci/v1card.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/csps/cryptoflex/slbcci/v1card.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/csps/cryptoflex/slbcci/v1card.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// V1Card.cpp: implementation of the CV2Card class. // // (c) Copyright Schlumberger Technology Corp., unpublished work, created // 1999. This computer program includes Confidential, Proprietary // Information and is a Trade Secret of Schlumberger Technology Corp. All // use, disclosure, and/or reproduction is prohibited unless authorized // in writing. All Rights Reserved. ////////////////////////////////////////////////////////////////////// #include "NoWarning.h" #include <algorithm> #include <functional> #include <memory> // for auto_ptr #include <scuArrayP.h> #include <SmartCard.h> #include "TransactionWrap.h" #include "cciExc.h" #include "MethodHelp.h" #include "cciCert.h" #include "cciKeyPair.h" #include "cciPriKey.h" #include "cciPubKey.h" #include "V1Cert.h" #include "V1Cont.h" #include "V1ContRec.h" #include "V1KeyPair.h" #include "V1PriKey.h" #include "V1PubKey.h" #include "V1Paths.h" #include "V1Card.h" using namespace std; using namespace cci; using namespace scu; /////////////////////////// LOCAL/HELPER ///////////////////////////////// namespace { // Enumerate T type objects in the exchange and signature key pair // using C::<Accessor> to get the T object, returning vector<T> // objects. template<class T> class EnumItems : std::unary_function<void, vector<T> > { public: EnumItems(CV1Card const &rv1card, ObjectAccess oa, typename AccessorMethod<T, CAbstractKeyPair>::AccessorPtr Accessor) : m_rv1card(rv1card), m_oa(oa), m_matAccess(Accessor), m_Result() {} result_type operator()(argument_type) { DoAppend(m_rv1card.DefaultContainer()); return m_Result; } protected: void DoAppend(CContainer &rhcntr) { if (rhcntr) { AppendItem(rhcntr->ExchangeKeyPair()); AppendItem(rhcntr->SignatureKeyPair()); } } private: void AppendItem(CKeyPair &rhkp) { if (rhkp) { T hObject(m_matAccess(*rhkp)); if (hObject && (m_oa == hObject->Access())) m_Result.push_back(hObject); } } CV1Card const &m_rv1card; ObjectAccess m_oa; MemberAccessorType<T, CAbstractKeyPair> m_matAccess; result_type m_Result; }; bool IsSupported(iop::CSmartCard &rSmartCard) throw() { bool fSupported = false; try { rSmartCard.Select(CV1Paths::Chv()); rSmartCard.Select(CV1Paths::IcFile()); rSmartCard.Select(CV1Paths::RootContainers()); rSmartCard.Select(CV1Paths::PrivateKeys()); rSmartCard.Select(CV1Paths::PublicKeys()); fSupported = true; } catch(scu::Exception &) {} return fSupported; } } // namespace /////////////////////////// PUBLIC ///////////////////////////////// // Types // C'tors/D'tors CV1Card::~CV1Card() throw() {} // Operators // Operations void CV1Card::CardId(string const &rsNewCardId) const { CTransactionWrap(this); DWORD dwLen = OpenFile(CV1Paths::IcFile()); if (0 == dwLen) throw scu::OsException(NTE_FAIL); if (rsNewCardId.length() > dwLen) throw scu::OsException(ERROR_INVALID_PARAMETER); if (rsNewCardId.length() < dwLen) SmartCard().WriteBinary(0, rsNewCardId.length() + 1, reinterpret_cast<BYTE const *>(rsNewCardId.c_str())); else SmartCard().WriteBinary(0, static_cast<WORD>(rsNewCardId.length()), reinterpret_cast<BYTE const *>(rsNewCardId.data())); RefreshCardId(); } void CV1Card::ChangePIN(SecureArray<BYTE> const &rstrOldPIN, SecureArray<BYTE> const &rstrNewPIN) { CTransactionWrap wrap(this); SmartCard().Select(CV1Paths::Root()); SuperClass::ChangePIN(rstrOldPIN, rstrNewPIN); } void CV1Card::DefaultContainer(CContainer const &rcont) { m_avhDefaultCntr.Value(rcont); if(!m_avhDefaultCntr.Value()) m_avhDefaultCntr.Dirty(); // Nothing more to do since, by definition, the one and only // container is already the default container. } pair<string, // interpreted as the public modulus CPrivateKey> CV1Card::GenerateKeyPair(KeyType kt, string const &rsExponent, ObjectAccess oaPrivateKey) { throw Exception(ccNotImplemented); return pair<string, CPrivateKey>(); } void CV1Card::InitCard() { // We want to select /3f00/0015 (length 1744) and /3f00/3f11/0015 (length 300), and clear both files. CTransactionWrap wrap(this); BYTE bData[1744]; memset(bData, 0, 1744); SmartCard().Select(CV1Paths::RootContainers()); SmartCard().WriteBinary(0x0000, 0x06d0, bData); SmartCard().Select(CV1Paths::PublicKeys()); SmartCard().WriteBinary(0x0000, 0x012c, bData); } void CV1Card::InvalidateCache() { m_avhDefaultCntr.Value(CContainer()); m_avhDefaultCntr.Dirty(); m_avhExchangeKeyPair.Value(CKeyPair()); m_avhExchangeKeyPair.Dirty(); m_avhSignatureKeyPair.Value(CKeyPair()); m_avhSignatureKeyPair.Dirty(); } void CV1Card::Label(string const &rLabel) { throw Exception(ccNotImplemented); } DWORD CV1Card::OpenFile(char const *szPath) const { iop::FILE_HEADER fh; SmartCard().Select(szPath, &fh); return fh.file_size; } void CV1Card::VerifyKey(string const &rstrKey, BYTE bKeyNum) { CTransactionWrap wrap(this); SmartCard().Select(CV1Paths::CryptoSys()); SuperClass::VerifyKey(rstrKey, bKeyNum); } // Access size_t CV1Card::AvailableStringSpace(ObjectAccess oa) const { throw Exception(ccNotImplemented); return 0; } string CV1Card::CardId() const { return m_sCardId; } CContainer CV1Card::DefaultContainer() const { CTransactionWrap wrap(this); if (!m_avhDefaultCntr.IsCached()) { auto_ptr<CV1Container> apv1cntr(new CV1Container(*this, CV1ContainerRecord::DefaultName(), false)); if (apv1cntr->Exists()) { CContainer hcntr; hcntr = CContainer(apv1cntr.get()); apv1cntr.release(); m_avhDefaultCntr.Value(hcntr); } } return m_avhDefaultCntr.Value(); } vector<CContainer> CV1Card::EnumContainers() const { CContainer hcntr(0); auto_ptr<CV1Container> apv1cntr(new CV1Container(*this, CV1ContainerRecord::DefaultName(), false)); if (apv1cntr->Exists()) { hcntr = CContainer(apv1cntr.get()); apv1cntr.release(); } vector<CContainer> vhcntr; if (hcntr) vhcntr.push_back(hcntr); return vhcntr; } vector<CCertificate> CV1Card::EnumCertificates(ObjectAccess access) const { CTransactionWrap wrap(this); EnumItems<CCertificate> Enumerator(*this, access, CAbstractKeyPair::Certificate); return Enumerator(); } vector<CPublicKey> CV1Card::EnumPublicKeys(ObjectAccess access) const { CTransactionWrap wrap(this); EnumItems<CPublicKey> Enumerator(*this, access, CAbstractKeyPair::PublicKey); return Enumerator(); } vector<CPrivateKey> CV1Card::EnumPrivateKeys(ObjectAccess access) const { CTransactionWrap wrap(this); EnumItems<CPrivateKey> Enumerator(*this, access, CAbstractKeyPair::PrivateKey); return Enumerator(); } vector<CDataObject> CV1Card::EnumDataObjects(ObjectAccess access) const { return vector<CDataObject>(); // can never have data objects } string CV1Card::Label() const { throw Exception(ccNotImplemented); return string(); } CAbstractCertificate * CV1Card::MakeCertificate(ObjectAccess oa) const { CTransactionWrap wrap(this); if (oaPublicAccess != oa) throw Exception(ccInvalidParameter); return new CV1Certificate(*this, ksNone); } CAbstractContainer * CV1Card::MakeContainer() const { CTransactionWrap wrap(this); return new CV1Container(*this, CV1ContainerRecord::DefaultName(), true); } CAbstractDataObject * CV1Card::MakeDataObject(ObjectAccess oa) const { throw Exception(ccNotImplemented); return 0; } CAbstractKeyPair * CV1Card::MakeKeyPair(CContainer const &rhcont, KeySpec ks) const { CTransactionWrap wrap(this); // If the key pair is cached, return it; otherwise make a new one // and cache it. CArchivedValue<CKeyPair> *pavhkp = 0; switch (ks) { case ksExchange: pavhkp = &m_avhExchangeKeyPair; break; case ksSignature: pavhkp = &m_avhSignatureKeyPair; break; default: throw Exception(ccBadKeySpec); break; } if (!pavhkp->IsCached() || !pavhkp->Value()) pavhkp->Value(CKeyPair(new CV1KeyPair(*this, rhcont, ks))); return pavhkp->Value().operator->(); // yuk! } CAbstractPrivateKey * CV1Card::MakePrivateKey(ObjectAccess oa) const { CTransactionWrap wrap(this); if (oaPrivateAccess != oa) throw Exception(ccInvalidParameter); return new CV1PrivateKey(*this, ksNone); } CAbstractPublicKey * CV1Card::MakePublicKey(ObjectAccess oa) const { CTransactionWrap wrap(this); if (oaPublicAccess != oa) throw Exception(ccInvalidParameter); return new CV1PublicKey(*this, ksNone); } BYTE CV1Card::MaxKeys(KeyType kt) const { BYTE bCount; switch (kt) { case ktRSA1024: bCount = 2; break; default: bCount = 0; break; } return bCount; } size_t CV1Card::MaxStringSpace(ObjectAccess oa) const { throw Exception(ccNotImplemented); return 0; } bool CV1Card::SupportedKeyFunction(KeyType kt, CardOperation oper) const { bool fSupported = false; switch (oper) { case coEncryption: // .. or public key operations break; case coDecryption: // .. or private key operations switch (kt) { case ktRSA1024: fSupported = true; break; default: break; } default: break; } return fSupported; } scu::Marker<unsigned int> CV1Card::MarkerOnCard() const { return scu::Marker<unsigned int>(); } // Predicates bool CV1Card::IsCAPIEnabled() const { return true; } bool CV1Card::IsPKCS11Enabled() const { return false; } bool CV1Card::IsProtectedMode() const { return true; } bool CV1Card::IsKeyGenEnabled() const { return false; } bool CV1Card::IsEntrustEnabled() const { return false; } BYTE CV1Card::MajorVersion() const { return (BYTE)0; } bool CV1Card::IsMarkerOnCard() const { return false; } // Static Variables /////////////////////////// PROTECTED ///////////////////////////////// // C'tors/D'tors CV1Card::CV1Card(string const &rstrReaderName, auto_ptr<iop::CIOP> &rapiop, auto_ptr<iop::CSmartCard> &rapSmartCard) : SuperClass(rstrReaderName, rapiop, rapSmartCard), m_sCardId(), m_avhDefaultCntr(), m_avhExchangeKeyPair(), m_avhSignatureKeyPair() {} // Operators // Operations void CV1Card::DoSetup() { CAbstractCard::DoSetup(); RefreshCardId(); } // Access // Predicates // Static Variables /////////////////////////// PRIVATE ///////////////////////////////// // C'tors/D'tors // Operators // Operations auto_ptr<CAbstractCard> CV1Card::DoMake(string const &rstrReaderName, auto_ptr<iop::CIOP> &rapiop, auto_ptr<iop::CSmartCard> &rapSmartCard) { return IsSupported(*rapSmartCard.get()) ? auto_ptr<CAbstractCard>(new CV1Card(rstrReaderName, rapiop, rapSmartCard)) : auto_ptr<CAbstractCard>(0); } string CV1Card::ReadCardId() const { string sCardId; // *** BEGIN WORKAROUND *** // The following SetContext and OpenFile call is made to // make sure the card and this system's current path are // synchronized, pointing to the right directory. Without // it, the subsequent call to ReadBinaryFile fails because // they appear to be out of synch. It's not clear why // this happens but this workaround avoids the problem. try { SmartCard().Select(CV1Paths::RootContainers()); } catch (...) { } // *** END WORKAROUND *** try { iop::FILE_HEADER fh; SmartCard().Select(CV1Paths::IcFile(), &fh); DWORD dwLen = fh.file_size; scu::AutoArrayPtr<BYTE> aaCardId(new BYTE[dwLen + 1]); SmartCard().ReadBinary(0, dwLen, aaCardId.Get()); aaCardId[dwLen] = '\0'; sCardId.assign(reinterpret_cast<char *>(aaCardId.Get())); } catch (...) { } return sCardId; } void CV1Card::RefreshCardId() const { m_sCardId = ReadCardId(); } // Access // Predicates // Static Variables
23.875197
103
0.536558
npocmaka
bb273f3bdb11d6262d7f465851fc9144b956ade5
6,448
cpp
C++
lammps-master/src/compute_fragment_atom.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/compute_fragment_atom.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/compute_fragment_atom.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Axel Kohlmeyer (Temple U) ------------------------------------------------------------------------- */ #include <cstring> #include "compute_fragment_atom.h" #include "atom.h" #include "atom_vec.h" #include "update.h" #include "modify.h" #include "force.h" #include "comm.h" #include "memory.h" #include "error.h" #include "group.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ ComputeFragmentAtom::ComputeFragmentAtom(LAMMPS *lmp, int narg, char **arg) : Compute(lmp, narg, arg), fragmentID(NULL) { if (narg != 3) error->all(FLERR,"Illegal compute fragment/atom command"); if (atom->avec->bonds_allow == 0) error->all(FLERR,"Compute fragment/atom used when bonds are not allowed"); peratom_flag = 1; size_peratom_cols = 0; comm_forward = 1; comm_reverse = 1; nmax = 0; } /* ---------------------------------------------------------------------- */ ComputeFragmentAtom::~ComputeFragmentAtom() { memory->destroy(fragmentID); } /* ---------------------------------------------------------------------- */ void ComputeFragmentAtom::init() { if (atom->tag_enable == 0) error->all(FLERR,"Cannot use compute fragment/atom unless atoms have IDs"); if (force->bond == NULL) error->all(FLERR,"Compute fragment/atom requires a bond style to be defined"); int count = 0; for (int i = 0; i < modify->ncompute; i++) if (strcmp(modify->compute[i]->style,"fragment/atom") == 0) count++; if (count > 1 && comm->me == 0) error->warning(FLERR,"More than one compute fragment/atom"); } /* ---------------------------------------------------------------------- */ void ComputeFragmentAtom::compute_peratom() { int i,j,k; invoked_peratom = update->ntimestep; // grow fragmentID array if necessary if (atom->nmax > nmax) { memory->destroy(fragmentID); nmax = atom->nmax; memory->create(fragmentID,nmax,"fragment/atom:fragmentID"); vector_atom = fragmentID; } // if group is dynamic, insure ghost atom masks are current if (group->dynamic[igroup]) { commflag = 0; comm->forward_comm_compute(this); } // each atom starts in its own fragment, int nlocal = atom->nlocal; tagint *tag = atom->tag; int *mask = atom->mask; int *num_bond = atom->num_bond; int **bond_type = atom->bond_type; tagint **bond_atom = atom->bond_atom; for (i = 0; i < nlocal + atom->nghost; i++) if (mask[i] & groupbit) fragmentID[i] = tag[i]; else fragmentID[i] = 0; // loop until no more changes on any proc: // acquire fragmentIDs of ghost atoms // loop over my atoms, and check atoms bound to it // if both atoms are in fragment, assign lowest fragmentID to both // iterate until no changes in my atoms // then check if any proc made changes commflag = 1; int change,done,anychange; while (1) { comm->forward_comm_compute(this); // reverse communication when bonds are not stored on every processor if (force->newton_bond) comm->reverse_comm_compute(this); change = 0; while (1) { done = 1; for (i = 0; i < nlocal; i++) { if (!(mask[i] & groupbit)) continue; for (j = 0; j < num_bond[i]; j++) { if (bond_type[i][j] == 0) continue; k = atom->map(bond_atom[i][j]); if (k < 0) continue; if (!(mask[k] & groupbit)) continue; if (fragmentID[i] == fragmentID[k]) continue; fragmentID[i] = fragmentID[k] = MIN(fragmentID[i],fragmentID[k]); done = 0; } } if (!done) change = 1; if (done) break; } // stop if all procs are done MPI_Allreduce(&change,&anychange,1,MPI_INT,MPI_MAX,world); if (!anychange) break; } } /* ---------------------------------------------------------------------- */ int ComputeFragmentAtom::pack_forward_comm(int n, int *list, double *buf, int /*pbc_flag*/, int * /*pbc*/) { int i,j,m; m = 0; if (commflag) { for (i = 0; i < n; i++) { j = list[i]; buf[m++] = fragmentID[j]; } } else { int *mask = atom->mask; for (i = 0; i < n; i++) { j = list[i]; buf[m++] = ubuf(mask[j]).d; } } return m; } /* ---------------------------------------------------------------------- */ void ComputeFragmentAtom::unpack_forward_comm(int n, int first, double *buf) { int i,m,last; m = 0; last = first + n; if (commflag) for (i = first; i < last; i++) { double x = buf[m++]; // only overwrite ghost IDs with values lower than current ones fragmentID[i] = MIN(x,fragmentID[i]); } else { int *mask = atom->mask; for (i = first; i < last; i++) mask[i] = (int) ubuf(buf[m++]).i; } } /* ---------------------------------------------------------------------- */ int ComputeFragmentAtom::pack_reverse_comm(int n, int first, double *buf) { int i,m,last; m = 0; last = first + n; for (i = first; i < last; i++) { buf[m++] = fragmentID[i]; } return m; } /* ---------------------------------------------------------------------- */ void ComputeFragmentAtom::unpack_reverse_comm(int n, int *list, double *buf) { int i,j,m; m = 0; for (i = 0; i < n; i++) { j = list[i]; double x = buf[m++]; // only overwrite local IDs with values lower than current ones fragmentID[j] = MIN(x,fragmentID[j]); } } /* ---------------------------------------------------------------------- memory usage of local atom-based array ------------------------------------------------------------------------- */ double ComputeFragmentAtom::memory_usage() { double bytes = nmax * sizeof(double); return bytes; }
26.318367
82
0.519386
rajkubp020
bb316da5751b41614f789db5d168f9ec47ffeabd
5,090
cpp
C++
3rdparty/openmm/plugins/amoeba/openmmapi/src/AmoebaWcaDispersionForce.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
5
2020-07-31T17:33:03.000Z
2022-01-01T19:24:37.000Z
3rdparty/openmm/plugins/amoeba/openmmapi/src/AmoebaWcaDispersionForce.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
11
2020-06-16T05:05:42.000Z
2022-03-30T09:59:14.000Z
3rdparty/openmm/plugins/amoeba/openmmapi/src/AmoebaWcaDispersionForce.cpp
merkys/MMB
0531385b8367405e1188e31c3eef7aa4cc50170b
[ "MIT" ]
9
2020-01-24T12:02:37.000Z
2020-10-16T06:23:56.000Z
/* -------------------------------------------------------------------------- * * OpenMMAmoeba * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2008-2009 Stanford University and the Authors. * * Authors: * * Contributors: * * * * 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, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * -------------------------------------------------------------------------- */ #include "openmm/Force.h" #include "openmm/OpenMMException.h" #include "openmm/AmoebaWcaDispersionForce.h" #include "openmm/internal/AmoebaWcaDispersionForceImpl.h" #include <cmath> using namespace OpenMM; AmoebaWcaDispersionForce::AmoebaWcaDispersionForce() { epso = 0.1100; epsh = 0.0135; rmino = 1.7025; rminh = 1.3275; awater = 0.033428; slevy = 1.0; shctd = 0.81; dispoff = 0.26; } int AmoebaWcaDispersionForce::addParticle(double radius, double epsilon) { parameters.push_back(WcaDispersionInfo(radius, epsilon)); return parameters.size()-1; } void AmoebaWcaDispersionForce::getParticleParameters(int particleIndex, double& radius, double& epsilon) const { radius = parameters[particleIndex].radius; epsilon = parameters[particleIndex].epsilon; } void AmoebaWcaDispersionForce::setParticleParameters(int particleIndex, double radius, double epsilon) { parameters[particleIndex].radius = radius; parameters[particleIndex].epsilon = epsilon; } double AmoebaWcaDispersionForce::getEpso() const { return epso; } double AmoebaWcaDispersionForce::getEpsh() const { return epsh; } double AmoebaWcaDispersionForce::getRmino() const { return rmino; } double AmoebaWcaDispersionForce::getRminh() const { return rminh; } double AmoebaWcaDispersionForce::getAwater() const { return awater; } double AmoebaWcaDispersionForce::getShctd() const { return shctd; } double AmoebaWcaDispersionForce::getDispoff() const { return dispoff; } double AmoebaWcaDispersionForce::getSlevy() const { return slevy; } void AmoebaWcaDispersionForce::setEpso(double inputEpso) { epso = inputEpso; } void AmoebaWcaDispersionForce::setEpsh(double inputEpsh) { epsh = inputEpsh; } void AmoebaWcaDispersionForce::setRmino(double inputRmino) { rmino = inputRmino; } void AmoebaWcaDispersionForce::setRminh(double inputRminh) { rminh = inputRminh; } void AmoebaWcaDispersionForce::setAwater(double inputAwater) { awater = inputAwater; } void AmoebaWcaDispersionForce::setShctd(double inputShctd) { shctd = inputShctd; } void AmoebaWcaDispersionForce::setDispoff(double inputDispoff) { dispoff = inputDispoff; } void AmoebaWcaDispersionForce::setSlevy(double inputSlevy) { slevy = inputSlevy; } ForceImpl* AmoebaWcaDispersionForce::createImpl() const { return new AmoebaWcaDispersionForceImpl(*this); } void AmoebaWcaDispersionForce::updateParametersInContext(Context& context) { dynamic_cast<AmoebaWcaDispersionForceImpl&>(getImplInContext(context)).updateParametersInContext(getContextImpl(context)); }
37.153285
126
0.616699
merkys
bb32644997946e6a4025f9719b3aa0c385636be7
5,265
cpp
C++
source/GeomUtils.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
2
2018-01-11T13:00:14.000Z
2018-01-12T02:02:16.000Z
source/GeomUtils.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
null
null
null
source/GeomUtils.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
null
null
null
#include "GeomUtils.h" namespace nest { using namespace std; bool GeomUtils::BSBS(Vector4 &center0, float radius0, Vector4 &center1, float radius1) { float x = center0.x - center1.x; float y = center0.y - center1.y; float z = center0.z - center1.z; return (x * x + y * y + z * z) <= (radius0 + radius1) * (radius0 + radius1); } bool GeomUtils::AABBBS(Vector4 &max, Vector4 &min, Vector4 &center, float radius) { float x = center.x; float y = center.y; float z = center.z; if(x < min.x) x = min.x; else if(x > max.x) x = max.x; if(y < min.y) y = min.y; else if(y > max.y) y = max.y; if(z < min.z) z = min.z; else if(z > max.z) z = max.z; x -= center.x; y -= center.y; z -= center.z; return (x * x + y * y + z * z) <= (radius * radius); } bool GeomUtils::AABBAABB(Vector4 &max0, Vector4 &min0, Vector4 &max1, Vector4 &min1) { if(min0.x > max1.x) return false; if(max0.x < min1.x) return false; if(min0.y > max1.y) return false; if(max0.y < min1.y) return false; if(min0.z > max1.z) return false; if(max0.z < min1.z) return false; return true; } bool GeomUtils::rayBS(Vector4 &result, Vector4 &orgion, Vector4 &delta, Vector4 &center, float radius) { Vector4 e = center - orgion; float lens = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; float len = sqrt(lens); float a = e * delta / len; float f = radius * radius - lens + a * a; if(f < 0) return false; f = a - sqrt(f); if(f > len || f < 0) return false; result = delta * f + orgion; return true; } bool GeomUtils::rayAABB(Vector4 &result, Vector4 &orgion, Vector4 &delta, Vector4 &max, Vector4 &min) { bool inside = true; float xt, xn; if(orgion.x < min.x) { xt = min.x - orgion.x; if(xt > delta.x) return false; xt /= delta.x; inside = false; xn = -1; } else if(orgion.x > max.x) { xt = max.x - orgion.x; if(xt < delta.x) return false; xt /= delta.x; inside = false; xn = 1; } else { xt = -1; } float yt, yn; if(orgion.y < min.y) { yt = min.y - orgion.y; if(yt > delta.y) return false; yt /= delta.y; inside = false; yn = -1; } else if(orgion.y > max.y) { yt = max.y - orgion.y; if(yt < delta.y) return false; yt /= delta.y; inside = false; yn = 1; } else { yt = -1; } float zt, zn; if(orgion.z < min.z) { zt = min.z - orgion.z; if(zt > delta.z) return false; zt /= delta.z; inside = false; zn = -1; } else if(orgion.z > max.z) { zt = max.z - orgion.z; if(zt < delta.z) return false; zt /= delta.z; inside = false; zn = 1; } else { zt = -1; } if(inside) return false; int which = 0; float t = xt; if(yt > t) { which = 1; t = yt; } if(zt > t) { which = 2; t = zt; } float x, y, z; switch(which) { case 0: // yz y = orgion.y + delta.y * t; if (y < min.y || y > max.y) return false; z = orgion.z + delta.z * t; if (z < min.z || z > max.z) return false; break; case 1: // xz x = orgion.x + delta.x * t; if (x < min.x || x > max.x) return false; z = orgion.z + delta.z * t; if (z < min.z || z > max.z) return false; break; case 2: // xy x = orgion.x + delta.x * t; if (x < min.x || x > max.x) return false; y = orgion.y + delta.y * t; if (y < min.y || y > max.y) return false; break; } result = delta * t + orgion; return true; } bool GeomUtils::rayTri(float* t, float* u, float* v, Vector4 &orgion, Vector4 &delta, Vector4 &p0, Vector4 &p1, Vector4 &p2) { Vector4 e1 = p1 - p0; Vector4 e2 = p2 - p0; Vector4 p = Vector4::crossProduct(delta, e2); float det = e1 * p; if(det < 0.0001f) return false; Vector4 t0 = orgion - p0; Vector4 q = Vector4::crossProduct(t0, e1); float ivt = 1.0f / det; *t = e2 * q; *t *= ivt; if(u != NULL) { *u = t0 * p; if(*u < 0.0f || *u > det) return false; *v = delta * q; if(*v < 0.0f || *u + *v > det) return false; *u *= ivt; *v *= ivt; } return true; } bool GeomUtils::rayGeom(vector<RayGeomResult> *results, RayGeomResult *result, bool uv, Vector4 &orgion, Vector4 &delta, Geometry &geom) { Vector4 vt1; if(!rayAABB(vt1, orgion, delta, geom.bound.max, geom.bound.min)) return false; bool flag = result != NULL; RayGeomResult current; Vector4 p0, p1, p2; float t, u, v; int i, j, k; for(i = 0; i < geom.numTris; i++) { j = i * 3; k = geom.indexData[j] * 3; p0.x = geom.vertexData[k]; p0.y = geom.vertexData[k + 1]; p0.z = geom.vertexData[k + 2]; k = geom.indexData[j + 1] * 3; p1.x = geom.vertexData[k]; p1.y = geom.vertexData[k + 1]; p1.z = geom.vertexData[k + 2]; k = geom.indexData[j + 2] * 3; p2.x = geom.vertexData[k]; p2.y = geom.vertexData[k + 1]; p2.z = geom.vertexData[k + 2]; if(rayTri(&t, uv ? &u : NULL, uv ? &v : NULL, orgion, delta, p0, p1, p2)) { current.t = t; current.index = geom.indexData[j]; if(uv) { current.u = u; current.v = v; } if(flag) { *result = current; return true; } else results->push_back(current); } } return flag ? false : results->size() > 0; } }
21.577869
137
0.545109
sindney
bb342ca2cd0cdefd902e65dc12fba3aa83fdff98
237
cpp
C++
src/0081/0081-Search-In-Rotated-Sorted-Array-II.cpp
coldnew/leetcode-solutions
3bc7943f8341397840ecd34aefc5af6e52b09b4e
[ "Unlicense" ]
2
2022-03-10T17:06:18.000Z
2022-03-11T08:52:00.000Z
src/0081/0081-Search-In-Rotated-Sorted-Array-II.cpp
coldnew/leetcode-solutions
3bc7943f8341397840ecd34aefc5af6e52b09b4e
[ "Unlicense" ]
null
null
null
src/0081/0081-Search-In-Rotated-Sorted-Array-II.cpp
coldnew/leetcode-solutions
3bc7943f8341397840ecd34aefc5af6e52b09b4e
[ "Unlicense" ]
null
null
null
#include <vector> #include "leetcode_utils.h" using namespace std; class Solution1 { public: bool search(vector<int>& nums, int target) { for (auto& n : nums) if (n == target) return true; return false; } };
15.8
46
0.616034
coldnew
bb3489a82893551a049dea1fc46cea0e9af79823
123
hpp
C++
addons/qstore/configs/CfgWeapons.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/qstore/configs/CfgWeapons.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/qstore/configs/CfgWeapons.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
class CfgWeapons { class Default; #include "weapons/ExtrasOptions.hpp" #include "weapons/GrenadeOptions.hpp" };
24.6
41
0.715447
SOCOMD
7d68c31b97696dd78d4a5ecf9eee213df7d2cade
6,224
cpp
C++
src/Renderer.cpp
MetalYos/3DModeler
ea8d50571dbd715c5f004360d26356a179e5862f
[ "MIT" ]
null
null
null
src/Renderer.cpp
MetalYos/3DModeler
ea8d50571dbd715c5f004360d26356a179e5862f
[ "MIT" ]
null
null
null
src/Renderer.cpp
MetalYos/3DModeler
ea8d50571dbd715c5f004360d26356a179e5862f
[ "MIT" ]
null
null
null
#include "Renderer.h" Renderer::~Renderer() { destroyBuffers(); } void Renderer::Init(int width, int height) { m_Width = width; m_Height = height; setAspectRatio(); initBuffers(); isInit = true; } /*----------------------------------------- Getters -----------------------------------------*/ bool Renderer::IsInit() const { return isInit; } int Renderer::GetWidth() const { return m_Width; } int Renderer::GetHeight() const { return m_Height; } double Renderer::GetAspectRation() const { return m_AspectRatio; } RendererColor Renderer::GetPixel(int x, int y) const { if (x < 0 || x >= m_Width) return { 0, 0, 0 }; if (y < 0 || y >= m_Height) return { 0, 0, 0 }; RendererColor color; color.R = m_FrameBuffer[x * 3 + m_Width * y * 3]; color.G = m_FrameBuffer[x * 3 + m_Width * y * 3 + 1]; color.B = m_FrameBuffer[x * 3 + m_Width * y * 3 + 2]; return color; } unsigned char* Renderer::GetFrameBuffer() { return m_FrameBuffer; } /*----------------------------------------- Setters -----------------------------------------*/ void Renderer::SetWidth(int width) { m_Width = width; setAspectRatio(); destroyBuffers(); initBuffers(); } void Renderer::SetHeight(int height) { m_Height = height; setAspectRatio(); destroyBuffers(); initBuffers(); } /*-------------------------------------- Draw Methods ---------------------------------------*/ void Renderer::DrawBackground(const RendererColor& color) { int size = m_Width * m_Height; for (int i = 0; i < size; i++) { m_FrameBuffer[i * 3] = color.R; m_FrameBuffer[i * 3 + 1] = color.G; m_FrameBuffer[i * 3 + 2] = color.B; } } void Renderer::DrawBackground(const RendererGradientColor& gradient) { auto locations = gradient.GetLocations(); auto colors = gradient.GetColors(); unsigned int index = 0; for (int y = 0; y < m_Height; y++) { for (int x = 0; x < m_Width; x++) { unsigned int nextIndex = (index == gradient.GetLocations().size() - 1) ? index : index + 1; double location0 = locations[index]; double location1 = locations[nextIndex]; RendererColor color0 = colors[index]; RendererColor color1 = colors[nextIndex]; double t = ((double)y - (location0 * m_Height)) / ((location1 * m_Height) - (location0 * m_Height)); RendererColor color; color.R = color0.R * (1.0 - t) + color1.R * t; color.G = color0.G * (1.0 - t) + color1.G * t; color.B = color0.B * (1.0 - t) + color1.B * t; DrawPixel(x, y, color); if ((1.0 - t) < AL_DBL_EPSILON) index++; } } } void Renderer::DrawPixel(int x, int y, const RendererColor& color) { if (x < 0 || x >= m_Width) return; if (y < 0 || y >= m_Height) return; m_FrameBuffer[x * 3 + m_Width * y * 3] = color.R; m_FrameBuffer[x * 3 + m_Width * y * 3 + 1] = color.G; m_FrameBuffer[x * 3 + m_Width * y * 3 + 2] = color.B; } void Renderer::DrawPixel(int x, int y, const RendererColor& color, int thickness) { if (thickness == 0) DrawPixel(x, y, color); else { // Draw thickness int startX = x; int endX = x; int startY = y; int endY = y; for (int i = thickness; i > 0; i--) { if ((startX == x) && (x - i >= 0)) startX = x - i; if ((endX == x) && (x + i < m_Width)) endX = x + i; if ((startY == y) && (y - i >= 0)) startY = y - i; if ((endY == y) && (y + i < m_Height)) endY = y + i; } for (int xPix = startX; xPix <= endX; xPix++) { for (int yPix = startY; yPix <= endY; yPix++) DrawPixel(xPix, yPix, color); } } } void Renderer::DrawLine(const Vec4& p0, const Vec4& p1, const RendererColor& color, int thickness) { int x1 = (int)p0[0]; int y1 = (int)p0[1]; int x2 = (int)p1[0]; int y2 = (int)p1[1]; int delta_x(x2 - x1); // if x1 == x2, then it does not matter what we set here signed char const ix((delta_x > 0) - (delta_x < 0)); delta_x = std::abs(delta_x) << 1; int delta_y(y2 - y1); // if y1 == y2, then it does not matter what we set here signed char const iy((delta_y > 0) - (delta_y < 0)); delta_y = std::abs(delta_y) << 1; DrawPixel(x1, y1, color, thickness); if (delta_x >= delta_y) { // error may go below zero int error(delta_y - (delta_x >> 1)); while (x1 != x2) { // reduce error, while taking into account the corner case of error == 0 if ((error > 0) || (!error && (ix > 0))) { error -= delta_x; y1 += iy; } // else do nothing error += delta_y; x1 += ix; DrawPixel(x1, y1, color, thickness); } } else { // error may go below zero int error(delta_x - (delta_y >> 1)); while (y1 != y2) { // reduce error, while taking into account the corner case of error == 0 if ((error > 0) || (!error && (iy > 0))) { error -= delta_y; x1 += ix; } // else do nothing error += delta_x; y1 += iy; DrawPixel(x1, y1, color, thickness); } } } /*------------------------------------- Private Methods -------------------------------------*/ void Renderer::setAspectRatio() { if (m_Height == 0) m_AspectRatio = 1.0; else m_AspectRatio = (double)m_Width / (double)m_Height; } void Renderer::initBuffers() { initFrameBuffer(); initZBuffer(); } void Renderer::initFrameBuffer() { int size = m_Width * m_Height * 3; m_FrameBuffer = new unsigned char[size]; for (int i = 0; i < size; i++) { m_FrameBuffer[i] = 0; } } void Renderer::initZBuffer() { int size = m_Width * m_Height; m_ZBuffer = new double[size]; } void Renderer::destroyBuffers() { if (m_FrameBuffer != nullptr) delete[] m_FrameBuffer; if (m_ZBuffer != nullptr) delete[] m_ZBuffer; }
24.124031
112
0.508515
MetalYos
7d68c52fc885cd20e77dda22f02e1852a0bfd277
34
hpp
C++
src/boost_timer_config.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_timer_config.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_timer_config.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/timer/config.hpp>
17
33
0.764706
miathedev
7d6a10c32b20c50b10da41e4826aa291fdccfe00
1,833
cpp
C++
Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/gamepad.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
45
2017-07-24T05:31:06.000Z
2019-03-29T12:23:57.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/gamepad.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
7
2019-01-14T14:46:46.000Z
2019-01-25T20:57:05.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/gamepad.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
10
2017-07-24T02:11:43.000Z
2018-12-27T20:49:37.000Z
/******************************************************************************/ /* Mednafen NEC PC-FX Emulation Module */ /******************************************************************************/ /* gamepad.cpp: ** Copyright (C) 2006-2016 Mednafen Team ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the GNU General Public License ** as published by the Free Software Foundation; either version 2 ** of the License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software Foundation, Inc., ** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "../pcfx.h" #include "../input.h" #include "gamepad.h" namespace MDFN_IEN_PCFX { class PCFX_Input_Gamepad : public PCFX_Input_Device { public: PCFX_Input_Gamepad() { buttons = 0; } virtual ~PCFX_Input_Gamepad() override { } virtual uint32 ReadTransferTime(void) override { return 1536; } virtual uint32 WriteTransferTime(void) override { return 1536; } virtual uint32 Read(void) override { return buttons | FX_SIG_PAD << 28; } virtual void Write(uint32 data) override { } virtual void Power(void) override { buttons = 0; } virtual void Frame(uint32_t data) override { buttons = data; } private: // 5....098 7......0 // m mldru rs654321 uint16 buttons; }; PCFX_Input_Device *PCFXINPUT_MakeGamepad(void) { return new PCFX_Input_Gamepad(); } }
22.62963
80
0.637752
redscientistlabs
7d6afb61fb2fd326afbcd061baef925287502f92
543
cpp
C++
src/gameobjects/room.cpp
Pfeifenjoy/Theseus
9b427c16deaaacfff2e174e3dd133feed9724d3b
[ "MIT" ]
6
2016-10-28T15:39:09.000Z
2019-04-16T09:00:03.000Z
src/gameobjects/room.cpp
Pfeifenjoy/Theseus
9b427c16deaaacfff2e174e3dd133feed9724d3b
[ "MIT" ]
null
null
null
src/gameobjects/room.cpp
Pfeifenjoy/Theseus
9b427c16deaaacfff2e174e3dd133feed9724d3b
[ "MIT" ]
6
2017-02-22T17:25:32.000Z
2021-02-03T19:17:06.000Z
#include "room.hpp" #include "../engine/texturemanager.hpp" using namespace std; using namespace theseus::engine; using namespace theseus::gameobjects; Room::Room(sf::Vector2f size) { sf::Texture *texture; texture = &TextureManager::instance().getTexture("floor_red.png"); setTexture(0, *texture); // Repeat texture if nessesary texture->setRepeated(true); //Set size of the wall IntRect(startposition x, startposition y, length x, height y) this->sprite(0).setTextureRect(sf::IntRect(0, 0, size.x, size.y)); } Room::~Room() {}
22.625
85
0.721915
Pfeifenjoy
7d724c41cd6ea5052177b2e7b181d5eb11bb4e9e
364
cc
C++
05/io.cc
sandeep-krishnamurthy/cpp_from_scratch
e1c5f339c3c6ff81ff3e460edc942acbcf834582
[ "Apache-2.0" ]
2
2018-11-30T17:57:35.000Z
2018-11-30T18:13:09.000Z
05/io.cc
sandeep-krishnamurthy/cpp_from_scratch
e1c5f339c3c6ff81ff3e460edc942acbcf834582
[ "Apache-2.0" ]
null
null
null
05/io.cc
sandeep-krishnamurthy/cpp_from_scratch
e1c5f339c3c6ff81ff3e460edc942acbcf834582
[ "Apache-2.0" ]
1
2018-11-30T18:13:14.000Z
2018-11-30T18:13:14.000Z
#include <iostream> /* * Read integer from terminal */ int read_integer() { int input; std::cin >> input; return input; } /* * Read Float from terminal */ int read_float() { float input; std::cin >> input; return input; } /* * Read Char from terminal */ int read_char() { char input; std::cin >> input; return input; }
11.741935
30
0.582418
sandeep-krishnamurthy
7d74521ae7f4718efcf775474f825c935ebbec25
5,312
cpp
C++
test/encoding/encoding_test.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
test/encoding/encoding_test.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
test/encoding/encoding_test.cpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * buffers_test.cpp * * Created on: Dec 14, 2015 * Author: zmij */ #include <gtest/gtest.h> #include <wire/encoding/buffers.hpp> #include <wire/encoding/detail/fixed_size_io.hpp> #include <vector> #include <type_traits> namespace wire { namespace encoding { namespace test { template< typename T > class buffer_io_test : public ::testing::TestWithParam< T > { protected: typedef std::vector<uint8_t> buffer_type; typedef buffer_type::const_iterator input_iterator; typedef std::back_insert_iterator<buffer_type> output_iterator; typedef detail::writer< T > writer_type; typedef detail::reader< T > reader_type; buffer_type buffer; }; #define BUFFER_IO_TEST(the_type, generator) \ typedef buffer_io_test< the_type > the_type##_io_test; \ TEST_P(the_type##_io_test, IOTest) \ { \ ParamType v = GetParam(); \ ParamType e; \ \ writer_type::output(std::back_inserter(buffer), v); \ std::cerr << "Value " << v << " Buffer size " << buffer.size() << "\n"; \ auto begin = buffer.begin(); \ reader_type::input(begin, buffer.end(), e); \ EXPECT_EQ(v, e); \ EXPECT_EQ(begin, buffer.end()); \ } \ INSTANTIATE_TEST_CASE_P(BufferIO, the_type##_io_test, generator) //@{ /** @name Varint io */ BUFFER_IO_TEST(uint16_t, ::testing::Values(0, 1, 2, 4, 8, 16, 100, 1024, 4096, std::numeric_limits<uint16_t>::max()) ); BUFFER_IO_TEST(int16_t, ::testing::Values(-1, -5, -1800, 0, 1, 2, 16, 100, 4096, std::numeric_limits<int16_t>::max(), std::numeric_limits<int16_t>::min()) ); BUFFER_IO_TEST(uint32_t, ::testing::Values(0, 1, 2, 4, 8, 16, 100, 1024, 4096, std::numeric_limits<uint32_t>::max())); BUFFER_IO_TEST(int32_t, ::testing::Values(0, 1, 2, -1, -5, 16, 100, -1800, 4096, std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::min())); BUFFER_IO_TEST(uint64_t, ::testing::Values(0, 1, 2, 4, 8, 16, 100, 1024, 4096, std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint64_t>::max())); BUFFER_IO_TEST(int64_t, ::testing::Values(0, 1, 2, -1, -5, 16, 100, -1800, 4096, std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::min(), std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::min())); typedef detail::wire_types wire_types_enum; BUFFER_IO_TEST(wire_types_enum, ::testing::Values( detail::SCALAR_VARINT, detail::SCALAR_FIXED) ); enum class test_enumeration { val0, val2 = 2, val3 }; std::ostream& operator << (std::ostream& os, test_enumeration val) { std::ostream::sentry s(os); if (s) { os << static_cast<std::underlying_type<test_enumeration>::type>(val); } return os; } BUFFER_IO_TEST(test_enumeration, ::testing::Values( test_enumeration::val0, test_enumeration::val2, test_enumeration::val3) ); //@} //@{ /** @name Fixed size values */ BUFFER_IO_TEST(bool, ::testing::Values(true, false)); BUFFER_IO_TEST(char, ::testing::Values(0, '0', 'a', 'B', '=', '*')); typedef unsigned char uchar; BUFFER_IO_TEST(uchar, ::testing::Values(0, '0', 'a', 'B', '=', '*')); BUFFER_IO_TEST(uint8_t, ::testing::Values(0, '0', 'a', 'B', '=', '*')); BUFFER_IO_TEST(int8_t, ::testing::Values(0, '0', 'a', 'B', '=', '*')); BUFFER_IO_TEST(float, ::testing::Values(0, 1, -3.14, std::numeric_limits<float>::min(), std::numeric_limits<float>::max(), std::numeric_limits<float>::epsilon(), std::numeric_limits<float>::lowest())); BUFFER_IO_TEST(double, ::testing::Values(0, 1, -3.14, std::numeric_limits<float>::min(), std::numeric_limits<float>::max(), std::numeric_limits<float>::epsilon(), std::numeric_limits<float>::lowest(), std::numeric_limits<double>::min(), std::numeric_limits<double>::max(), std::numeric_limits<double>::epsilon(), std::numeric_limits<double>::lowest())); typedef long double long_double; BUFFER_IO_TEST(long_double, ::testing::Values(0, 1, -3.14, std::numeric_limits<float>::min(), std::numeric_limits<float>::max(), std::numeric_limits<float>::epsilon(), std::numeric_limits<float>::lowest(), std::numeric_limits<double>::min(), std::numeric_limits<double>::max(), std::numeric_limits<double>::epsilon(), std::numeric_limits<double>::lowest(), std::numeric_limits<long double>::min(), std::numeric_limits<long double>::max(), std::numeric_limits<long double>::epsilon(), std::numeric_limits<long double>::lowest())); BUFFER_IO_TEST(uint32_fixed_t, ::testing::Values(0, 1, 2, 4, 8, 16, 100, 1024, 4096, std::numeric_limits<uint32_t>::max())); BUFFER_IO_TEST(int32_fixed_t, ::testing::Values(0, 1, 2, -1, -5, 16, 100, -1800, 4096, std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::min())); BUFFER_IO_TEST(uint64_fixed_t, ::testing::Values(0, 1, 2, 4, 8, 16, 100, 1024, 4096, std::numeric_limits<uint32_t>::max(), std::numeric_limits<uint64_t>::max())); BUFFER_IO_TEST(int64_fixed_t, ::testing::Values(0, 1, 2, -1, -5, 16, 100, -1800, 4096, std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::min(), std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::min())); //@} //@{ /** @name string io */ typedef std::string std_string; BUFFER_IO_TEST(std_string, ::testing::Values( "", " ", "abcdABCD", "+-!@#%^&", "абвгАБВГ", "こんにちはテスト", "メッセージ", "안녕하세요 테스트", "你好测试", "Waſſerschloſʒ", "Wasserschloß" ) ); //@} } // namespace test } // namespace encoding } // namespace wire
32.193939
92
0.677711
zmij
7d74bbb6c9d84a6c21a561e9c3b39292614a0dc2
1,567
cc
C++
third_party/blink/renderer/core/timing/performance_paint_timing.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/core/timing/performance_paint_timing.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/core/timing/performance_paint_timing.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/timing/performance_paint_timing.h" #include "third_party/blink/renderer/bindings/core/v8/v8_object_builder.h" #include "third_party/blink/renderer/core/performance_entry_names.h" namespace blink { namespace { AtomicString FromPaintTypeToString(PerformancePaintTiming::PaintType type) { DCHECK(IsMainThread()); switch (type) { case PerformancePaintTiming::PaintType::kFirstPaint: { DEFINE_STATIC_LOCAL(const AtomicString, kFirstPaint, ("first-paint")); return kFirstPaint; } case PerformancePaintTiming::PaintType::kFirstContentfulPaint: { DEFINE_STATIC_LOCAL(const AtomicString, kFirstContentfulPaint, ("first-contentful-paint")); return kFirstContentfulPaint; } } NOTREACHED(); return g_empty_atom; } } // namespace PerformancePaintTiming::PerformancePaintTiming(PaintType type, double start_time) : PerformanceEntry(FromPaintTypeToString(type), start_time, start_time) {} PerformancePaintTiming::~PerformancePaintTiming() = default; AtomicString PerformancePaintTiming::entryType() const { return performance_entry_names::kPaint; } PerformanceEntryType PerformancePaintTiming::EntryTypeEnum() const { return PerformanceEntry::EntryType::kPaint; } } // namespace blink
31.34
76
0.719847
zealoussnow
7d7b54062f9a6d0db7349bfa766fda19f9f4a33c
1,723
cc
C++
test/segment_patch_test.cc
WuJoel2020/aom
65e6b6954c45c1b12883942b14d1988da377e0cd
[ "BSD-2-Clause" ]
null
null
null
test/segment_patch_test.cc
WuJoel2020/aom
65e6b6954c45c1b12883942b14d1988da377e0cd
[ "BSD-2-Clause" ]
null
null
null
test/segment_patch_test.cc
WuJoel2020/aom
65e6b6954c45c1b12883942b14d1988da377e0cd
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2019, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include "av1/encoder/segment_patch.h" #include "third_party/googletest/src/googletest/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/i420_video_source.h" namespace { const int kNumFrames = 10; } // namespace // Test av1_get_segments() API. TEST(SegmentPatchTest, get_segments) { libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 1, 30, 0, kNumFrames); Av1SegmentParams params; av1_get_default_segment_params(&params); std::unique_ptr<uint8_t> output; ASSERT_NO_FATAL_FAILURE(video.Begin()); for (int i = 0; i < kNumFrames; ++i) { const aom_image_t *frame = video.img(); ASSERT_TRUE(frame != nullptr) << "Could not read frame# " << i << " from source video"; if (i == 0) { // Allocate output buffer. output.reset(new uint8_t[frame->w * frame->h]); } int num_components = -1; av1_get_segments(frame->planes[0], frame->w, frame->h, frame->stride[0], &params, output.get(), &num_components); ASSERT_GT(num_components, 0); printf("Segmented frame# %d: num_components = %d\n", i, num_components); video.Next(); } }
35.895833
80
0.68137
WuJoel2020
7d7f3382877a0bc88ce686c957f828082adf235f
4,088
cpp
C++
engine/src/core/window.cpp
JackiBackiBoy/ox3d
a96e41b8a6886b0e8fa811e500718b6e457b162d
[ "Apache-2.0" ]
1
2022-02-24T21:19:25.000Z
2022-02-24T21:19:25.000Z
engine/src/core/window.cpp
JackiBackiBoy/ox3d
a96e41b8a6886b0e8fa811e500718b6e457b162d
[ "Apache-2.0" ]
null
null
null
engine/src/core/window.cpp
JackiBackiBoy/ox3d
a96e41b8a6886b0e8fa811e500718b6e457b162d
[ "Apache-2.0" ]
null
null
null
#include "window.h" #include <iostream> #include <vector> #include "rendering/model.h" #include "input/keyboard.h" #include "input/mouse.h" #include "ui/uiFont.h" using namespace ox; Window::Window(const uint32_t& width, const uint32_t& height, const std::string& title) : m_Width(width), m_Height(height), m_Title(title) { createWindow(); m_GraphicsManager = new GraphicsManager(); } void Window::createWindow() { glfwInit(); // initialize glfw // set GLFW options glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); m_RawWindow = glfwCreateWindow(m_Width, m_Height, m_Title.c_str(), nullptr, nullptr); glfwSetWindowUserPointer(m_RawWindow, &m_GraphicsManager); glfwSetFramebufferSizeCallback(m_RawWindow, m_GraphicsManager->onResize); glfwSetInputMode(m_RawWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSwapInterval(1); glfwSetCursorPosCallback(m_RawWindow, Mouse::onMouseMove); glfwSetScrollCallback(m_RawWindow, Mouse::onMouseScroll); } void Window::onStart() { // Shaders m_Shader.loadVertexShader("assets/shaders/lightingShader.vert.spv"); m_Shader.loadFragmentShader("assets/shaders/lightingShader.frag.spv"); m_GraphicsManager->addShader(&m_Shader); // Models Model waterbottle; waterbottle.loadFromFile("assets/models/waterbottle/WaterBottle.gltf"); m_GraphicsManager->submitModel(waterbottle); m_GraphicsManager->m_Vertices = waterbottle.getVertices(); m_GraphicsManager->m_Indices = waterbottle.getIndices(); // Camera m_Camera = Camera(); m_Camera.setPosition({ 0.0f, 0.0f, 2.0f }); m_Camera.setYaw(90.0f); m_Camera.setFOV(60.0f); // User Interface UIFont font; font.loadFromFile("assets/fonts/segoeui.ttf", 12); } void Window::onUpdate(const float& deltaTime) { // ------ Rotation with mouse ------ glm::vec2 mousePos = Mouse::getPosition(); // Fix for preventing violent camera rotation before // or during the initial movement with the mouse if (!Mouse::hasMoved || Mouse::firstMove) { lastMousePos = mousePos; } glm::vec2 deltaMousePos = mousePos - lastMousePos; m_Camera.setYaw(m_Camera.getYaw() + 0.05f * deltaMousePos.x); m_Camera.setPitch(m_Camera.getPitch() + 0.05f * deltaMousePos.y); glm::vec3 camPos = m_Camera.getPosition(); glm::vec3 camRight = m_Camera.getRight(); glm::vec3 camUp = m_Camera.getUp(); glm::vec3 camForward = m_Camera.getForward(); // ------ Mouse scrolling ------ float scrollDir = Mouse::getVerticalScroll(); if (scrollDir != 0.0f) { m_Camera.setFOV(m_Camera.getFOV() - scrollDir); } // ------ Keyboard movement ------ // Move forwards if (Keyboard::isKeyDown(KeyCode::W)) { m_Camera.setPosition(camPos + camForward * deltaTime * 3.0f); } // Move horizontally to the left if (Keyboard::isKeyDown(KeyCode::A)) { m_Camera.setPosition(camPos - camRight * deltaTime * 3.0f); } // Move backwards if (Keyboard::isKeyDown(KeyCode::S)) { m_Camera.setPosition(camPos - camForward * deltaTime * 3.0f); } // Move horizontally to the right if (Keyboard::isKeyDown(KeyCode::D)) { m_Camera.setPosition(camPos + camRight * deltaTime * 3.0f); } // Move upwards if (Keyboard::isKeyDown(KeyCode::Space)) { m_Camera.setPosition({ camPos.x, camPos.y + deltaTime * 3.0f, camPos.z }); } // Move downwards if (Keyboard::isKeyDown(KeyCode::LeftControl)) { m_Camera.setPosition({ camPos.x, camPos.y - deltaTime * 3.0f, camPos.z }); } m_Camera.update(); lastMousePos = mousePos; } void Window::onRender() { } void Window::run() { Window::onStart(); onStart(); m_GraphicsManager->loadVulkan(); // Rendering loop float deltaTime = 0.0f; while (!glfwWindowShouldClose(m_RawWindow)) { float t0 = static_cast<float>(glfwGetTime()); glfwPollEvents(); m_GraphicsManager->renderFrame(); Window::onUpdate(deltaTime); onUpdate(deltaTime); deltaTime = static_cast<float>(glfwGetTime()) - t0; } // onExit m_GraphicsManager->destroyVulkan(); glfwDestroyWindow(m_RawWindow); glfwTerminate(); } Window* Window::currentWindow = nullptr;
27.436242
87
0.705724
JackiBackiBoy
7d817da41723ebe764e2e9a007dd8fc31afdceae
834
hpp
C++
matrix/linear-equation.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
matrix/linear-equation.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
matrix/linear-equation.hpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#pragma once #include "gauss-elimination.hpp" template <typename mint> vector<vector<mint>> LinearEquation(vector<vector<mint>> a, vector<mint> b) { int H = a.size(), W = a[0].size(); for (int i = 0; i < H; i++) a[i].push_back(b[i]); auto p = GaussElimination(a, W, true); int rank = p.first; for (int i = rank; i < H; ++i) { if (a[i][W] != 0) return vector<vector<mint>>{}; } vector<vector<mint>> res(1, vector<mint>(W)); vector<int> pivot(W, -1); for (int i = 0, j = 0; i < rank; ++i) { while (a[i][j] == 0) ++j; res[0][j] = a[i][W], pivot[j] = i; } for (int j = 0; j < W; ++j) { if (pivot[j] == -1) { vector<mint> x(W); x[j] = 1; for (int k = 0; k < j; ++k) { if (pivot[k] != -1) x[k] = -a[pivot[k]][j]; } res.push_back(x); } } return res; }
23.828571
77
0.492806
NachiaVivias
7d8289ffc393b5fbc3922f08f321372494bf5cd6
1,808
cpp
C++
breath/meta/test/is_2s_complement_test.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
breath/meta/test/is_2s_complement_test.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
breath/meta/test/is_2s_complement_test.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
// =========================================================================== // This is an open source non-commercial project. // Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: // http://www.viva64.com // =========================================================================== // Copyright 2020 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ #include "breath/meta/is_2s_complement.hpp" #include "breath/testing/testing.hpp" int test_is_2s_complement() ; using breath::meta::is_2s_complement ; namespace { // This is actually a compile-time test. But we turn it into a // runtime test, at least for now, so that we get a report. // --------------------------------------------------------------------------- void do_test() { using breath::meta::is_2s_complement ; static_assert( ! is_2s_complement< bool >(), "" ) ; static_assert( is_2s_complement< signed char >(), "" ) ; static_assert( ! is_2s_complement< unsigned char >(), "" ) ; static_assert( is_2s_complement< int >(), "" ) ; static_assert( ! is_2s_complement< unsigned int >(), "" ) ; } } int test_is_2s_complement() { using namespace breath ; return test_runner::instance().run( "is_2s_complement()", { do_test } ) ; } // Local Variables: // mode: c++ // indent-tabs-mode: nil // c-basic-offset: 4 // End: // vim: set ft=cpp et sts=4 sw=4:
31.719298
78
0.522677
erez-o
7d82d7de9c6fd605a2ded04360c69ac156858fee
6,507
tcc
C++
flens/blas/closures/level2/mvswitch.tcc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
98
2015-01-26T20:31:37.000Z
2021-09-09T15:51:37.000Z
flens/blas/closures/level2/mvswitch.tcc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
16
2015-01-21T07:43:45.000Z
2021-12-06T12:08:36.000Z
flens/blas/closures/level2/mvswitch.tcc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
31
2015-01-05T08:06:45.000Z
2022-01-26T20:12:00.000Z
/* * Copyright (c) 2012, Michael Lehn * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3) Neither the name of the FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef FLENS_BLAS_CLOSURES_LEVEL2_MVSWITCH_TCC #define FLENS_BLAS_CLOSURES_LEVEL2_MVSWITCH_TCC 1 #include <flens/auxiliary/auxiliary.h> #include <flens/blas/closures/closures.h> #include <flens/blas/level1/level1.h> #include <flens/blas/level2/level2.h> #include <flens/blas/level3/level3.h> #include <flens/typedefs.h> #ifdef FLENS_DEBUG_CLOSURES # include <flens/blas/blaslogon.h> #else # include <flens/blas/blaslogoff.h> #endif namespace flens { namespace blas { // // This switch evaluates closures of the form // // y = beta*y + A*x // // If x is a closure then it gets evaluated and a temporary gets created to // store the result. For matrix A we distinguish between three cases: // case 1: A is no closure // case 2: A is a scaling closure (i.e. scale*A) // case 3: A is some other closure // // Entry point for mvSwitch // template <typename ALPHA, typename MA, typename VX, typename BETA, typename VY> typename RestrictTo<IsSame<MA, typename MA::Impl>::value && IsSame<VX, typename VX::Impl>::value && IsSame<VY, typename VY::Impl>::value, void>::Type mvSwitch(Transpose trans, const ALPHA &alpha, const MA &A, const VX &x, const BETA &beta, VY &y) { ASSERT(alpha==ALPHA(1) || alpha==ALPHA(-1)); // // If A is a closure then prune arbitrary many OpTrans/OpConj // typedef typename PruneConjTrans<MA>::Remainder RMA; trans = Transpose(trans^PruneConjTrans<MA>::trans); const RMA &A_ = PruneConjTrans<MA>::remainder(A); // // If x is a closure it gets evaluated. In this case a temporary gets // created. Otherwise we only keep a reference // FLENS_BLASLOG_TMP_TRON; const typename Result<VX>::Type &x_ = x; FLENS_BLASLOG_TMP_TROFF; // // Call mv implementation // mvCase(trans, alpha, A_, x_, beta, y); // // If a temporary was created and registered before we now unregister it // # ifdef FLENS_DEBUG_CLOSURES if (!IsSame<VX, typename Result<VX>::Type>::value) { FLENS_BLASLOG_TMP_REMOVE(x_, x); } # else const bool check = IsSame<VX, typename Result<VX>::Type>::value; if (!check) { std::cerr << "ERROR: Temporary required." << std::endl; } ASSERT(check); # endif } // // case 1: A is no closure // template <typename ALPHA, typename MA, typename VX, typename BETA, typename VY> typename RestrictTo<!IsClosure<MA>::value, void>::Type mvCase(Transpose trans, const ALPHA &alpha, const MA &A, const VX &x, const BETA &beta, VY &y) { mv(trans, alpha, A, x, beta, y); } // // case 2: A is closure of type scale*A // template <typename ALPHA, typename T, typename MA, typename VX, typename BETA, typename VY> void mvCase(Transpose trans, const ALPHA &alpha, const MatrixClosure<OpMult, ScalarValue<T>, MA> &scale_A, const VX &x, const BETA &beta, VY &y) { // // If A is a closure then prune arbitrary many OpTrans/OpConj // typedef typename PruneConjTrans<MA>::Remainder MA_; typedef typename Result<MA_>::Type RMA; Transpose trans_ = Transpose(trans^PruneConjTrans<MA>::trans); // // If the remaining A is a closure it gets evaluated. In this case // a temporary gets created. Otherwise we only keep a reference // FLENS_BLASLOG_TMP_TRON; const MA_ &A_ = PruneConjTrans<MA>::remainder(scale_A.right()); const RMA &A = A_; FLENS_BLASLOG_TMP_TROFF; mv(trans_, alpha*scale_A.left().value(), A, x, beta, y); // // If a temporary was created and registered before we now unregister it // # ifdef FLENS_DEBUG_CLOSURES if (!IsSame<MA_, RMA>::value) { FLENS_BLASLOG_TMP_REMOVE(A, A_); } # else const bool check = IsSame<MA_, RMA>::value; if (!check) { std::cerr << "ERROR: Temporary required." << std::endl; } ASSERT(check); # endif } // // case 3: A is some other closure // template <typename ALPHA, typename Op, typename L, typename R, typename VX, typename BETA, typename VY> void mvCase(Transpose trans, const ALPHA &alpha, const MatrixClosure<Op, L, R> &A, const VX &x, const BETA &beta, VY &y) { typedef MatrixClosure<Op, L, R> MC; // // Create (most certainly) temporary for the result of A // FLENS_BLASLOG_TMP_TRON; typedef typename Result<MC>::Type MA; const MA &A_ = A; FLENS_BLASLOG_TMP_TROFF; mv(trans, alpha, A_, x, beta, y); // // If a temporary was created and registered before we now unregister it // # ifdef FLENS_DEBUG_CLOSURES if (!IsSame<MC, MA>::value) { FLENS_BLASLOG_TMP_REMOVE(A_, A); } # else const bool check = IsSame<MC, MA>::value; if (!check) { std::cerr << "ERROR: Temporary required." << std::endl; } ASSERT(check); # endif } } } // namespace blas, flens #endif // FLENS_BLAS_CLOSURES_LEVEL2_MVSWITCH_TCC
31.897059
79
0.681113
stip
7d8416cc564537ada66cc5cd7a9ffb15664d331e
1,117
cpp
C++
108.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
1
2018-03-19T05:18:49.000Z
2018-03-19T05:18:49.000Z
108.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
null
null
null
108.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
null
null
null
//2012/03/22 //108.cpp //Run time: 0.008 #include <stdio.h> #define INF -2147483647 int sum[105][105]; int N; int Kadane(int *array){ static int i, max, sum; max = INF; for(sum=i=0; i<N; ++i){ sum += array[i]; if(sum < 0) sum = 0; else if(sum > max) max = sum; } return max; } int KadaneM(int *array, int *up){ static int i, max, sum; max = INF; for(sum=i=0; i<N; ++i){ sum += (array[i] - up[i]); if(sum < 0) sum = 0; else if(sum > max) max = sum; } return max; } int main(){ #ifndef ONLINE_JUDGE freopen("108.in", "r", stdin); freopen("108.out", "w", stdout); #endif int i, j, temp, MAX; int dp[105]; while(scanf("%d", &N) == 1){ for(j=0; j<N; ++j) scanf("%d", &sum[0][j]); MAX = Kadane(sum[0]); for(i=1; i<N; ++i){ for(j=0; j<N; ++j){ scanf("%d", &temp); sum[i][j] = temp + sum[i-1][j]; } temp = Kadane(sum[i]); if(temp > MAX) MAX = temp; for(j=0; j<i; ++j){ temp = KadaneM(sum[i], sum[j]); if(temp > MAX) MAX = temp; } } printf("%d\n", MAX); } return 0; }
16.426471
36
0.482543
abraxaslee
7d865997b7659ef789e0c81f435f330dd4c9c828
6,843
hxx
C++
com/ole32/com/dcomrem/chock.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/com/dcomrem/chock.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/com/dcomrem/chock.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------- // // File: chock.hxx // // Contents: APIs for channel hooks // //-------------------------------------------------------------------- #ifndef _CHOCK_HXX_ #define _CHOCK_HXX_ /***************************************************************************/ const DWORD MASK_A_C_ = 0xFF00FF00; const DWORD MASK__B_D = 0x00FF00FF; const DWORD MASK_AB__ = 0xFFFF0000; const DWORD MASK___CD = 0x0000FFFF; inline void ByteSwapLong( DWORD &l ) { // Start with ABCD. // First change it to BADC. l = ((l & MASK_A_C_) >> 8) | ((l & MASK__B_D) << 8); // Then change it to DCBA. l = ((l & MASK_AB__) >> 16) | ((l & MASK___CD) << 16); } /***************************************************************************/ inline void ByteSwapShort( unsigned short &s ) { s = ((s & 0x00FF) << 8) | ((s & 0xFF00) >> 8); } /***************************************************************************/ typedef struct { unsigned long rounded_size; // Actual number of extents. uuid_t id; // Extension identifier. unsigned long size; // Extension size. // byte data[]; // Extension data. } WireExtent; // Array of extensions #define UNIQUE_FLAG_PADDING 2 typedef struct { unsigned long size; // Number of extents. unsigned long reserved; // Must be zero. unsigned long unique; // Flag to indicate presence of unique_flag array. unsigned long rounded_size; // Actual number of extents. unsigned long unique_flag[UNIQUE_FLAG_PADDING]; // Flags to indicate presense of ORPC_EXTENTs } WireExtentArray; // These two structures are laid out to match the NDR wire represenation // of the type ORPCTHIS in obase.idl. typedef struct { COMVERSION version; // COM version number unsigned long flags; // ORPCF flags for presence of other data unsigned long reserved1; // set to zero CID cid; // causality id of caller unsigned long unique; // tag to indicate presence of extensions } WireThisPart1; typedef struct { WireThisPart1 part1; // Debug data. WireExtentArray ea; WireExtent e; } WireThisPart2; typedef union { WireThisPart1 c; WireThisPart2 d; } WireThis; // These two structures are laid out to match the NDR wire represenation // of the type ORPCTHAT in obase.idl. typedef struct { unsigned long flags; // ORPCF flags for presence of other data unsigned long unique; // tag to indicate presence of extensions } WireThatPart1; typedef struct { WireThatPart1 part1; // Debug data. WireExtentArray ea; WireExtent e; } WireThatPart2; typedef union { WireThatPart1 c; WireThatPart2 d; } WireThat; // // Definitions used to standardize Extent structure manipulations // #define SizeOfUniqueFlags(cNumExtents) (cNumExtents * sizeof (unsigned long)) #define SizeOfWireExtentArray (sizeof (WireExtentArray) - SizeOfUniqueFlags (UNIQUE_FLAG_PADDING)) #define SizeOfWireExtentArrayWithUniqueFlags(cNumExtents) \ (SizeOfWireExtentArray + SizeOfUniqueFlags (cNumExtents)) #define StartOfExtents(pArray, cNumExtents) \ (WireExtent *) ((char*) pArray + SizeOfWireExtentArrayWithUniqueFlags (cNumExtents)) //+---------------------------------------------------------------- // // Class: CDebugChannelHook, private // // Purpose: Translates channel hook calls to special calls the VC // debugger expects. // //----------------------------------------------------------------- class CDebugChannelHook : public IChannelHook { public: STDMETHOD (QueryInterface) ( REFIID riid, LPVOID FAR* ppvObj); STDMETHOD_(ULONG,AddRef) ( void ); STDMETHOD_(ULONG,Release) ( void ); STDMETHOD_(void,ClientGetSize) ( REFGUID, REFIID, ULONG *DataSize ); STDMETHOD_(void,ClientFillBuffer)( REFGUID, REFIID, ULONG *DataSize, void *DataBuffer ); STDMETHOD_(void,ClientNotify) ( REFGUID, REFIID, ULONG DataSize, void *DataBuffer, DWORD DataRep, HRESULT hrFault ); STDMETHOD_(void,ServerNotify) ( REFGUID, REFIID, ULONG DataSize, void *DataBuffer, DWORD DataRep ); STDMETHOD_(void,ServerGetSize) ( REFGUID, REFIID, HRESULT hrFault, ULONG *DataSize ); STDMETHOD_(void,ServerFillBuffer)( REFGUID, REFIID, ULONG *DataSize, void *DataBuffer, HRESULT hrFault ); }; //+---------------------------------------------------------------- // // Class: CErrorChannelHook, private // // Purpose: Channel hook for marshalling COM extended error // information. // //----------------------------------------------------------------- class CErrorChannelHook : public IChannelHook { public: STDMETHOD (QueryInterface) ( REFIID riid, LPVOID FAR* ppvObj); STDMETHOD_(ULONG,AddRef) ( void ); STDMETHOD_(ULONG,Release) ( void ); STDMETHOD_(void,ClientGetSize) ( REFGUID, REFIID, ULONG *DataSize ); STDMETHOD_(void,ClientFillBuffer)( REFGUID, REFIID, ULONG *DataSize, void *DataBuffer ); STDMETHOD_(void,ClientNotify) ( REFGUID, REFIID, ULONG DataSize, void *DataBuffer, DWORD DataRep, HRESULT hrFault ); STDMETHOD_(void,ServerNotify) ( REFGUID, REFIID, ULONG DataSize, void *DataBuffer, DWORD DataRep ); STDMETHOD_(void,ServerGetSize) ( REFGUID, REFIID, HRESULT hrFault, ULONG *DataSize ); STDMETHOD_(void,ServerFillBuffer)( REFGUID, REFIID, ULONG *DataSize, void *DataBuffer, HRESULT hrFault ); }; /***************************************************************************/ // Functions called by channel. void CleanupChannelHooks(); ULONG ClientGetSize( ULONG *cNumExtent, CMessageCall * ); HRESULT ClientNotify ( WireThat *, ULONG cMax, void **pStubData, DWORD DataRep, HRESULT hr, CMessageCall * ); void *FillBuffer ( WireExtentArray *, ULONG cMaxSize, ULONG cNumExtent, BOOL fClient, CMessageCall * ); void InitHooksIfNecessary(); ULONG ServerGetSize( ULONG *cNumExtent, CMessageCall * ); HRESULT ServerNotify ( WireThis *, ULONG cMax, void **pStubData, DWORD DataRep, CMessageCall * ); // Globals filled in by CRpcResolver::GetConnection extern LONG gcChannelHook; extern GUID *gaChannelHook; #endif // _CHOCK_HXX_
35.455959
99
0.565103
npocmaka
7d86df06afe2b822404093af3a1d7049a1597364
571
cpp
C++
BashuOJ-Code/2898.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2898.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2898.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<iomanip> #include<cmath> #include<climits> using namespace std; int n,m,f[305][305]={0}; int main(){ cin>>n>>m; int x,y,z; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i!=j)f[i][j]=INT_MIN; for(int i=1;i<=m;i++)cin>>x>>y>>z,f[x][y]=z; for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(f[i][k]!=INT_MIN&&f[k][j]!=INT_MIN)f[i][j]=max(f[i][j],f[i][k]+f[k][j]); int Max=INT_MIN; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++)Max=max(Max,f[i][j]); cout<<Max; return 0; }
21.961538
77
0.556918
magicgh
7d88a0fd2e1c42b149dbca54a32cda90d253b8ef
6,971
hpp
C++
sources/SoundSystem/spSoundEffect.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/SoundSystem/spSoundEffect.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/SoundSystem/spSoundEffect.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2020-02-15T09:17:41.000Z
2020-05-21T14:10:40.000Z
/* * Sound effect interface header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_AUDIO_SOUNDEFFECT_H__ #define __SP_AUDIO_SOUNDEFFECT_H__ #include "Base/spStandard.hpp" namespace sp { namespace audio { //! Sound effect types. enum ESoundEffectTypes { SOUNDEFFECT_REVERBERATION = 0, //!< Reverberation sound effect. Used for sound reflections. SOUNDEFFECT_CHORUS, //!< Not yet supported. SOUNDEFFECT_DISTORTION, //!< Not yet supported. SOUNDEFFECT_ECHO, //!< Not yet supported. SOUNDEFFECT_FLANGER, //!< Not yet supported. SOUNDEFFECT_FREQUENCY_SHIFTER, //!< Not yet supported. SOUNDEFFECT_VOCAL_MORPHER, //!< Not yet supported. SOUNDEFFECT_PITCH_SHIFTER, //!< Not yet supported. SOUNDEFFECT_RING_MODULATOR, //!< Not yet supported. SOUNDEFFECT_AUTOWAH, //!< Not yet supported. SOUNDEFFECT_COMPRESSOR, //!< Not yet supported. SOUNDEFFECT_EQUALIZER, //!< Not yet supported. }; /** Sound effect presets. \note All these presets have been taken from the "EFX-Util.h" file which is part of the "OpenAL EFX" extension. */ enum ESoundEffectPresets { /* Reverberation default presets: */ SFXPRESET_REVERB_GENERIC = 0, SFXPRESET_REVERB_PADDEDCELL, SFXPRESET_REVERB_ROOM, SFXPRESET_REVERB_BATHROOM, SFXPRESET_REVERB_LIVINGROOM, SFXPRESET_REVERB_STONEROOM, SFXPRESET_REVERB_AUDITORIUM, SFXPRESET_REVERB_CONCERTHALL, SFXPRESET_REVERB_CAVE, SFXPRESET_REVERB_ARENA, SFXPRESET_REVERB_HANGAR, SFXPRESET_REVERB_CARPETTEDHALLWAY, SFXPRESET_REVERB_HALLWAY, SFXPRESET_REVERB_STONECORRIDOR, SFXPRESET_REVERB_ALLEY, SFXPRESET_REVERB_FOREST, SFXPRESET_REVERB_CITY, SFXPRESET_REVERB_MOUNTAINS, SFXPRESET_REVERB_QUARRY, SFXPRESET_REVERB_PLAIN, SFXPRESET_REVERB_PARKINGLOT, SFXPRESET_REVERB_SEWERPIPE, SFXPRESET_REVERB_UNDERWATER, SFXPRESET_REVERB_DRUGGED, SFXPRESET_REVERB_DIZZY, SFXPRESET_REVERB_PSYCHOTIC, /* Reverberation castle presets: */ SFXPRESET_REVERB_CASTLE_SMALLROOM, SFXPRESET_REVERB_CASTLE_SHORTPASSAGE, SFXPRESET_REVERB_CASTLE_MEDIUMROOM, SFXPRESET_REVERB_CASTLE_LONGPASSAGE, SFXPRESET_REVERB_CASTLE_LARGEROOM, SFXPRESET_REVERB_CASTLE_HALL, SFXPRESET_REVERB_CASTLE_CUPBOARD, SFXPRESET_REVERB_CASTLE_COURTYARD, SFXPRESET_REVERB_CASTLE_ALCOVE, /* Reverberation factory presets: */ SFXPRESET_REVERB_FACTORY_ALCOVE, SFXPRESET_REVERB_FACTORY_SHORTPASSAGE, SFXPRESET_REVERB_FACTORY_MEDIUMROOM, SFXPRESET_REVERB_FACTORY_LONGPASSAGE, SFXPRESET_REVERB_FACTORY_LARGEROOM, SFXPRESET_REVERB_FACTORY_HALL, SFXPRESET_REVERB_FACTORY_CUPBOARD, SFXPRESET_REVERB_FACTORY_COURTYARD, SFXPRESET_REVERB_FACTORY_SMALLROOM, /* Reverberation icepalace presets: */ SFXPRESET_REVERB_ICEPALACE_ALCOVE, SFXPRESET_REVERB_ICEPALACE_SHORTPASSAGE, SFXPRESET_REVERB_ICEPALACE_MEDIUMROOM, SFXPRESET_REVERB_ICEPALACE_LONGPASSAGE, SFXPRESET_REVERB_ICEPALACE_LARGEROOM, SFXPRESET_REVERB_ICEPALACE_HALL, SFXPRESET_REVERB_ICEPALACE_CUPBOARD, SFXPRESET_REVERB_ICEPALACE_COURTYARD, SFXPRESET_REVERB_ICEPALACE_SMALLROOM, /* Reverberation spacestation presets: */ SFXPRESET_REVERB_SPACESTATION_ALCOVE, SFXPRESET_REVERB_SPACESTATION_MEDIUMROOM, SFXPRESET_REVERB_SPACESTATION_SHORTPASSAGE, SFXPRESET_REVERB_SPACESTATION_LONGPASSAGE, SFXPRESET_REVERB_SPACESTATION_LARGEROOM, SFXPRESET_REVERB_SPACESTATION_HALL, SFXPRESET_REVERB_SPACESTATION_CUPBOARD, SFXPRESET_REVERB_SPACESTATION_SMALLROOM, /* Reverberation wooden presets: */ SFXPRESET_REVERB_WOODEN_ALCOVE, SFXPRESET_REVERB_WOODEN_SHORTPASSAGE, SFXPRESET_REVERB_WOODEN_MEDIUMROOM, SFXPRESET_REVERB_WOODEN_LONGPASSAGE, SFXPRESET_REVERB_WOODEN_LARGEROOM, SFXPRESET_REVERB_WOODEN_HALL, SFXPRESET_REVERB_WOODEN_CUPBOARD, SFXPRESET_REVERB_WOODEN_SMALLROOM, SFXPRESET_REVERB_WOODEN_COURTYARD, /* Reverberation sport presets: */ SFXPRESET_REVERB_SPORT_EMPTYSTADIUM, SFXPRESET_REVERB_SPORT_SQUASHCOURT, SFXPRESET_REVERB_SPORT_SMALLSWIMMINGPOOL, SFXPRESET_REVERB_SPORT_LARGESWIMMINGPOOL, SFXPRESET_REVERB_SPORT_GYMNASIUM, SFXPRESET_REVERB_SPORT_FULLSTADIUM, SFXPRESET_REVERB_SPORT_STADIUMTANNOY, /* Reverberation prefab presets: */ SFXPRESET_REVERB_PREFAB_WORKSHOP, SFXPRESET_REVERB_PREFAB_SCHOOLROOM, SFXPRESET_REVERB_PREFAB_PRACTISEROOM, SFXPRESET_REVERB_PREFAB_OUTHOUSE, SFXPRESET_REVERB_PREFAB_CARAVAN, /* Reverberation dome- and pipe presets: */ SFXPRESET_REVERB_DOME_TOMB, SFXPRESET_REVERB_PIPE_SMALL, SFXPRESET_REVERB_DOME_SAINTPAULS, SFXPRESET_REVERB_PIPE_LONGTHIN, SFXPRESET_REVERB_PIPE_LARGE, SFXPRESET_REVERB_PIPE_RESONANT, /* Reverberation outdoor presets: */ SFXPRESET_REVERB_OUTDOORS_BACKYARD, SFXPRESET_REVERB_OUTDOORS_ROLLINGPLAINS, SFXPRESET_REVERB_OUTDOORS_DEEPCANYON, SFXPRESET_REVERB_OUTDOORS_CREEK, SFXPRESET_REVERB_OUTDOORS_VALLEY, /* Reverberation mood presets: */ SFXPRESET_REVERB_MOOD_HEAVEN, SFXPRESET_REVERB_MOOD_HELL, SFXPRESET_REVERB_MOOD_MEMORY, /* Reverberation driving presets: */ SFXPRESET_REVERB_DRIVING_COMMENTATOR, SFXPRESET_REVERB_DRIVING_PITGARAGE, SFXPRESET_REVERB_DRIVING_INCAR_RACER, SFXPRESET_REVERB_DRIVING_INCAR_SPORTS, SFXPRESET_REVERB_DRIVING_INCAR_LUXURY, SFXPRESET_REVERB_DRIVING_FULLGRANDSTAND, SFXPRESET_REVERB_DRIVING_EMPTYGRANDSTAND, SFXPRESET_REVERB_DRIVING_TUNNEL, /* Reverberation city presets: */ SFXPRESET_REVERB_CITY_STREETS, SFXPRESET_REVERB_CITY_SUBWAY, SFXPRESET_REVERB_CITY_MUSEUM, SFXPRESET_REVERB_CITY_LIBRARY, SFXPRESET_REVERB_CITY_UNDERPASS, SFXPRESET_REVERB_CITY_ABANDONED, /* Reverberation other presets: */ SFXPRESET_REVERB_DUSTYROOM, SFXPRESET_REVERB_CHAPEL, SFXPRESET_REVERB_SMALLWATERROOM, }; /** Sound effect base class. \note Currently only supported for OpenAL. \ingroup group_audio */ class SP_EXPORT SoundEffect { public: SoundEffect(); virtual ~SoundEffect(); /* Functions */ virtual void setType(const ESoundEffectTypes Type); virtual void setupEffectPreset(const ESoundEffectPresets Preset); /* Inline functions */ inline ESoundEffectTypes getType() const { return Type_; } protected: /* Members */ ESoundEffectTypes Type_; }; } // /namespace audio } // /namespace sp #endif // ================================================================================
30.047414
111
0.744943
rontrek
7d88fb0477e803fc74bdf7a279d3d388c4238830
2,097
cc
C++
code/qttoolkit/qtaddons/attributecontrollerwidget/code/stringcontroller.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/qttoolkit/qtaddons/attributecontrollerwidget/code/stringcontroller.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/qttoolkit/qtaddons/attributecontrollerwidget/code/stringcontroller.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // stringcontroller.cc // (C) 2013-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "stringcontroller.h" #include "game/entity.h" #include "db/valuetable.h" #include "ui_stringcontroller.h" #include "basegamefeature/basegameprotocol.h" using namespace Util; namespace QtAttributeControllerAddon { //------------------------------------------------------------------------------ /** */ StringController::StringController(QWidget* parent, const Ptr<Game::Entity>& _entity, const Attr::AttrId& _attrId, Util::Variant::Type _attrType): BaseAttributeController(parent, _entity, _attrId, _attrType) { // setup ui this->ui = new Ui::StringController(); this->ui->setupUi(this); this->ui->lineEdit->installEventFilter(this); Ptr<BaseGameFeature::GetAttribute> msg = BaseGameFeature::GetAttribute::Create(); msg->SetAttributeId(this->attributeId); _entity->SendSync(msg.cast<Messaging::Message>()); this->ui->lineEdit->setText(msg->GetAttr().GetString().AsCharPtr()); bool connected = false; connected = connect(this->ui->lineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(OnTextChanged(const QString &))); n_assert(connected); } //------------------------------------------------------------------------------ /** */ StringController::~StringController() { this->entity = 0; } //------------------------------------------------------------------------------ /** */ void StringController::OnTextChanged(const QString &string) { BaseAttributeController::OnValueChanged(); } //------------------------------------------------------------------------------ /** */ Util::Variant StringController::GetValue() const { Util::String value = this->ui->lineEdit->text().toUtf8().constData(); return Util::Variant(value); } //------------------------------------------------------------------------------ /** */ void StringController::Lock() { this->ui->lineEdit->setEnabled(false); } }
27.592105
146
0.533619
gscept
7d8ae07cf9e3aa1686166fff377d61f1fc10dfb5
5,000
cpp
C++
src/detail/LuaPbIntfImpl.cpp
zhuyadong/LuaPbIntf
94b99ffececb455cc6483cfe897f3601d7bcf479
[ "MIT" ]
null
null
null
src/detail/LuaPbIntfImpl.cpp
zhuyadong/LuaPbIntf
94b99ffececb455cc6483cfe897f3601d7bcf479
[ "MIT" ]
null
null
null
src/detail/LuaPbIntfImpl.cpp
zhuyadong/LuaPbIntf
94b99ffececb455cc6483cfe897f3601d7bcf479
[ "MIT" ]
1
2018-09-10T10:26:38.000Z
2018-09-10T10:26:38.000Z
#include "LuaPbIntfImpl.h" #include "MessageSetter.h" #include "MsgToTbl.h" // for LuaException #include <LuaIntf/LuaIntf.h> #include <LuaIntf/LuaState.h> #include <google/protobuf/compiler/importer.h> // for DiskSourceTree #include <google/protobuf/descriptor.h> // for Descriptor #include <google/protobuf/dynamic_message.h> // for GetPrototype() #include <google/protobuf/message.h> // for Message #include <sstream> // for ostringstream using namespace LuaIntf; using namespace googlex::protobuf; // See protobuf CommandLineInterface::Run(). class ErrorCollector : public compiler::MultiFileErrorCollector { public: void Clear() { m_sError.clear(); } const std::string& GetError() const { return m_sError; } // Only record the last error. void AddError(const std::string & filename, int line, int column, const std::string & message) override { std::ostringstream oss; oss << filename << ":" << line << ": " << message; m_sError = oss.str(); } private: std::string m_sError; }; LuaPbIntfImpl::LuaPbIntfImpl() : m_pDiskSourceTree(new DiskSourceTree), // unique_ptr m_pErrorCollector(new ErrorCollector), // unique_ptr m_pImporter(new Importer(m_pDiskSourceTree.get(), // unique_ptr m_pErrorCollector.get())), m_pMsgFactory(new MsgFactory) // unique_ptr { // The current dir is the default proto path. AddProtoPath(""); } LuaPbIntfImpl::~LuaPbIntfImpl() { } // e.g. AddProtoPath("proto") // e.g. AddProtoPath("d:/proto") void LuaPbIntfImpl::AddProtoPath(const string& sProtoPath) { MapPath("", sProtoPath); } void LuaPbIntfImpl::MapPath( const string& sVirtualPath, const string& sDiskPath) { m_pDiskSourceTree->MapPath(sVirtualPath, sDiskPath); } // e.g. ImportProtoFile("bar/foo.proto") void LuaPbIntfImpl::ImportProtoFile(const string& sProtoFile) { m_pErrorCollector->Clear(); const FileDescriptor* pDesc = m_pImporter->Import(sProtoFile); if (pDesc) return; throw LuaException("Failed to import: " + m_pErrorCollector->GetError()); } MessageSptr LuaPbIntfImpl::MakeSharedMessage(const string& sTypeName) const { const Descriptor* pDesc = m_pImporter->pool()-> FindMessageTypeByName(sTypeName); if (!pDesc) throw LuaException("No message type: " + sTypeName); const Message* pProtoType = m_pMsgFactory->GetPrototype(pDesc); if (!pProtoType) throw LuaException("No prototype for " + sTypeName); return MessageSptr(pProtoType->New()); } std::string LuaPbIntfImpl::Encode(const string& sMsgTypeName, const LuaRef& luaTable) const { luaTable.checkTable(); // Bad argument #-1 to 'encode' (table expected, got number) MessageSptr pMsg = MakeSharedMessage(sMsgTypeName); assert(pMsg); MessageSetter(*pMsg).SetMsg(luaTable); return pMsg->SerializeAsString(); } // Encode() LuaRef LuaPbIntfImpl::Decode(lua_State* L, const string& sMsgTypeName, const string& sData) const { assert(L); MessageSptr pMsg = MakeSharedMessage(sMsgTypeName); assert(pMsg); if (pMsg->ParseFromString(sData)) return MsgToTbl(*L, *pMsg).ToTbl(); return LuaRef(L, nullptr); } LuaRef LuaPbIntfImpl::GetServiceDescriptorTbl(lua_State* L, const string& sServiceName) const { assert(L); const googlex::protobuf::ServiceDescriptor* pDesc = GetServiceDescriptor(sServiceName); if (!pDesc) throw LuaIntf::LuaException("No such service: " + sServiceName); googlex::protobuf::ServiceDescriptorProto msg; pDesc->CopyTo(&msg); return MsgToTbl(*L, msg).ToTbl(); } std::string LuaPbIntfImpl::GetRpcInputName(const string& sServiceName, const string& sMethodName) const { return FindRpcMethod(sServiceName, sMethodName).input_type()->full_name(); } std::string LuaPbIntfImpl::GetRpcOutputName(const string& sServiceName, const string& sMethodName) const { return FindRpcMethod(sServiceName, sMethodName).output_type()->full_name(); } bool LuaPbIntfImpl::IsRpcClientStreaming(const string& sServiceName, const string& sMethodName) const { return FindRpcMethod(sServiceName, sMethodName).client_streaming(); } bool LuaPbIntfImpl::IsRpcServerStreaming(const string& sServiceName, const string& sMethodName) const { return FindRpcMethod(sServiceName, sMethodName).server_streaming(); } const googlex::protobuf::ServiceDescriptor* LuaPbIntfImpl::GetServiceDescriptor(const string& sServiceName) const { return m_pImporter->pool()->FindServiceByName(sServiceName); } const MethodDescriptor& LuaPbIntfImpl::FindRpcMethod( const string& sServiceName, const string& sMethodName) const { const ServiceDescriptor* pDesc = GetServiceDescriptor(sServiceName); if (!pDesc) throw LuaException("No such service: " + sServiceName); const MethodDescriptor* pMethod = pDesc->FindMethodByName(sMethodName); if (pMethod) return *pMethod; throw LuaException("No such method: " + sServiceName + "." + sMethodName); }
30.674847
88
0.7212
zhuyadong
7d8f0c7d898969b06ab52c266bebf6b76f2b6522
26,529
cpp
C++
src/graphics/gfx_hud.cpp
q4a/TheXTech
574a4ad6723cce804732337073db9d093cb700b1
[ "MIT" ]
null
null
null
src/graphics/gfx_hud.cpp
q4a/TheXTech
574a4ad6723cce804732337073db9d093cb700b1
[ "MIT" ]
null
null
null
src/graphics/gfx_hud.cpp
q4a/TheXTech
574a4ad6723cce804732337073db9d093cb700b1
[ "MIT" ]
null
null
null
/* * TheXTech - A platform game engine ported from old source code for VB6 * * Copyright (c) 2009-2011 Andrew Spinks, original VB6 code * Copyright (c) 2020-2021 Vitaly Novichkov <admin@wohlnet.ru> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "../globals.h" #include "../graphics.h" void DrawInterface(int Z, int numScreens) { int B = 0; int C = 0; int D = 0; std::string scoreStr = std::to_string(Score); std::string coinsStr = std::to_string(Coins); std::string livesStr = std::to_string(int(Lives)); std::string numStarsStr = std::to_string(numStars); if(ScreenType == 5 || ScreenType == 6) // 2 Players { if(static_cast<int>(numScreens) == 1 && ScreenType != 6) // Only 1 screen { for(B = 1; B <= numPlayers; B++) { if(B == 1) C = -40; else C = 40; if(Player[B].Character == 3 || Player[B].Character == 4 || Player[B].Character == 5) { if(B == 1) D = -1; else D = 1; if(Player[B].Hearts > 0) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32 + 17 * D, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32 + 17 * D, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } if(Player[B].Hearts > 1) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 17 * D, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 17 * D, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } if(Player[B].Hearts > 2) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32 + 17 * D, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32 + 17 * D, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } } else { // 2 players 1 screen heldbonus frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C, 16, GFX.Container[1].w, GFX.Container[1].h, GFX.Container[Player[B].Character], 0, 0); if(Player[B].HeldBonus > 0) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C + 12, 16 + 12, NPCWidth[Player[B].HeldBonus], NPCHeight[Player[B].HeldBonus], GFXNPC[Player[B].HeldBonus], 0, 0); } } } for(B = 1; B <= 2; B++) { if(B == 1) C = -58; else C = 56; if(Player[B].Character == 5 && Player[B].Bombs > 0) { frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 - 34 + C, 52, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[8], 0, 0); frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 - 10 + C, 53, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(std::to_string(Player[B].Bombs), 1, float(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 12 + C), 53); } } C = 40; if(BattleMode == false) { // Print coins on the screen if((Player[1].HasKey | Player[2].HasKey) != 0) { frmMain.renderTexture(-24 + 40 + 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[0], 0, 0); } if(Player[1].Character == 5) { frmMain.renderTexture(40 + 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[6], 0, 0); } else { frmMain.renderTexture(40 + 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[2], 0, 0); } frmMain.renderTexture(40 + 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96 + 8 + GFX.Interface[2].w, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(coinsStr, 1, 40 + 20 - (int(coinsStr.size()) * 18) + (float(vScreen[Z].Width) / 2.0f) - (GFX.Container[1].w / 2) + 80 + 4 + 12 + 18 + 32 + GFX.Interface[3].w, 16 + 11); // Print Score SuperPrint(scoreStr, 1, 40 + 20 - (int(scoreStr.size()) * 18) + (float(vScreen[Z].Width) / 2.0f) - (GFX.Container[1].w / 2) + 80 + 12 + 4 + 18 + 32 + GFX.Interface[3].w, 16 + 31); // Print lives on the screen frmMain.renderTexture(-80 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 - 16, 16 + 10, GFX.Interface[3].w, GFX.Interface[3].h, GFX.Interface[3], 0, 0); frmMain.renderTexture(-80 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 10 + GFX.Interface[1].w, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(livesStr, 1, float(-80 + (vScreen[Z].Width / 2.0) - (GFX.Container[1].w / 2) + C - 122 + 12 + 18 + GFX.Interface[5].w), 16 + 11); // Print stars on the screen if(numStars > 0) { frmMain.renderTexture(-80 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122, 16 + 30, GFX.Interface[5].w, GFX.Interface[5].h, GFX.Interface[5], 0, 0); frmMain.renderTexture(-80 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 10 + GFX.Interface[1].w, 16 + 31, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(numStarsStr, 1, float(-80 + (vScreen[Z].Width / 2.0) - (GFX.Container[1].w / 2) + C - 122 + 12 + 18 + GFX.Interface[5].w), 16 + 31); } } else { // plr 1 score frmMain.renderTexture(-80 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 - 16, 16 + 10, GFX.Interface[3].w, GFX.Interface[3].h, GFX.Interface[3], 0, 0); frmMain.renderTexture(-80 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 10 + GFX.Interface[1].w, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(std::to_string(BattleLives[1]), 1, float(-80 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 12 + 18 + GFX.Interface[5].w), 16 + 11); // plr 2 score frmMain.renderTexture(40 + 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96 - 16, 16 + 10, GFX.Interface[3].w, GFX.Interface[3].h, GFX.Interface[7], 0, 0); frmMain.renderTexture(40 + 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96 + 8 + GFX.Interface[2].w, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(std::to_string(BattleLives[2]), 1, float(24 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 80 + 4 + 12 + 18 + 32 + GFX.Interface[3].w), 16 + 11); } } else // Split screen { // 2 players 2 screen heldbonus if(Player[Z].Character == 3 || Player[Z].Character == 4 || Player[Z].Character == 5) { if(Player[Z].Hearts > 0) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } if(Player[Z].Hearts > 1) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } if(Player[Z].Hearts > 2) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2, 16, GFX.Container[1].w + B, GFX.Container[1].h, GFX.Container[Player[Z].Character], 0, 0); if(Player[Z].HeldBonus > 0) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 12, 16 + 12, NPCWidth[Player[Z].HeldBonus], NPCHeight[Player[Z].HeldBonus], GFXNPC[Player[Z].HeldBonus], 0, 0); } } if(Player[Z].Character == 5 && Player[Z].Bombs > 0) { frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 - 34, 52, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[8], 0, 0); frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 - 10, 53, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(std::to_string(Player[Z].Bombs), 1, 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 12, 53); } if(BattleMode == false) { // Print coins on the screen if(Player[Z].HasKey == true) { frmMain.renderTexture(-24 + 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[0], 0, 0); } if(Player[Z].Character == 5) { frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[6], 0, 0); } else { frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[2], 0, 0); } frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96 + 8 + GFX.Interface[2].w, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(coinsStr, 1, float(20 - int(coinsStr.size()) * 18 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 80 + 4 + 12 + 18 + 32 + GFX.Interface[3].w), 16 + 11); // Print Score SuperPrint(scoreStr, 1, float(20 - int(scoreStr.size()) * 18 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 80 + 12 + 4 + 18 + 32 + GFX.Interface[3].w), 16 + 31); // Print lives on the screen frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 - 16, 16 + 10, GFX.Interface[3].w, GFX.Interface[3].h, GFX.Interface[3], 0, 0); frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 10 + GFX.Interface[1].w, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(livesStr, 1, float(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 12 + 18 + GFX.Interface[5].w), 16 + 11); // Print stars on the screen if(numStars > 0) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122, 16 + 30, GFX.Interface[5].w, GFX.Interface[5].h, GFX.Interface[5], 0, 0); frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 10 + GFX.Interface[1].w, 16 + 31, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(numStarsStr, 1, float(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 12 + 18 + GFX.Interface[5].w), 16 + 31); } } else { if(Z == 1) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122, 16 + 10, GFX.Interface[3].w, GFX.Interface[3].h, GFX.Interface[3], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122, 16 + 10, GFX.Interface[3].w, GFX.Interface[3].h, GFX.Interface[7], 0, 0); } frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 10 + GFX.Interface[1].w + 16, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(std::to_string(BattleLives[Z]), 1, float(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 12 + 18 + GFX.Interface[5].w + 16), 16 + 11); } } } else // 1 Player or Multi Mario { // if(nPlay.Online == false) { if(Player[1].Character == 3 || Player[1].Character == 4 || Player[1].Character == 5) { // BitBlt myBackBuffer, vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX::HeartMask(1).hdc, 0, 0, vbSrcAnd; // BitBlt myBackBuffer, vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX::HeartMask(1).hdc, 0, 0, vbSrcAnd; // BitBlt myBackBuffer, vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX::HeartMask(1).hdc, 0, 0, vbSrcAnd; if(Player[1].Hearts > 0) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } if(Player[1].Hearts > 1) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } if(Player[1].Hearts > 2) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); } } else { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2, 16, GFX.Container[1].w + B, GFX.Container[1].h, GFX.Container[0], 0, 0); if(Player[1].HeldBonus > 0) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 12, 16 + 12, NPCWidth[Player[1].HeldBonus], NPCHeight[Player[1].HeldBonus], GFXNPC[Player[1].HeldBonus], 0, 0); } } } // else // { // if(Player[nPlay.MySlot + 1].Character == 3 || Player[nPlay.MySlot + 1].Character == 4) // { //// BitBlt myBackBuffer, vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX::HeartMask(1).hdc, 0, 0, vbSrcAnd; //// BitBlt myBackBuffer, vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX::HeartMask(1).hdc, 0, 0, vbSrcAnd; //// BitBlt myBackBuffer, vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX::HeartMask(1).hdc, 0, 0, vbSrcAnd; // if(Player[nPlay.MySlot + 1].Hearts > 0) // { // frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); // } // else // { // frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C - 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); // } // if(Player[nPlay.MySlot + 1].Hearts > 1) // { // frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); // } // else // { // frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); // } // if(Player[nPlay.MySlot + 1].Hearts > 2) // { // frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[1], 0, 0); // } // else // { // frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Heart[1].w / 2 + C + 32, 16, GFX.Heart[1].w, GFX.Heart[1].h, GFX.Heart[2], 0, 0); // } // } // else // { // BitBlt myBackBuffer, vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2, 16, GFX.Container[1].w + B, GFX.Container[1].h, GFX::ContainerMask(0).hdc, 0, 0, vbSrcAnd; // BitBlt myBackBuffer, vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2, 16, GFX.Container[1].w + B, GFX.Container[1].h, GFX::Container(0).hdc, 0, 0, vbSrcPaint; // if(Player[nPlay.MySlot + 1].HeldBonus > 0) // { // frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 12, 16 + 12, NPCWidth[Player[nPlay.MySlot + 1].HeldBonus], NPCHeight[Player[nPlay.MySlot + 1].HeldBonus], GFXNPCMask[Player[nPlay.MySlot + 1].HeldBonus], 0, 0); // frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 12, 16 + 12, NPCWidth[Player[nPlay.MySlot + 1].HeldBonus], NPCHeight[Player[nPlay.MySlot + 1].HeldBonus], GFXNPC[Player[nPlay.MySlot + 1].HeldBonus], 0, 0); // } // } // } if(Player[1].Character == 5 && Player[1].Bombs > 0) { frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 - 34 + C, 52, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[8], 0, 0); frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 - 10 + C, 53, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(std::to_string(Player[1].Bombs), 1, float(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 12 + C), 53); } // Print coins on the screen if(Player[1].HasKey == true) { frmMain.renderTexture(-24 + 20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[0], 0, 0); } if(Player[1].Character == 5) { frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[6], 0, 0); } else { frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96, 16 + 10, GFX.Interface[2].w, GFX.Interface[2].h, GFX.Interface[2], 0, 0); } frmMain.renderTexture(20 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 96 + 8 + GFX.Interface[2].w, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(coinsStr, 1, float(20 - int(coinsStr.size()) * 18 + vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + 80 + 4 + 12 + 18 + 32 + GFX.Interface[3].w), 16 + 11); // Print Score SuperPrint(scoreStr, 1, 20 - int(scoreStr.size()) * 18 + float(vScreen[Z].Width) / 2.0f - GFX.Container[1].w / 2 + 80 + 12 + 4 + 18 + 32 + GFX.Interface[3].w, 16 + 31); // Print lives on the screen frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 - 16, 16 + 10, GFX.Interface[3].w, GFX.Interface[3].h, GFX.Interface[3], 0, 0); frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 10 + GFX.Interface[1].w, 16 + 11, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(livesStr, 1, float(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 12 + 18 + GFX.Interface[5].w), 16 + 11); // Print stars on the screen if(numStars > 0) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122, 16 + 30, GFX.Interface[5].w, GFX.Interface[5].h, GFX.Interface[5], 0, 0); frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 10 + GFX.Interface[1].w, 16 + 31, GFX.Interface[1].w, GFX.Interface[1].h, GFX.Interface[1], 0, 0); SuperPrint(numStarsStr, 1, float(vScreen[Z].Width / 2.0 - GFX.Container[1].w / 2 + C - 122 + 12 + 18 + GFX.Interface[5].w), 16 + 31); } } if(BattleIntro > 0) { if(BattleIntro > 45 || BattleIntro % 2 == 1) { frmMain.renderTexture(vScreen[Z].Width / 2.0 - GFX.BMVs.w / 2, -96 + vScreen[Z].Height / 2.0 - GFX.BMVs.h / 2, GFX.BMVs.w, GFX.BMVs.h, GFX.BMVs, 0, 0); frmMain.renderTexture(-50 + vScreen[Z].Width / 2.0 - GFX.CharacterName[Player[1].Character].w, -96 + vScreen[Z].Height / 2.0 - GFX.CharacterName[Player[1].Character].h / 2, GFX.CharacterName[Player[1].Character].w, GFX.CharacterName[Player[1].Character].h, GFX.CharacterName[Player[1].Character], 0, 0); frmMain.renderTexture(50 + vScreen[Z].Width / 2.0, -96 + vScreen[Z].Height / 2.0 - GFX.CharacterName[Player[2].Character].h / 2, GFX.CharacterName[Player[2].Character].w, GFX.CharacterName[Player[2].Character].h, GFX.CharacterName[Player[2].Character], 0, 0); } } if(BattleOutro > 0) { frmMain.renderTexture(10 + vScreen[Z].Width / 2.0, -96 + vScreen[Z].Height / 2.0 - GFX.BMWin.h / 2, GFX.BMWin.w, GFX.BMWin.h, GFX.BMWin, 0, 0); frmMain.renderTexture(-10 + vScreen[Z].Width / 2.0 - GFX.CharacterName[Player[BattleWinner].Character].w, -96 + vScreen[Z].Height / 2.0 - GFX.CharacterName[Player[BattleWinner].Character].h / 2, GFX.CharacterName[Player[BattleWinner].Character].w, GFX.CharacterName[Player[BattleWinner].Character].h, GFX.CharacterName[Player[BattleWinner].Character], 0, 0); } }
60.020362
366
0.486223
q4a
7d94b5c0e7b53664a967b5e0c84d8e9f59921dbe
737
cpp
C++
source/debugging_main.cpp
Arpit-Rulania/cpp_word_ladder
afa53979c53b6450a245b34fd32d3da41c332dbe
[ "Apache-2.0" ]
null
null
null
source/debugging_main.cpp
Arpit-Rulania/cpp_word_ladder
afa53979c53b6450a245b34fd32d3da41c332dbe
[ "Apache-2.0" ]
null
null
null
source/debugging_main.cpp
Arpit-Rulania/cpp_word_ladder
afa53979c53b6450a245b34fd32d3da41c332dbe
[ "Apache-2.0" ]
null
null
null
#include "comp6771/word_ladder.hpp" #include <iostream> // Please note: it's not good practice to test your code via a main function that does // printing. Instead, you should be using your test folder. This file should only really // be used for more "primitive" debugging as we know that playing solely with test // frameplays might be overwhelming for some. auto main() -> int { auto const english_lexicon = word_ladder::read_lexicon("./test/word_ladder/english.txt"); auto const ladders = word_ladder::generate("snack", "packs", english_lexicon); for (auto i = 0u; i < ladders.size(); i++) { for (auto j = 0u; j < ladders[i].size(); j++) { std::cout << ladders[i][j] << " "; } std::cout << '\n'; } // debug here }
36.85
90
0.68114
Arpit-Rulania
7d96a801fdd861b7c68010bb53e59bc22b9d908b
2,539
cpp
C++
src/presentation/models/movedatamodel.cpp
karagog/GKChess
cda731f5a130255f00002ed9489cd8524ac3d863
[ "Apache-2.0" ]
null
null
null
src/presentation/models/movedatamodel.cpp
karagog/GKChess
cda731f5a130255f00002ed9489cd8524ac3d863
[ "Apache-2.0" ]
null
null
null
src/presentation/models/movedatamodel.cpp
karagog/GKChess
cda731f5a130255f00002ed9489cd8524ac3d863
[ "Apache-2.0" ]
null
null
null
/*Copyright 2014 George Karagoulis 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 "movedatamodel.h" USING_NAMESPACE_GUTIL; NAMESPACE_GKCHESS1(UI); MoveDataModel::MoveDataModel(QObject *parent) :QAbstractItemModel(parent) {} void MoveDataModel::InitFromPGN(const QList<PGN_MoveData> &) { throw NotImplementedException<>(); } int MoveDataModel::rowCount(const QModelIndex &i) const { return _get_container_from_index(i)->Moves.size(); } int MoveDataModel::columnCount(const QModelIndex &) const { return 1; } QVariant MoveDataModel::data(const QModelIndex &i, int role) const { QVariant ret; MoveDataCache *md = _get_data_from_index(i); if(md) { switch((::Qt::ItemDataRole)role) { case ::Qt::DisplayRole: //ret = md->Data.Text; break; default: break; } } return ret; } QModelIndex MoveDataModel::index(int r, int c, const QModelIndex &i) const { return createIndex(r, c, _get_container_from_index(i)->Moves[r]); } QModelIndex MoveDataModel::parent(const QModelIndex &i) const { QModelIndex ret; MoveDataCache *mc = _get_data_from_index(i); if(mc){ if(mc->Parent){ MoveDataCache *grandparent = mc->Parent->Parent; int row = mc->Parent->Data.PlyNumber - 1; if(grandparent) row -= grandparent->Data.PlyNumber; ret = createIndex(row, 0, mc->Parent); } } return ret; } MoveDataModel::MoveDataContainer *MoveDataModel::_get_container_from_index(const QModelIndex &i) { return i.isValid() ? _get_data_from_index(i) : &m_rootContainer; } MoveDataModel::MoveDataContainer const *MoveDataModel::_get_container_from_index(const QModelIndex &i) const { return i.isValid() ? _get_data_from_index(i) : &m_rootContainer; } MoveDataModel::MoveDataCache *MoveDataModel::_get_data_from_index(const QModelIndex &i) { return i.isValid() ? reinterpret_cast<MoveDataCache *>(i.internalPointer()) : 0; } END_NAMESPACE_GKCHESS1;
26.447917
108
0.701063
karagog
7d96ff40d68658bdc9dc889dd9e0790c4b35c83c
144
hpp
C++
src/code_gen/include/code_gen.hpp
aroques/compiler
ee2557af9146a6fc7c8db4c505f787a6b3200bba
[ "MIT" ]
2
2019-02-15T10:08:42.000Z
2021-06-20T19:25:38.000Z
src/code_gen/include/code_gen.hpp
aroques/compiler
ee2557af9146a6fc7c8db4c505f787a6b3200bba
[ "MIT" ]
2
2019-04-10T13:44:09.000Z
2019-04-14T17:18:58.000Z
src/code_gen/include/code_gen.hpp
aroques/compiler
ee2557af9146a6fc7c8db4c505f787a6b3200bba
[ "MIT" ]
null
null
null
#ifndef CODE_GEN_HPP #define CODE_GEN_HPP #include "parser/include/Node.hpp" std::string generate_target(Node* root); #endif // !CODE_GEN_HPP
18
40
0.777778
aroques
7d99abc7f77057dcb7962a5203a13f669c0a0764
2,434
cpp
C++
auv_guidance/src/min_jerk_trajectory.cpp
osu-uwrt/auv_gnc
40dbe4bda0c00fd41ed714cc2ea82f0c319e5e46
[ "BSD-2-Clause" ]
31
2019-08-07T08:04:51.000Z
2022-03-19T10:03:42.000Z
auv_guidance/src/min_jerk_trajectory.cpp
Chandler-Xu/auv_gnc
9e9efb49fd2a88a76b97c2381bb6138ec7513520
[ "BSD-2-Clause" ]
null
null
null
auv_guidance/src/min_jerk_trajectory.cpp
Chandler-Xu/auv_gnc
9e9efb49fd2a88a76b97c2381bb6138ec7513520
[ "BSD-2-Clause" ]
11
2019-09-17T14:01:01.000Z
2022-03-16T11:45:33.000Z
#include "auv_guidance/min_jerk_trajectory.hpp" #include <iostream> namespace auv_guidance { /** * @param start Initial conditions of position, velocity, and acceleration. * @param end Final conditions of position, velocity, and acceleration * @param duration Duration for which trajectory will occur */ MinJerkTrajectory::MinJerkTrajectory(const Eigen::Ref<const Eigen::Vector3d> &start, const Eigen::Ref<const Eigen::Vector3d> &end, double duration) { x0_ = start(0), v0_ = start(1), a0_ = start(2); xf_ = end(0), vf_ = end(1), af_ = end(2); t0_ = 0; tf_ = duration; dt = tf_ - t0_; dt2 = dt * dt; c0_ = 0, c1_ = 0, c2_ = 0, c3_ = 0, c4_ = 0, c5_ = 0; MinJerkTrajectory::computeCoeffs(); } /** * Compute the needed coefficients for the min jerk trajectory */ void MinJerkTrajectory::computeCoeffs() { c0_ = x0_; c1_ = v0_ * dt; c2_ = 0.5 * a0_ * dt2; c3_ = -10.0 * x0_ - 6.0 * v0_ * dt - 1.5 * a0_ * dt2 + 10.0 * xf_ - 4.0 * vf_ * dt + 0.5 * af_ * dt2; c4_ = 15.0 * x0_ + 8.0 * v0_ * dt + 1.5 * a0_ * dt2 - 15.0 * xf_ + 7.0 * vf_ * dt - af_ * dt2; c5_ = -6.0 * x0_ - 3.0 * v0_ * dt - 0.5 * a0_ * dt2 + 6.0 * xf_ - 3.0 * vf_ * dt + 0.5 * af_ * dt2; } /** * @param time Time instance for which to compute the state of the trajectory * Compute the state of the trajectory at specified time */ Eigen::Vector3d MinJerkTrajectory::computeState(double time) { Eigen::Vector3d state = Eigen::Vector3d::Zero(); if (time <= t0_) { state(0) = x0_; // Pos state(1) = v0_; // Vel state(2) = a0_; // Accel return state; } else if (time >= tf_) { state(0) = xf_; // Pos state(1) = vf_; // Vel state(2) = af_; // Accel return state; } double tau = (time - t0_) / (tf_ - t0_); double tau2 = tau * tau; double tau3 = tau * tau2; double tau4 = tau * tau3; double tau5 = tau * tau4; state(0) = c0_ + c1_ * tau + c2_ * tau2 + c3_ * tau3 + c4_ * tau4 + c5_ * tau5; state(1) = (c1_ + 2.0 * c2_ * tau + 3.0 * c3_ * tau2 + 4.0 * c4_ * tau3 + 5.0 * c5_ * tau4) / dt; state(2) = (2.0 * c2_ + 6.0 * c3_ * tau + 12.0 * c4_ * tau2 + 20.0 * c5_ * tau3) / dt2; return state; } double MinJerkTrajectory::getMiddleVelocity() { Eigen::Vector3d state = MinJerkTrajectory::computeState((tf_ - t0_) / 2.0); return state(1); } } // namespace auv_guidance
32.026316
147
0.576828
osu-uwrt
7d99dbcd0ba0abfad905db57df7fd967e3c55e9e
2,658
cpp
C++
ARK2D/src/ARK2D/UI/ComboBoxItem.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
6
2015-08-25T19:16:20.000Z
2021-04-19T16:47:58.000Z
ARK2D/src/ARK2D/UI/ComboBoxItem.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
1
2015-09-17T14:03:12.000Z
2015-09-17T14:03:12.000Z
ARK2D/src/ARK2D/UI/ComboBoxItem.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
1
2018-10-02T19:59:47.000Z
2018-10-02T19:59:47.000Z
/* * ComboBoxItem.cpp * * Created on: 14 Jul 2011 * Author: Ashley */ #include "ComboBoxItem.h" #include "ComboBox.h" #include "../ARK2D.h" #include "Button.h" namespace ARK { namespace UI { ComboBoxItem::ComboBoxItem(): AbstractUIComponent(), parent(NULL), m_text("") { m_width = 20; } ComboBoxItem::ComboBoxItem(string text, string value): AbstractUIComponent(), parent(NULL), m_text(text), m_value(value) { m_width = 20; } void ComboBoxItem::setText(string t) { m_text = t; } const string& ComboBoxItem::getText() { return m_text; } void ComboBoxItem::setValue(string t) { m_value = t; } const string& ComboBoxItem::getValue() { return m_value; } bool ComboBoxItem::keyPressed(unsigned int key) { if (key == (unsigned int) Input::MOUSE_BUTTON_LEFT) { if (m_state == Button::STATE_OVER) { m_state = Button::STATE_DOWN; return true; } } return false; } bool ComboBoxItem::keyReleased(unsigned int key) { if (key == (unsigned int) Input::MOUSE_BUTTON_LEFT) { Input* in = ARK2D::getInput(); bool mib = isGlobalPositionInBounds(in->getMouseX(), in->getMouseY()); if (mib && m_state == Button::STATE_DOWN) { ARK2D::getLog()->i("clicky"); //if (GigaRectangle<int>::s_contains(m_x, m_y, (signed int) (m_width), (signed int)(m_height), (signed int) (i->getMouseX()), (signed int) (i->getMouseY()))) { parent->m_selected = this; if (parent->m_itemChangedEvent != NULL) { void (*pt)(ComboBox*) = (void(*)(ComboBox*)) parent->m_itemChangedEvent; pt(parent); } m_state = Button::STATE_OFF; return true; } m_state = Button::STATE_OFF; } return false; } bool ComboBoxItem::mouseMoved(int x, int y, int oldx, int oldy) { return AbstractUIComponent::mouseMoved(x, y, oldx, oldy); } void ComboBoxItem::render() { renderBackground(); renderOverlay(); Renderer* g = ARK2D::getRenderer(); float tx = 0; float ty = 0; if (m_state == Button::STATE_DOWN) { tx += 2; ty += 2; } g->drawString(m_text, tx, ty); } void ComboBoxItem::renderBackground() { Renderer* g = ARK2D::getRenderer(); g->setDrawColor(Color::black_50a); g->fillRect(0, 0, m_width, m_height); } void ComboBoxItem::renderOverlay() { Renderer* g = ARK2D::getRenderer(); g->setDrawColor(Color::white); if (m_state == Button::STATE_OVER || m_state == Button::STATE_DOWN) { g->setDrawColor(Color::white_50a); } g->drawRect(0, 0, m_width, m_height); } } }
25.075472
163
0.607223
ashleygwinnell
7d9b992cff65f8c1270b72673eb6b215169e04d7
21,873
cc
C++
arcane/ceapart/src/arcane/tests/AMRCartesianMeshTesterModule.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/ceapart/src/arcane/tests/AMRCartesianMeshTesterModule.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/ceapart/src/arcane/tests/AMRCartesianMeshTesterModule.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* AMRCartesianMeshTesterModule.cc (C) 2000-2021 */ /* */ /* Module de test du gestionnaire de maillages cartésiens AMR. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arcane/utils/CheckedConvert.h" #include "arcane/utils/PlatformUtils.h" #include "arcane/utils/Real2.h" #include "arcane/utils/MD5HashAlgorithm.h" #include "arcane/MeshUtils.h" #include "arcane/Directory.h" #include "arcane/ITimeLoopMng.h" #include "arcane/ITimeLoopService.h" #include "arcane/ITimeLoop.h" #include "arcane/TimeLoopEntryPointInfo.h" #include "arcane/IMesh.h" #include "arcane/IItemFamily.h" #include "arcane/ItemPrinter.h" #include "arcane/IParallelMng.h" #include "arcane/IMesh.h" #include "arcane/IItemFamily.h" #include "arcane/IMeshModifier.h" #include "arcane/IMeshUtilities.h" #include "arcane/ServiceBuilder.h" #include "arcane/ServiceFactory.h" #include "arcane/MeshStats.h" #include "arcane/IPostProcessorWriter.h" #include "arcane/IVariableMng.h" #include "arcane/SimpleSVGMeshExporter.h" #include "arcane/cea/ICartesianMesh.h" #include "arcane/cea/CellDirectionMng.h" #include "arcane/cea/FaceDirectionMng.h" #include "arcane/cea/NodeDirectionMng.h" #include "arcane/cea/CartesianConnectivity.h" #include "arcane/cea/CartesianMeshRenumberingInfo.h" #include "arcane/cea/ICartesianMeshPatch.h" #include "arcane/tests/ArcaneTestGlobal.h" #include "arcane/tests/AMRCartesianMeshTester_axl.h" #include "arcane/tests/CartesianMeshTestUtils.h" /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace ArcaneTest { using namespace Arcane; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Module de test pour les infos sur les maillages cartésiens. */ class AMRCartesianMeshTesterModule : public ArcaneAMRCartesianMeshTesterObject { public: explicit AMRCartesianMeshTesterModule(const ModuleBuildInfo& mbi); ~AMRCartesianMeshTesterModule(); public: static void staticInitialize(ISubDomain* sd); public: void buildInit() override; void compute() override; void init() override; private: VariableCellReal m_density; VariableCellReal m_old_density; VariableCellReal3 m_cell_center; VariableFaceReal3 m_face_center; VariableNodeReal m_node_density; ICartesianMesh* m_cartesian_mesh; Ref<CartesianMeshTestUtils> m_utils; UniqueArray<VariableCellReal*> m_cell_patch_variables; private: void _compute1(); void _compute2(); void _initAMR(); void _computeSubCellDensity(Cell cell); void _computeCenters(); void _processPatches(); void _writePostProcessing(); void _checkUniqueIds(); void _checkUniqueIds(IItemFamily* family,const String& expected_hash); }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ AMRCartesianMeshTesterModule:: AMRCartesianMeshTesterModule(const ModuleBuildInfo& mbi) : ArcaneAMRCartesianMeshTesterObject(mbi) , m_density(VariableBuildInfo(this,"Density")) , m_old_density(VariableBuildInfo(this,"OldDensity")) , m_cell_center(VariableBuildInfo(this,"CellCenter")) , m_face_center(VariableBuildInfo(this,"FaceCenter")) , m_node_density(VariableBuildInfo(this,"NodeDensity")) , m_cartesian_mesh(nullptr) { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ AMRCartesianMeshTesterModule:: ~AMRCartesianMeshTesterModule() { for (VariableCellReal* v : m_cell_patch_variables) delete v; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: staticInitialize(ISubDomain* sd) { String time_loop_name("AMRCartesianMeshTestLoop"); ITimeLoopMng* tlm = sd->timeLoopMng(); ITimeLoop* time_loop = tlm->createTimeLoop(time_loop_name); { List<TimeLoopEntryPointInfo> clist; clist.add(TimeLoopEntryPointInfo("AMRCartesianMeshTester.buildInit")); time_loop->setEntryPoints(ITimeLoop::WBuild,clist); } { List<TimeLoopEntryPointInfo> clist; clist.add(TimeLoopEntryPointInfo("AMRCartesianMeshTester.init")); time_loop->setEntryPoints(ITimeLoop::WInit,clist); } { List<TimeLoopEntryPointInfo> clist; clist.add(TimeLoopEntryPointInfo("AMRCartesianMeshTester.compute")); time_loop->setEntryPoints(ITimeLoop::WComputeLoop,clist); } { StringList clist; clist.add("AMRCartesianMeshTester"); time_loop->setRequiredModulesName(clist); clist.clear(); clist.add("ArcanePostProcessing"); clist.add("ArcaneCheckpoint"); time_loop->setOptionalModulesName(clist); } tlm->registerTimeLoop(time_loop); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: buildInit() { if (subDomain()->isContinue()) return; m_global_deltat.assign(1.0); IItemFamily* cell_family = defaultMesh()->cellFamily(); cell_family->createGroup("CELL0"); cell_family->createGroup("CELL1"); cell_family->createGroup("CELL2"); IItemFamily* face_family = defaultMesh()->faceFamily(); face_family->createGroup("FACE0"); face_family->createGroup("FACE1"); face_family->createGroup("FACE2"); face_family->createGroup("FACE3"); face_family->createGroup("FACE4"); face_family->createGroup("FACE5"); face_family->createGroup("AllFacesDirection0"); face_family->createGroup("AllFacesDirection1"); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: init() { info() << "AMR Init"; IMesh* mesh = defaultMesh(); IItemFamily* cell_family = mesh->cellFamily(); Int32UniqueArray ids(1); ids[0] = 0; cell_family->createGroup("CELL0",ids,true); ids[0] = 1; cell_family->createGroup("CELL1",ids,true); ids[0] = 2; cell_family->createGroup("CELL2",ids,true); IItemFamily* face_family = defaultMesh()->faceFamily(); ids[0] = 0; face_family->createGroup("FACE0",ids,true); ids[0] = 1; face_family->createGroup("FACE1",ids,true); ids[0] = 2; face_family->createGroup("FACE2",ids,true); ids[0] = 3; face_family->createGroup("FACE3",ids,true); ids[0] = 4; face_family->createGroup("FACE4",ids,true); ids[0] = 5; face_family->createGroup("FACE5",ids,true); m_cartesian_mesh = ICartesianMesh::getReference(mesh); m_utils = makeRef(new CartesianMeshTestUtils(m_cartesian_mesh)); if (!subDomain()->isContinue()) _initAMR(); _computeCenters(); if (subDomain()->isContinue()) m_cartesian_mesh->recreateFromDump(); else{ m_cartesian_mesh->computeDirections(); CartesianMeshRenumberingInfo renumbering_info; renumbering_info.setRenumberPatchMethod(1); renumbering_info.setSortAfterRenumbering(true); m_cartesian_mesh->renumberItemsUniqueId(renumbering_info); _checkUniqueIds(); _processPatches(); } // Initialise la densité. // On met une densité de 1.0 à l'intérieur // et on ajoute une densité de 5.0 pour chaque direction dans les // mailles de bord. m_density.fill(1.0); Integer nb_dir = defaultMesh()->dimension(); for( Integer idir=0; idir<nb_dir; ++idir){ CellDirectionMng cdm(m_cartesian_mesh->cellDirection(idir)); Integer nb_boundary1 = 0; Integer nb_boundary2 = 0; ENUMERATE_CELL(icell,cdm.innerCells()){ DirCell cc(cdm.cell(*icell)); Cell next = cc.next(); Cell prev = cc.previous(); if (next.null() || prev.null()){ // Maille au bord. J'ajoute de la densité. // Ne devrait pas arriver car on est sur les innerCells() ++nb_boundary1; m_density[icell] += 5.0; } } // Parcours les mailles frontières pour la direction ENUMERATE_CELL(icell,cdm.outerCells()){ DirCell cc(cdm[icell]); //info() << "CELL: cell=" << ItemPrinter(*icell); // Maille au bord. J'ajoute de la densité. ++nb_boundary2; m_density[icell] += 5.0; } info() << "NB_BOUNDARY1=" << nb_boundary1 << " NB_BOUNDARY2=" << nb_boundary2; } m_utils->testAll(); _writePostProcessing(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: _checkUniqueIds(IItemFamily* family,const String& expected_hash) { // Vérifie que toutes les entités ont le bon uniqueId(); MD5HashAlgorithm hash_algo; IMesh* mesh = m_cartesian_mesh->mesh(); IParallelMng* pm = mesh->parallelMng(); UniqueArray<Int64> own_items_uid; ENUMERATE_(Item,iitem,family->allItems().own()){ Item item{*iitem}; own_items_uid.add(item.uniqueId()); } UniqueArray<Int64> global_items_uid; pm->allGatherVariable(own_items_uid,global_items_uid); std::sort(global_items_uid.begin(),global_items_uid.end()); UniqueArray<Byte> hash_result; hash_algo.computeHash64(asBytes(global_items_uid.constSpan()),hash_result); String hash_str = Convert::toHexaString(hash_result); info() << "HASH_RESULT family=" << family->name() << " v=" << hash_str << " expected=" << expected_hash; if (hash_str!=expected_hash) ARCANE_FATAL("Bad hash for uniqueId() for family '{0}'",family->fullName()); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: _checkUniqueIds() { IMesh* mesh = m_cartesian_mesh->mesh(); _checkUniqueIds(mesh->nodeFamily(),options()->nodesUidHash()); _checkUniqueIds(mesh->faceFamily(),options()->facesUidHash()); _checkUniqueIds(mesh->cellFamily(),options()->cellsUidHash()); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: _processPatches() { // Vérifie qu'il y a autant de patchs que d'options raffinement dans // le jeu de données (en comptant le patch 0 qui es le maillage cartésien). // Cela permet de vérifier que les appels successifs // à computeDirections() n'ajoutent pas de patchs. Integer nb_expected_patch = 1 + options()->refinement().size(); Integer nb_patch = m_cartesian_mesh->nbPatch(); if (nb_expected_patch!=nb_patch) ARCANE_FATAL("Bad number of patchs expected={0} value={1}",nb_expected_patch,nb_patch); IParallelMng* pm = parallelMng(); Int32 comm_rank = pm->commRank(); Int32 comm_size = pm->commSize(); UniqueArray<Int32> nb_cells_expected(options()->expectedNumberOfCellsInPatchs); if (nb_cells_expected.size()!=nb_patch) ARCANE_FATAL("Bad size for option '{0}'",options()->expectedNumberOfCellsInPatchs.name()); // Affiche les informations sur les patchs for( Integer i=0; i<nb_patch; ++i ){ ICartesianMeshPatch* p = m_cartesian_mesh->patch(i); CellGroup patch_cells(p->cells()); info() << "Patch cell_group=" << patch_cells.name() << " nb_cell=" << patch_cells.size(); VariableCellReal* cellv = new VariableCellReal(VariableBuildInfo(defaultMesh(),String("CellPatch")+i)); m_cell_patch_variables.add(cellv); cellv->fill(0.0); ENUMERATE_CELL(icell,patch_cells){ (*cellv)[icell] = 2.0; } CellGroup patch_own_cell = patch_cells.own(); UniqueArray<Int64> own_cells_uid; ENUMERATE_(Cell,icell,patch_own_cell){ Cell cell{*icell}; info() << "Patch i=" << i << " cell=" << ItemPrinter(*icell); own_cells_uid.add(cell.uniqueId()); } // Affiche la liste globales des uniqueId() des mailles. { UniqueArray<Int64> global_cells_uid; pm->allGatherVariable(own_cells_uid,global_cells_uid); std::sort(global_cells_uid.begin(),global_cells_uid.end()); Integer nb_global_uid = global_cells_uid.size(); info() << "GlobalUids Patch=" << i << " NB=" << nb_global_uid << " expected=" << nb_cells_expected[i]; // Vérifie que le nombre de mailles par patch est le bon. if (nb_cells_expected[i]!=nb_global_uid) ARCANE_FATAL("Bad number of cells for patch I={0} N={1} expected={2}", i,nb_cells_expected[i],nb_global_uid); for( Integer c=0; c<nb_global_uid; ++c ) info() << "GlobalUid Patch=" << i << " I=" << c << " cell_uid=" << global_cells_uid[c]; } // Exporte le patch au format SVG { String filename = String::format("Patch{0}-{1}-{2}.svg",i,comm_rank,comm_size); Directory directory = subDomain()->exportDirectory(); String full_filename = directory.file(filename); ofstream ofile(full_filename.localstr()); SimpleSVGMeshExporter exporter(ofile); exporter.write(patch_own_cell); } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: _computeCenters() { IMesh* mesh = defaultMesh(); // Calcule le centre des mailles { VariableNodeReal3& nodes_coord = mesh->nodesCoordinates(); ENUMERATE_CELL(icell,allCells()){ Cell cell = *icell; Real3 center; for( NodeEnumerator inode(cell.nodes()); inode.hasNext(); ++inode ) center += nodes_coord[inode]; center /= cell.nbNode(); m_cell_center[icell] = center; } } // Calcule le centre des faces { VariableNodeReal3& nodes_coord = mesh->nodesCoordinates(); ENUMERATE_FACE(iface,allFaces()){ Face face = *iface; Real3 center; for( NodeEnumerator inode(face.nodes()); inode.hasNext(); ++inode ) center += nodes_coord[inode]; center /= face.nbNode(); m_face_center[iface] = center; } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: _initAMR() { // Parcours les mailles actives et ajoute dans la liste des mailles // à raffiner celles qui sont contenues dans le boîte englobante // spécifiée dans le jeu de données. for( auto& x : options()->refinement() ){ m_cartesian_mesh->refinePatch2D(x->position(),x->length()); m_cartesian_mesh->computeDirections(); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: compute() { _compute1(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Calcule la densité d'une maille AMR. */ void AMRCartesianMeshTesterModule:: _computeSubCellDensity(Cell cell) { Int32 nb_children = cell.nbHChildren(); if (nb_children==0) return; // Pour les mailles AMR, la densité est la moyenne des noeuds qui la compose. for( Int32 j=0; j<nb_children; ++j ) { Real sub_density = 0.0; Cell sub_cell = cell.hChild(j); Integer sub_cell_nb_node = sub_cell.nbNode(); for( Integer k=0; k<sub_cell_nb_node; ++k ) sub_density += m_node_density[sub_cell.node(k)]; sub_density /= (Real)sub_cell_nb_node; m_density[sub_cell] =sub_density; _computeSubCellDensity(sub_cell); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: _compute1() { // Pour test, on parcours les N directions // et pour chaque maille, on modifie sa densité // par la formule new_density = (density+density_next+density_prev) / 3.0. // Effectue l'operation en deux fois. Une premiere sur les // mailles internes, et une deuxieme sur les mailles externes. // Du coup, il faut passer par une variable intermediaire (m_old_density) // mais on evite un test dans la boucle principale IMesh* mesh = defaultMesh(); Integer nb_dir = mesh->dimension(); for( Integer idir=0; idir<nb_dir; ++idir){ m_old_density.copy(m_density); CellDirectionMng cdm(m_cartesian_mesh->cellDirection(idir)); // Travail sur les mailles internes info() << "Direction=" << idir << " cells=" << cdm.innerCells().name() << " n=" << cdm.innerCells().size(); ENUMERATE_CELL(icell,cdm.innerCells()){ Cell cell = *icell; DirCell cc(cdm.cell(cell)); Cell next = cc.next(); Cell prev = cc.previous(); Real d = m_old_density[icell] + m_old_density[next] + m_old_density[prev]; m_density[icell] = d / 3.0; _computeSubCellDensity(cell); } // Travail sur les mailles externes // Test si la maille avant ou apres est nulle. ENUMERATE_CELL(icell,cdm.outerCells()){ Cell cell = *icell; DirCell cc(cdm[icell]); Cell next = cc.next(); Cell prev = cc.previous(); Real d = m_old_density[icell]; Integer n = 1; if (!next.null()){ d += m_old_density[next]; ++n; } if (!prev.null()){ d += m_old_density[prev]; ++n; } m_density[icell] = d / n; _computeSubCellDensity(cell); } } // Modifie la densité aux noeuds. // Elle sera égale à la moyenne des densités des mailles entourant ce noeud ENUMERATE_NODE(inode,mesh->allNodes()){ Node node = *inode; Integer nb_cell = node.nbCell(); Real density = 0.0; for( Integer i=0; i<nb_cell; ++i ) density += m_density[node.cell(i)]; density /= (Real)nb_cell; m_node_density[inode] = density; } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: _compute2() { // Pour test, on parcours les N directions // et pour chaque maille, on modifie sa densité // par la formule new_density = (density+density_next+density_prev) / 3.0. // A noter que cette methode ne donne pas le meme comportement que // _compute1() car les mailles de bord et internes sont mises à jour // dans un ordre différent. Integer nb_dir = defaultMesh()->dimension(); for( Integer idir=0; idir<nb_dir; ++idir){ CellDirectionMng cdm(m_cartesian_mesh->cellDirection(idir)); // Travail sur toutes les mailles ENUMERATE_CELL(icell,cdm.allCells()){ DirCell cc(cdm[icell]); Cell next = cc.next(); Cell prev = cc.previous(); Real d = m_density[icell]; Integer n = 1; if (!next.null()){ d += m_density[next]; ++n; } if (!prev.null()){ d += m_density[prev]; ++n; } m_density[icell] = d / n; } } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AMRCartesianMeshTesterModule:: _writePostProcessing() { info() << "Post-process AMR"; IPostProcessorWriter* post_processor = options()->postProcessor(); Directory output_directory = Directory(subDomain()->exportDirectory(),"amrtestpost1"); output_directory.createDirectory(); info() << "Creating output dir '" << output_directory.path() << "' for export"; UniqueArray<Real> times; times.add(m_global_time()); post_processor->setTimes(times); post_processor->setMesh(defaultMesh()); post_processor->setBaseDirectoryName(output_directory.path()); VariableList variables; //variables.add(m_density.variable()); //variables.add(m_node_density.variable()); for( VariableCellReal* v : m_cell_patch_variables ) variables.add(v->variable()); post_processor->setVariables(variables); ItemGroupList groups; groups.add(allCells()); { Integer nb_patch = m_cartesian_mesh->nbPatch(); for( Integer i=0; i<nb_patch; ++i ){ ICartesianMeshPatch* p = m_cartesian_mesh->patch(i); groups.add(p->cells()); } } post_processor->setGroups(groups); IVariableMng* vm = subDomain()->variableMng(); vm->writePostProcessing(post_processor); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_REGISTER_MODULE_AMRCARTESIANMESHTESTER(AMRCartesianMeshTesterModule); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace ArcaneTest /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
34.445669
107
0.579756
JeromeDuboisPro
7da3965752d36faf440c4d8a7e04af250c85ecdd
5,217
cc
C++
rrd/src/factory.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
40
2015-03-10T07:55:39.000Z
2021-06-11T10:13:56.000Z
rrd/src/factory.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
297
2015-04-30T10:02:04.000Z
2022-03-09T13:31:54.000Z
rrd/src/factory.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
29
2015-08-03T10:04:15.000Z
2021-11-25T12:21:00.000Z
/* ** Copyright 2011-2015 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include "com/centreon/broker/rrd/factory.hh" #include <memory> #include "com/centreon/broker/config/parser.hh" #include "com/centreon/broker/rrd/connector.hh" #include "com/centreon/exceptions/msg_fmt.hh" using namespace com::centreon::exceptions; using namespace com::centreon::broker; using namespace com::centreon::broker::rrd; /************************************** * * * Local Objects * * * **************************************/ /** * Search for a property value. * * @param[in] cfg Configuration object. * @param[in] key Key to get. * @param[in] thrw Should throw if value is not found. * @param[in] def Default value. */ static std::string find_param(config::endpoint const& cfg, std::string const& key, bool thrw = true, std::string const& def = "") { std::map<std::string, std::string>::const_iterator it{cfg.params.find(key)}; if (cfg.params.end() == it) { if (thrw) throw msg_fmt( "RRD: no '{}' defined " " for endpoint '{}'", key, cfg.name); else return def; } return it->second; } /** * Check if a configuration match the RRD layer. * * @param[in] cfg Endpoint configuration. * * @return True if the configuration matches the RRD layer. */ bool factory::has_endpoint(config::endpoint& cfg, io::extension* ext) { if (ext) *ext = io::extension("RRD", false, false); return cfg.type == "rrd"; } /** * Build a RRD endpoint from a configuration. * * @param[in] cfg Endpoint configuration. * @param[out] is_acceptor Will be set to false. * @param[in] cache Unused. * * @return Endpoint matching the given configuration. */ io::endpoint* factory::new_endpoint( config::endpoint& cfg, bool& is_acceptor, std::shared_ptr<persistent_cache> cache) const { (void)cache; // Local socket path. std::string path{find_param(cfg, "path", false)}; // Network connection. unsigned short port{0}; { try { port = static_cast<uint16_t>( std::stoul(find_param(cfg, "port", false, "0"))); } catch (...) { throw msg_fmt( "RRD: bad port" " defined " " for endpoint '{}'", cfg.name); } } // Get rrd creator cache size. uint32_t cache_size(16); { std::map<std::string, std::string>::const_iterator it{ cfg.params.find("cache_size")}; if (it != cfg.params.end()) try { cache_size = std::stoul(it->second); } catch (std::exception const& e) { throw msg_fmt( "RRD: bad port" " defined " " for endpoint '{}'", cfg.name); } } // Should metrics be written ? bool write_metrics; { std::map<std::string, std::string>::const_iterator it( cfg.params.find("write_metrics")); if (it != cfg.params.end()) write_metrics = config::parser::parse_boolean(it->second); else write_metrics = true; } // Should status be written ? bool write_status; { std::map<std::string, std::string>::const_iterator it{ cfg.params.find("write_status")}; if (it != cfg.params.end()) write_status = config::parser::parse_boolean(it->second); else write_status = true; } // Get metrics RRD path. std::string metrics_path{write_metrics ? find_param(cfg, "metrics_path") : ""}; // Get status RRD path. std::string status_path{write_status ? find_param(cfg, "status_path") : ""}; // Ignore update errors (2.4.0-compatible behavior). bool ignore_update_errors; { std::map<std::string, std::string>::const_iterator it{ cfg.params.find("ignore_update_errors")}; if (it != cfg.params.end()) ignore_update_errors = config::parser::parse_boolean(it->second); else ignore_update_errors = true; } // Create endpoint. std::unique_ptr<rrd::connector> endp{new rrd::connector}; if (write_metrics) endp->set_metrics_path(metrics_path); if (write_status) endp->set_status_path(status_path); if (!path.empty()) endp->set_cached_local(path); else if (port) endp->set_cached_net(port); endp->set_cache_size(cache_size); endp->set_write_metrics(write_metrics); endp->set_write_status(write_status); endp->set_ignore_update_errors(ignore_update_errors); is_acceptor = false; return endp.release(); }
28.664835
78
0.607437
centreon-lab
7da3dcf9ddee43685c8567fd00efdefea85b9be0
2,528
cpp
C++
3rd_party/occa/src/occa/internal/lang/type/functionPtr.cpp
RonRahaman/nekRS
ffc02bca33ece6ba3330c4ee24565b1c6b5f7242
[ "BSD-3-Clause" ]
312
2015-07-02T09:02:09.000Z
2022-03-30T16:13:23.000Z
3rd_party/occa/src/occa/internal/lang/type/functionPtr.cpp
neams-th-coe/nekRS
5d2c8ab3d14b3fb16db35682336a1f96000698bb
[ "BSD-3-Clause" ]
520
2015-07-12T18:32:38.000Z
2022-03-31T16:15:00.000Z
3rd_party/occa/src/occa/internal/lang/type/functionPtr.cpp
neams-th-coe/nekRS
5d2c8ab3d14b3fb16db35682336a1f96000698bb
[ "BSD-3-Clause" ]
79
2015-07-22T22:10:56.000Z
2022-03-17T09:07:01.000Z
#include <occa/internal/lang/type/functionPtr.hpp> #include <occa/internal/lang/variable.hpp> namespace occa { namespace lang { functionPtr_t::functionPtr_t() : type_t(), returnType(), isBlock(false) {} functionPtr_t::functionPtr_t(const vartype_t &returnType_, identifierToken &nameToken) : type_t(nameToken), returnType(returnType_), isBlock(false) {} functionPtr_t::functionPtr_t(const vartype_t &returnType_, const std::string &name_) : type_t(name_), returnType(returnType_), isBlock(false) {} functionPtr_t::functionPtr_t(const functionPtr_t &other) : type_t(other), returnType(other.returnType), args(other.args), isBlock(other.isBlock) {} int functionPtr_t::type() const { return typeType::functionPtr; } type_t& functionPtr_t::clone() const { return *(new functionPtr_t(*this)); } bool functionPtr_t::isPointerType() const { return true; } void functionPtr_t::addArgument(const variable_t &arg) { args.push_back(arg); } void functionPtr_t::addArguments(const variableVector &args_) { const int count = (int) args_.size(); for (int i = 0; i < count; ++i) { args.push_back(args_[i]); } } dtype_t functionPtr_t::dtype() const { return dtype::byte; } bool functionPtr_t::equals(const type_t &other) const { const functionPtr_t &other_ = other.to<functionPtr_t>(); const int argSize = (int) args.size(); if ((isBlock != other_.isBlock) || (argSize != (int) other_.args.size())) { return false; } if (returnType != other_.returnType) { return false; } for (int i = 0; i < argSize; ++i) { if (args[i].vartype != other_.args[i].vartype) { return false; } } return true; } void functionPtr_t::printDeclaration(printer &pout) const { if (!isBlock) { returnType.printDeclaration(pout, "(*" + name()); } else { returnType.printDeclaration(pout, "(^" + name()); } pout << ')'; pout << '('; const std::string argIndent = pout.indentFromNewline(); const int argCount = (int) args.size(); for (int i = 0; i < argCount; ++i) { if (i) { pout << ",\n" << argIndent; } args[i].printDeclaration(pout); } pout << ')'; } } }
26.061856
67
0.56606
RonRahaman
7da503332eb9c01fe8a27c3e8922159a23d89e29
752
cpp
C++
baekjoon/11727.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
baekjoon/11727.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
baekjoon/11727.cpp
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
/* 11727 : 2×n 타일링 2 URL : https://www.acmicpc.net/problem/11727 Input #1 : 2 Output #1 : 3 Input #2 : 8 Output #2 : 171 Input #3 : 12 Output #3 : 2731 */ #include <iostream> #include <cstring> #define MAX_N 1001 #define MOD 10007 using namespace std; int cache[MAX_N]; int tiling(int width) { int &ret = cache[width]; if (width <= 1) { return 1; } if (ret != -1) { return ret; } ret = (tiling(width - 1) + (2 * tiling(width - 2))) % MOD; return ret; } int main(int argc, char const *argv[]) { int n; memset(&(cache[0]), -1, sizeof(int) * MAX_N); cin >> n; cout << tiling(n); return 0; }
13.192982
62
0.486702
GihwanKim
7da5cf270a212137dd4cf4cd4675ec43c6c03dec
10,982
hpp
C++
viennagrid/algorithm/geometry.hpp
viennagrid/viennagrid-dev
6e47c8d098a0b691d6b9988f2444cd11d440f4c2
[ "MIT" ]
7
2015-09-13T03:50:58.000Z
2019-06-27T14:24:49.000Z
viennagrid/algorithm/geometry.hpp
viennagrid/viennagrid-dev
6e47c8d098a0b691d6b9988f2444cd11d440f4c2
[ "MIT" ]
null
null
null
viennagrid/algorithm/geometry.hpp
viennagrid/viennagrid-dev
6e47c8d098a0b691d6b9988f2444cd11d440f4c2
[ "MIT" ]
5
2015-07-03T07:14:15.000Z
2021-05-20T00:51:58.000Z
#ifndef VIENNAGRID_ALGORITHM_GEOMETRY_HPP #define VIENNAGRID_ALGORITHM_GEOMETRY_HPP /* ======================================================================= Copyright (c) 2011-2014, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include <limits> #include "viennagrid/mesh/mesh.hpp" #include "viennagrid/topology/quadrilateral.hpp" #include "viennagrid/algorithm/inner_prod.hpp" #include "viennagrid/algorithm/norm.hpp" #include "viennagrid/algorithm/cross_prod.hpp" #include "viennagrid/algorithm/detail/numeric.hpp" /** @file viennagrid/algorithm/geometry.hpp @brief Contains various functions for computing geometric quantities */ namespace viennagrid { namespace detail { /** @brief Implementation for calculating a normal vector of a vertex in 1D */ template<typename PointAccessorT, typename ElementT> typename PointAccessorT::value_type normal_vector_impl( PointAccessorT const point_accessor, ElementT const & element, viennagrid::vertex_tag, viennagrid::dimension_tag<1>) { typedef typename PointAccessorT::value_type PointType; (void)point_accessor; (void)element; return PointType(1.0); } /** @brief Implementation for calculating a normal vector of a line in 2D */ template<typename PointAccessorT, typename ElementT> typename PointAccessorT::value_type normal_vector_impl( PointAccessorT const point_accessor, ElementT const & element, viennagrid::line_tag, viennagrid::dimension_tag<2>) { typedef typename PointAccessorT::value_type PointType; PointType const & p0 = point_accessor( viennagrid::vertices(element)[0] ); PointType const & p1 = point_accessor( viennagrid::vertices(element)[1] ); PointType line = p1-p0; std::swap(line[0], line[1]); line[0] = -line[0]; return line; } /** @brief Implementation for calculating a normal vector of a triangle in 3D */ template<typename PointAccessorT, typename ElementT> typename PointAccessorT::value_type normal_vector_impl( PointAccessorT const point_accessor, ElementT const & element, viennagrid::triangle_tag, viennagrid::dimension_tag<3>) { typedef typename PointAccessorT::value_type PointType; PointType const & p0 = point_accessor( viennagrid::vertices(element)[0] ); PointType const & p1 = point_accessor( viennagrid::vertices(element)[1] ); PointType const & p2 = point_accessor( viennagrid::vertices(element)[2] ); return viennagrid::cross_prod( p1-p0, p2-p0 ); } /** @brief Implementation for calculating a normal vector of a quadrilateral in 3D. * * Reuses the implementation for a triangle. */ template<typename PointAccessorT, typename ElementT> typename PointAccessorT::value_type normal_vector_impl( PointAccessorT const point_accessor, ElementT const & element, viennagrid::quadrilateral_tag, viennagrid::dimension_tag<3>) { return normal_vector_impl(point_accessor, element, viennagrid::triangle_tag(), viennagrid::dimension_tag<3>()); } } /** @brief Calculates the normal vector of an element * * @param point_accessor Point accessor for input points * @param element The input element */ template<typename PointAccessorT, typename ElementT> typename PointAccessorT::value_type normal_vector( PointAccessorT const point_accessor, ElementT const & element ) { typedef typename viennagrid::result_of::element_tag<ElementT>::type ElementTag; typedef typename PointAccessorT::value_type PointType; typedef viennagrid::dimension_tag< result_of::static_size<PointType>::value > DimensionTag; return detail::normal_vector_impl( point_accessor, element, ElementTag(), DimensionTag() ); } /** @brief Calculates the normal vector of an element * * @param element The input element */ template<typename ElementT> typename viennagrid::result_of::point<ElementT>::type normal_vector( ElementT const & element ) { return normal_vector( default_point_accessor(element), element ); } /** @brief Calculates the determinant of a 1x1 matrix with the columns provided as 1D-points * * @param p0 The first column/point */ template<typename PointT> typename viennagrid::result_of::coord<PointT>::type determinant( PointT const & p0) { return p0[0]; } /** @brief Calculates the determinant of a 2x2 matrix with the columns provided as 2D-points * * @param p0 The first column * @param p1 The second column */ template<typename PointT> typename viennagrid::result_of::coord<PointT>::type determinant( PointT const & p0, PointT const & p1 ) { return p0[0]*p1[1] - p0[1]*p1[0]; } /** @brief Calculates the determinant of a 3x3 matrix with the columns provided as 3D-points * * @param p0 The first column * @param p1 The second column * @param p2 The third column */ template<typename PointT> typename viennagrid::result_of::coord<PointT>::type determinant( PointT const & p0, PointT const & p1, PointT const & p2 ) { return p0[0]*p1[1]*p2[2] + p1[0]*p2[1]*p0[2] + p2[0]*p0[1]*p1[2] - p0[2]*p1[1]*p2[0] - p1[2]*p2[1]*p0[0] - p2[2]*p0[1]*p1[0]; } /** @brief Calculates the bounding box of a point iterator range. A pair of points is return, where the first represents the coordinate-wise minimum and the second represents the coordinate-wise maximum. * * @param it The start point iterator * @param it_end The end point iterator */ template<typename PointIteratorT> std::pair< typename std::iterator_traits<PointIteratorT>::value_type, typename std::iterator_traits<PointIteratorT>::value_type > bounding_box( PointIteratorT it, PointIteratorT const & it_end ) { typedef typename std::iterator_traits<PointIteratorT>::value_type PointType; typedef typename viennagrid::result_of::coord<PointType>::type NumericType; PointType lower_left; PointType upper_right; std::fill( lower_left.begin(), lower_left.end(), std::numeric_limits<NumericType>::max() ); std::fill( upper_right.begin(), upper_right.end(), - std::numeric_limits<NumericType>::max() ); //std::fill( upper_right.begin(), upper_right.end(), std::numeric_limits<NumericType>::lowest() ); C++11 for (; it != it_end; ++it ) { lower_left = viennagrid::min( lower_left, *it ); upper_right = viennagrid::max( upper_right, *it ); } return std::make_pair( lower_left, upper_right ); } /** @brief Calculates the bounding box a mesh. A pair of points is return, where the first represents the coordinate-wise minimum and the second represents the coordinate-wise maximum. * * @param mesh The input mesh */ template<typename MeshT> std::pair< typename viennagrid::result_of::point<MeshT>::type, typename viennagrid::result_of::point<MeshT>::type > bounding_box( MeshT const & mesh ) { typedef typename viennagrid::result_of::point<MeshT>::type PointType; typedef typename viennagrid::result_of::coord<MeshT>::type NumericType; PointType lower_left; PointType upper_right; std::fill( lower_left.begin(), lower_left.end(), std::numeric_limits<NumericType>::max() ); std::fill( upper_right.begin(), upper_right.end(), - std::numeric_limits<NumericType>::max() ); //std::fill( upper_right.begin(), upper_right.end(), std::numeric_limits<NumericType>::lowest() ); C++11 typedef typename viennagrid::result_of::const_vertex_range<MeshT>::type ConstVertexRangeType; typedef typename viennagrid::result_of::iterator<ConstVertexRangeType>::type ConstVertexIteratorType; ConstVertexRangeType vertices(mesh); for (ConstVertexIteratorType vit = vertices.begin(); vit != vertices.end(); ++vit) { lower_left = viennagrid::min( lower_left, viennagrid::point(*vit) ); upper_right = viennagrid::max( upper_right, viennagrid::point(*vit) ); } return std::make_pair( lower_left, upper_right ); } /** @brief Calculates the size of a mesh: ||bounding_box.min - bounding_box.max|| * * @param mesh The input mesh */ template<typename MeshT> typename viennagrid::result_of::coord<MeshT>::type mesh_size( MeshT const & mesh ) { std::pair< typename viennagrid::result_of::point<MeshT>::type, typename viennagrid::result_of::point<MeshT>::type > bb = bounding_box(mesh); return viennagrid::norm_2(bb.second - bb.first); } /** @brief Makes a vector orthogonal to a set of linearly independent orthogonal vectors (Gram–Schmidt process step) * * @param it The begin vector iterator of the linearly independent orthogonal vector set * @param end The end vector iterator of the linearly independent orthogonal vector set * @param vec The vector to orthogonalize */ template<typename VectorIteratorT, typename VectorT> VectorT orthogonalize_vector( VectorIteratorT it, VectorIteratorT const & end, VectorT vec ) { for (; it != end; ++it) vec -= viennagrid::inner_prod( vec, *it ) / viennagrid::inner_prod( *it, *it ) * (*it); return vec; } /** @brief Makes a set of vectors orthogonal (Gram–Schmidt process step). * * If linearly dependent vectors are encountered, they are moved/swapped to the end of the sequence. * * @param start The begin vector iterator of the vector set to orthogonalize * @param end The end vector iterator of the vector set to orthogonalize * @param nc Numeric config * * @return Number of linearly independent vectors found during the process */ template<typename IteratorT, typename NumericConfigT> std::size_t orthogonalize( IteratorT start, IteratorT end, NumericConfigT nc ) { typedef typename std::iterator_traits<IteratorT>::value_type vector_type; typedef typename viennagrid::result_of::coord<vector_type>::type coord_type; std::size_t count = 0; for (IteratorT n = start; n != end;) { *n = orthogonalize_vector(start, n, *n); if ( viennagrid::norm_1(*n) < detail::absolute_tolerance<coord_type>(nc) ) { --end; std::swap(*n, *end); } else { ++n; ++count; } } return count; } } #endif
36.364238
205
0.664087
viennagrid
7da76807c52c0d703a05f4f77c3cb7c33747c03d
393
cpp
C++
Uva-494 - Kindergarten Counting Game.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
1
2020-11-02T22:18:22.000Z
2020-11-02T22:18:22.000Z
Uva-494 - Kindergarten Counting Game.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
null
null
null
Uva-494 - Kindergarten Counting Game.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<cstring> #include<cstdio> using namespace std; int main() { int count = 0,k=0; string str; while (getline(cin, str)) { for (int i = 0; i<str.length(); i++) { if ((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')) { k = 1; } else { count += k; k = 0; } } cout << count << endl; count = 0; } }
14.035714
68
0.486005
Samim-Arefin
7da86fdc3a6b20c376e6cc5be514261b4b395669
2,448
cpp
C++
src/main.cpp
zhitko/speech-rate-meter
6414215f15c4c21bb5afe4bf16dcdbc4164d8f57
[ "MIT" ]
4
2021-03-14T09:47:58.000Z
2021-08-05T10:15:15.000Z
src/main.cpp
zhitko/speech-rate-meter
6414215f15c4c21bb5afe4bf16dcdbc4164d8f57
[ "MIT" ]
3
2021-05-21T09:39:16.000Z
2022-03-28T13:17:31.000Z
src/main.cpp
zhitko/speech-rate-meter
6414215f15c4c21bb5afe4bf16dcdbc4164d8f57
[ "MIT" ]
1
2021-05-05T21:07:32.000Z
2021-05-05T21:07:32.000Z
#include <QtWidgets/QApplication> #include <QQmlApplicationEngine> #include <QFileInfo> #include <QStringList> #include <QDirIterator> #include <QDir> #include <QDateTime> #include <QTextCodec> #include "backend.h" #include "settings.h" #include "applicationconfig.h" #include "qml/qmlfileinfo.h" #include "qml/qmlpoint.h" #include "3party/RadialBar/radialbar.h" void cleanDataDir(); static const QtMessageHandler QT_DEFAULT_MESSAGE_HANDLER = qInstallMessageHandler(0); void logToFile(const QString message) { QFile file("logs.txt"); if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) { QTextStream stream(&file); stream << message << endl; } } void messageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); QString message = QString("%1: %2").arg( QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss:zzz "), QString(localMsg.constData()) ); logToFile(message); (*QT_DEFAULT_MESSAGE_HANDLER)(type, context, message); } int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #ifndef ANDROID qputenv("QT_SCALE_FACTOR", "0.75"); #endif qInstallMessageHandler(messageOutput); QApplication app(argc, argv); qmlRegisterType<RadialBar>("RadialBar", 1, 0, "RadialBar"); qmlRegisterType<Backend>("intondemo.backend", 1, 0, "Backend"); qmlRegisterType<Settings>("intondemo.settings", 1, 0, "Settings"); qRegisterMetaType<QmlFileInfo>("FileInfo"); qRegisterMetaType<QmlPoint>("Point"); QQmlApplicationEngine engine; Settings::getInstance(&app); const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); auto result = QApplication::exec(); #ifdef ANDROID cleanDataDir(); #endif return result; } void cleanDataDir() { QDir dataDir(ApplicationConfig::GetFullDataPath()); QStringList allFiles = dataDir.entryList(ApplicationConfig::WaveFileFilter, QDir::NoDotAndDotDot | QDir::Files); foreach(auto file, allFiles) { QDir dir; dir.remove(dataDir.absoluteFilePath(file)); } }
26.608696
116
0.688725
zhitko
7dad3646cc4818631270df897879dca9c9f89008
288
cpp
C++
Core/Surface.cpp
zgub4/op3d
2a9a01b3b7666f4ef1afcb279530c57126e3baa8
[ "Apache-2.0" ]
2
2017-03-02T15:40:58.000Z
2017-05-19T07:58:05.000Z
Core/Surface.cpp
zgub4/op3d
2a9a01b3b7666f4ef1afcb279530c57126e3baa8
[ "Apache-2.0" ]
2
2017-04-05T01:50:36.000Z
2017-04-06T09:20:12.000Z
Core/Surface.cpp
zgub4/op3d
2a9a01b3b7666f4ef1afcb279530c57126e3baa8
[ "Apache-2.0" ]
null
null
null
#include "Surface.h" #include <stdexcept> void op3d::Surface::create(const VkInstance& instance, GLFWwindow* window) { if (glfwCreateWindowSurface(instance, window, nullptr, replace()) != VK_SUCCESS) { throw std::runtime_error("Failed to create VkSurfaceKHR!"); } }
24
84
0.697917
zgub4
7dafe8bed18d89d649b3d442050edc5458882964
3,276
cpp
C++
lab01/LoadedDie.cpp
jrgoldfinemiddleton/cs162
dea72d9219e748e15a5796177a6b018bcab7816e
[ "BSD-2-Clause" ]
3
2016-11-04T20:18:46.000Z
2019-04-22T05:00:03.000Z
lab01/LoadedDie.cpp
jrgoldfinemiddleton/cs162
dea72d9219e748e15a5796177a6b018bcab7816e
[ "BSD-2-Clause" ]
1
2016-11-04T20:23:25.000Z
2016-11-04T20:23:45.000Z
lab01/LoadedDie.cpp
jrgoldfinemiddleton/cs162
dea72d9219e748e15a5796177a6b018bcab7816e
[ "BSD-2-Clause" ]
6
2015-12-25T16:14:46.000Z
2019-04-22T05:00:04.000Z
/********************************************************************* ** Program Filename: LoadedDie.cpp ** Author: Jason Goldfine-Middleton ** Date: 09/26/15 ** Description: The LoadedDie class implementation file. ** Input: N/A ** Output: N/A *********************************************************************/ #include "LoadedDie.hpp" #include <cstdlib> // for rand() /********************************************************************* ** Function: LoadedDie() ** Description: Constructs a LoadedDie. ** Parameters: sides - the number of sides ** Pre-Conditions: sides must be positive ** Post-Conditions: distributionArr will point to an array on the ** heap; the array will be filled with values equal ** to those of the sides of the LoadedDie, with ** greater values occurring more frequently *********************************************************************/ LoadedDie::LoadedDie(int sides) { numSides = sides; // map a random value to a side of a loaded die distributionArr = new int[sumSides()]; // where to start putting the next die value int startIndex = 0; // fill up the distribution array such that the higher the side // of the die is, the more random values (indices) will match it for (int sideValue = 1; sideValue <= numSides; ++sideValue) { int endIndex = startIndex + sideValue; for (int index = startIndex; index < endIndex; ++index) { distributionArr[index] = sideValue; } startIndex = endIndex; } } /********************************************************************* ** Function: ~LoadedDie() ** Description: The destructor for LoadedDie. ** Parameters: N/A ** Pre-Conditions: distributionArr is not deallocated ** Post-Conditions: distributionArr is deallocated *********************************************************************/ LoadedDie::~LoadedDie() { delete distributionArr; } /********************************************************************* ** Function: getRoll() ** Description: Rolls the LoadedDie, returning a value between 1 and ** the number of sides. ** Parameters: none ** Pre-Conditions: srand() must have already been run; distributionArr ** must contain sumSides() elements ranging in value ** from 1 to numSides ** Post-Conditions: an integer value between 1 and the number of sides ** is returned *********************************************************************/ int LoadedDie::getRoll() { int distributionIndex = rand() % sumSides(); int roll = distributionArr[distributionIndex]; return roll; } /********************************************************************* ** Function: sumSides() ** Description: Returns the sum of all values on the sides of the ** LoadedDie. ** Parameters: none ** Pre-Conditions: none ** Post-Conditions: the sum of all sides is returned *********************************************************************/ int LoadedDie::sumSides() { int sum = 0; for (int sideValue = 1; sideValue <= numSides; ++sideValue) { sum += sideValue; } return sum; }
30.90566
71
0.502137
jrgoldfinemiddleton
7db33c0b3176bdacbd16de10c56795ea0457a18c
4,384
cpp
C++
oskar/settings/test/Test_DateTime.cpp
happyseayou/OSKAR
3fb995ed39deb6b11da12524e8e30f0ca8f9c39b
[ "BSD-3-Clause" ]
46
2015-12-15T14:24:16.000Z
2022-01-24T16:54:49.000Z
oskar/settings/test/Test_DateTime.cpp
happyseayou/OSKAR
3fb995ed39deb6b11da12524e8e30f0ca8f9c39b
[ "BSD-3-Clause" ]
37
2016-08-04T17:53:03.000Z
2022-03-10T10:22:01.000Z
oskar/settings/test/Test_DateTime.cpp
happyseayou/OSKAR
3fb995ed39deb6b11da12524e8e30f0ca8f9c39b
[ "BSD-3-Clause" ]
32
2016-05-09T10:30:11.000Z
2022-01-26T07:55:27.000Z
/* * Copyright (c) 2015-2021, The OSKAR Developers. * See the LICENSE file at the top-level directory of this distribution. */ #include <gtest/gtest.h> #include "settings/oskar_settings_types.h" #include <cstdio> using namespace std; using namespace oskar; TEST(settings_types, DateTime) { /* * d-M-yyyy h:m:s[.z] - British style * yyyy/M/d/h:m:s[.z] - CASA style * yyyy-M-d h:m:s[.z] - International style * yyyy-M-dTh:m:s[.z] - ISO date style * MJD */ DateTime t; // British style { EXPECT_TRUE(t.set_default("1-2-2015 10:05:23.2")); EXPECT_TRUE(t.is_default()); EXPECT_STREQ("01-02-2015 10:05:23.2", t.get_value()); } // CASA style { EXPECT_TRUE(t.set_value("2015/1/2/03:04:05.6")); EXPECT_FALSE(t.is_default()); EXPECT_STREQ("2015/01/02/03:04:05.6", t.get_value()); } // International style { EXPECT_TRUE(t.set_value("2015-2-3 04:05:06.7")); EXPECT_FALSE(t.is_default()); EXPECT_DOUBLE_EQ(6.7, t.value().seconds); EXPECT_DOUBLE_EQ(23.2, t.default_value().seconds); EXPECT_STREQ("2015-02-03 04:05:06.7", t.get_value()); } // International style { EXPECT_TRUE(t.set_value("2015-12-31 23:59:59.0")); EXPECT_FALSE(t.is_default()); EXPECT_DOUBLE_EQ(59.0, t.value().seconds); EXPECT_EQ(59, t.value().minutes); EXPECT_EQ(23, t.value().hours); EXPECT_EQ(31, t.value().day); EXPECT_EQ(12, t.value().month); EXPECT_EQ(2015, t.value().year); EXPECT_DOUBLE_EQ(23.2, t.default_value().seconds); EXPECT_STREQ("2015-12-31 23:59:59.0", t.get_value()); } // ISO style { EXPECT_TRUE(t.set_value("2015-3-4T05:06:07.8910111213")); EXPECT_FALSE(t.is_default()); } // MJD1 { double mjd = t.to_mjd(); double mjd2 = t.to_mjd_2(); EXPECT_DOUBLE_EQ(mjd, mjd2); t.from_mjd(mjd); EXPECT_DOUBLE_EQ(mjd, t.to_mjd()); } // MJD2 { double mjd = 46113.7511111; t.from_mjd(mjd); EXPECT_DOUBLE_EQ(mjd, t.to_mjd()); EXPECT_EQ(DateTime::MJD, t.format()); } { DateTime t1; EXPECT_TRUE(t1.set_value("46113.7654321")); EXPECT_EQ(DateTime::MJD, t1.format()); EXPECT_STREQ("46113.7654321", t1.get_value()); EXPECT_DOUBLE_EQ(46113.7654321, t1.to_mjd()); } { DateTime t1; t1.set_value("45464844.54646541"); EXPECT_STREQ("45464844.546465", t1.get_value()); } // Failure modes. // British style { EXPECT_FALSE(t.set_value("01-13-2015 10:05:23.2")); EXPECT_FALSE(t.set_value("00-12-2015 10:05:23.2")); EXPECT_FALSE(t.set_value("01-12-2015 25:05:23.2")); EXPECT_FALSE(t.set_value("01-12-2015 22:60:23.2")); EXPECT_FALSE(t.set_value("01-12-2015 22:59:61.2")); } // CASA style { EXPECT_FALSE(t.set_value("2015/13/1/03:04:05.6")); EXPECT_FALSE(t.set_value("2015/12/0/03:04:05.6")); EXPECT_FALSE(t.set_value("2015/12/1/25:04:05.6")); EXPECT_FALSE(t.set_value("2015/12/1/22:60:05.6")); EXPECT_FALSE(t.set_value("2015/12/1/22:59:61.6")); } // International style { EXPECT_FALSE(t.set_value("2015-13-1 04:05:06.7")); EXPECT_FALSE(t.set_value("2015-12-33 04:05:06.7")); EXPECT_FALSE(t.set_value("2015-12-0 04:05:06.7")); EXPECT_FALSE(t.set_value("2015-12-1 25:05:06.7")); EXPECT_FALSE(t.set_value("2015-12-1 22:60:06.7")); EXPECT_FALSE(t.set_value("2015-12-1 22:59:61.7")); } // ISO style { EXPECT_FALSE(t.set_value("2015-13-4T05:06:07.8910111213")); EXPECT_FALSE(t.set_value("2015-12-0T05:06:07.8910111213")); EXPECT_FALSE(t.set_value("2015-12-1T25:06:07.8910111213")); EXPECT_FALSE(t.set_value("2015-12-1T22:60:07.8910111213")); EXPECT_FALSE(t.set_value("2015-12-1T22:59:67.8910111213")); } // Comparisons. { DateTime t1, t2; EXPECT_TRUE(t1.set_value("1-2-2015 10:05:23.2")); EXPECT_TRUE(t2.set_value("1-2-2015 10:05:23.2")); EXPECT_TRUE(t1 == t2); EXPECT_TRUE(t1.set_value("1-2-2015 10:05:23.2")); EXPECT_TRUE(t2.set_value("1-2-2015 10:06:23.2")); EXPECT_TRUE(t2 > t1); } }
32.235294
72
0.584398
happyseayou
7db6756ae7222f4da506e70a3ff1f6a58eb28567
545
hpp
C++
include/Client.hpp
SokolovVadim/Server
4d69a5bee42173b3a8e37dfa2dcd62d7aba25a93
[ "MIT" ]
null
null
null
include/Client.hpp
SokolovVadim/Server
4d69a5bee42173b3a8e37dfa2dcd62d7aba25a93
[ "MIT" ]
null
null
null
include/Client.hpp
SokolovVadim/Server
4d69a5bee42173b3a8e37dfa2dcd62d7aba25a93
[ "MIT" ]
null
null
null
// // Created by vadim on 15.08.19. // #ifndef SERVER_CLIENT_HPP #define SERVER_CLIENT_HPP #include "Inet.hpp" #include "Subroutine.hpp" void ClientRoutine(const std::string & script_name); void ExecuteScript(const std::string & script_name); class Client { public: Client(); ~Client(); void Init(); void AssignPort(); int Connect(); void UploadData(const char* filename, int sockfd); sockaddr_in* getServAddr() const; private: int sockfd_; struct sockaddr_in * servaddr_; }; #endif //SERVER_CLIENT_HPP
18.166667
54
0.695413
SokolovVadim
7db68987b9886e429db35e11547376b8bfd58222
6,683
cpp
C++
plugins/src/amxinfo.cpp
SL-RP/PawnPlus
be9c7bf801d4338516f930817d295f2a51754bdc
[ "MIT" ]
79
2018-03-07T22:49:20.000Z
2022-03-31T04:55:30.000Z
plugins/src/amxinfo.cpp
SL-RP/PawnPlus
be9c7bf801d4338516f930817d295f2a51754bdc
[ "MIT" ]
45
2018-07-13T20:57:40.000Z
2022-02-01T17:55:34.000Z
plugins/src/amxinfo.cpp
SL-RP/PawnPlus
be9c7bf801d4338516f930817d295f2a51754bdc
[ "MIT" ]
29
2018-03-23T08:22:02.000Z
2022-02-13T22:59:50.000Z
#include "amxinfo.h" #include "natives.h" #include "modules/tags.h" #include "modules/amxutils.h" #include <unordered_map> #include "subhook/subhook.h" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <signal.h> #include <setjmp.h> #endif struct natives_extra : public amx::extra { natives_extra(AMX *amx) : extra(amx) { } natives_extra(AMX *amx, const std::unordered_map<std::string, AMX_NATIVE> &natives) : extra(amx), natives(natives) { } std::unordered_map<std::string, AMX_NATIVE> natives; virtual std::unique_ptr<extra> clone() override { return std::unique_ptr<extra>(new natives_extra(_amx, natives)); } }; static std::unordered_map<AMX*, std::shared_ptr<amx::instance>> amx_map; bool amx::valid(AMX *amx) { return amx_map.find(amx) != amx_map.end(); } void amx::call_all(void(*func)(void *cookie, AMX *amx), void *cookie) { for(const auto &pair : amx_map) { if(pair.second->valid()) { func(cookie, pair.first); } } } // Nothing should be loaded from the AMX here, since it may not even be initialized yet const amx::object &amx::load_lock(AMX *amx) { auto it = amx_map.find(amx); if(it != amx_map.end()) { return it->second; } return amx_map.emplace(amx, std::make_shared<instance>(amx)).first->second; } const amx::object &amx::clone_lock(AMX *amx, AMX *new_amx) { const auto &obj = load_lock(amx); return amx_map.emplace(new_amx, std::make_shared<instance>(*obj, new_amx)).first->second; } bool amx::unload(AMX *amx) { auto it = amx_map.find(amx); if(it != amx_map.end()) { amx_map.erase(it); return true; } return false; } bool amx::invalidate(AMX *amx) { auto it = amx_map.find(amx); if(it != amx_map.end()) { it->second->invalidate(); return true; } return false; } void amx::register_natives(AMX *amx, const AMX_NATIVE_INFO *nativelist, int number) { const auto &obj = load_lock(amx); auto &natives = obj->get_extra<natives_extra>().natives; for(int i = 0; (i < number || number == -1) && nativelist[i].name != nullptr; i++) { natives.insert(std::make_pair(nativelist[i].name, nativelist[i].func)); } obj->run_initializers(); } AMX_NATIVE amx::try_decode_native(const char *str) { if(str[0] == 0x1C) { auto name = reinterpret_cast<const unsigned char *>(str + 1); ucell value; if(amx_decode_value(name, value)) { return reinterpret_cast<AMX_NATIVE>(value); } } return nullptr; } AMX_NATIVE amx::find_native(AMX *amx, const char *name) { auto decoded = try_decode_native(name); if(decoded != nullptr) { return decoded; } return amx::find_native(amx, std::string(name)); } AMX_NATIVE amx::find_native(AMX *amx, const std::string &name) { auto decoded = try_decode_native(name.c_str()); if(decoded != nullptr) { return decoded; } const auto &obj = load_lock(amx); auto &natives = obj->get_extra<natives_extra>().natives; auto it = natives.find(name); if(it != natives.end()) { return it->second; } int index; if(!amx_FindNative(amx, name.c_str(), &index)) { auto amxhdr = (AMX_HEADER*)amx->base; auto func = (AMX_FUNCSTUB*)((unsigned char*)amxhdr+ amxhdr->natives + index* amxhdr->defsize); auto f = reinterpret_cast<AMX_NATIVE>(func->address); natives.insert(std::make_pair(name, f)); return f; } return nullptr; } size_t amx::num_natives(AMX *amx) { const auto &obj = load_lock(amx); auto &natives = obj->get_extra<natives_extra>().natives; return natives.size(); } #ifdef _WIN32 bool filter_exception(DWORD code) { switch(code) { case EXCEPTION_ACCESS_VIOLATION: case EXCEPTION_INT_DIVIDE_BY_ZERO: return true; default: return false; } } #else sigjmp_buf jmp; void signal_handler(int signal) { siglongjmp(jmp, signal); } #endif cell call_external_native(AMX *amx, AMX_NATIVE native, cell *params) { #ifdef _DEBUG return native(amx, params); #elif defined _WIN32 DWORD error; __try{ return native(amx, params); }__except(filter_exception(error = GetExceptionCode()) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { amx_LogicError(errors::unhandled_system_exception, error); } #else int error = sigsetjmp(jmp, true); if(error) { amx_LogicError(errors::unhandled_system_exception, error); } struct sigaction act, oldact; memset(&act, 0, sizeof(act)); act.sa_handler = signal_handler; act.sa_flags = SA_RESETHAND; sigaction(SIGSEGV, &act, &oldact); cell result = native(amx, params); sigaction(SIGSEGV, &oldact, nullptr); return result; #endif } cell amx::dynamic_call(AMX *amx, AMX_NATIVE native, cell *params, tag_ptr &out_tag) { cell result; amx->error = AMX_ERR_NONE; native_return_tag = nullptr; auto it = impl::runtime_native_map().find(native); if(it != impl::runtime_native_map().end() && subhook_read_dst(reinterpret_cast<void*>(native)) == nullptr) { const auto &info = it->second; try{ if(params[0] < info.arg_count * static_cast<cell>(sizeof(cell))) { amx_FormalError(errors::not_enough_args, info.arg_count, params[0] / static_cast<cell>(sizeof(cell))); } result = info.inner(amx, params); if(info.tag_uid != tags::tag_unknown) { native_return_tag = tags::find_tag(info.tag_uid); } }catch(const errors::end_of_arguments_error &err) { amx_FormalError(errors::not_enough_args, err.argbase - params - 1 + err.required, params[0] / static_cast<cell>(sizeof(cell))); } #ifndef _DEBUG catch(const std::exception &err) { amx_LogicError(errors::unhandled_exception, err.what()); } #endif }else{ result = call_external_native(amx, native, params); } out_tag = native_return_tag; if(amx->error != AMX_ERR_NONE) { int code = amx->error; amx->error = AMX_ERR_NONE; throw errors::amx_error(code); } return result; } void amx::instance::run_initializers() { if(_amx && loaded && !initialized && (_amx->flags & AMX_FLAG_NTVREG)) { int num; if(amx_NumPublics(_amx, &num) == AMX_ERR_NONE) { char *funcname = amx_NameBuffer(_amx); cell ret; for(int i = 0; i < num; i++) { if(amx_GetPublic(_amx, i, funcname) == AMX_ERR_NONE) { funcname[12] = '\0'; if(!std::strcmp(funcname, "_pp@on_init@")) { amx_Exec(_amx, &ret, i); } } } initialized = true; } } } void amx::instance::run_finalizers() { if(_amx && initialized && (_amx->flags & AMX_FLAG_NTVREG)) { int num; if(amx_NumPublics(_amx, &num) == AMX_ERR_NONE) { char *funcname = amx_NameBuffer(_amx); cell ret; for(int i = num - 1; i >= 0; i--) { if(amx_GetPublic(_amx, i, funcname) == AMX_ERR_NONE) { funcname[12] = '\0'; if(!std::strcmp(funcname, "_pp@on_exit@")) { amx_Exec(_amx, &ret, i); } } } } } }
21.983553
130
0.679635
SL-RP
7dbc6963058fa5fddf6d30ec2fbcd352cf7c7db9
655
cpp
C++
qt-mvvm/source/libmvvm_model/mvvm/model/datarole.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
6
2021-12-08T03:09:47.000Z
2022-02-24T03:51:14.000Z
qt-mvvm/source/libmvvm_model/mvvm/model/datarole.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
null
null
null
qt-mvvm/source/libmvvm_model/mvvm/model/datarole.cpp
seaCheng/animation-
89a0cb0efbcfea202965a5851979ae6f1b67f8f0
[ "BSD-3-Clause" ]
null
null
null
// ************************************************************************** // // // Model-view-view-model framework for large GUI applications // //! @license GNU General Public License v3 or higher (see COPYING) //! @authors see AUTHORS // // ************************************************************************** // #include "mvvm/model/datarole.h" #include "mvvm/model/customvariants.h" using namespace ModelView; DataRole::DataRole(Variant data, int role) : m_data(std::move(data)), m_role(role) {} bool DataRole::operator==(const DataRole& other) const { return m_role == other.m_role && Utils::IsTheSame(m_data, other.m_data); }
31.190476
85
0.540458
seaCheng
7dbd7789fc2435b41cc0344951cc4cae807877c1
4,592
cpp
C++
apps/cloud_composer/tools/fpfh_estimation.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
apps/cloud_composer/tools/fpfh_estimation.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
apps/cloud_composer/tools/fpfh_estimation.cpp
yxlao/StanfordPCL
98a8663f896c1ba880d14efa2338b7cfbd01b6ef
[ "MIT" ]
null
null
null
#include <pcl/apps/cloud_composer/tools/fpfh_estimation.h> #include <pcl/apps/cloud_composer/items/cloud_item.h> #include <pcl/apps/cloud_composer/items/normals_item.h> #include <pcl/apps/cloud_composer/items/fpfh_item.h> #include <pcl/features/fpfh.h> #include <pcl/point_types.h> #include <pcl/filters/filter.h> Q_EXPORT_PLUGIN2(cloud_composer_fpfh_estimation_tool, pcl::cloud_composer::FPFHEstimationToolFactory) pcl::cloud_composer::FPFHEstimationTool::FPFHEstimationTool( PropertiesModel *parameter_model, QObject *parent) : NewItemTool(parameter_model, parent) {} pcl::cloud_composer::FPFHEstimationTool::~FPFHEstimationTool() {} QList<pcl::cloud_composer::CloudComposerItem *> pcl::cloud_composer::FPFHEstimationTool::performAction( ConstItemList input_data, PointTypeFlags::PointType type) { QList<CloudComposerItem *> output; const CloudComposerItem *input_item; // Check input data length if (input_data.size() == 0) { qCritical() << "Empty input in FPFH Estimation Tool!"; return output; } else if (input_data.size() > 1) { qWarning() << "Input vector has more than one item in FPFH Estimation!"; } input_item = input_data.value(0); if (input_item->type() == CloudComposerItem::CLOUD_ITEM) { // Check if this cloud has normals computed! QList<CloudComposerItem *> normals_list = input_item->getChildren(CloudComposerItem::NORMALS_ITEM); if (normals_list.size() == 0) { qCritical() << "No normals item child found in this cloud item"; return output; } qDebug() << "Found item text=" << normals_list.at(0)->text(); double radius = parameter_model_->getProperty("Radius").toDouble(); sensor_msgs::PointCloud2::ConstPtr input_cloud = input_item->data(ItemDataRole::CLOUD_BLOB) .value<sensor_msgs::PointCloud2::ConstPtr>(); // Get the cloud in template form pcl::PointCloud<pcl::PointXYZ>::Ptr cloud( new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(*input_cloud, *cloud); // Get the normals cloud, we just use the first normals that were found // if there are more than one pcl::PointCloud<pcl::Normal>::ConstPtr input_normals = normals_list.value(0) ->data(ItemDataRole::CLOUD_TEMPLATED) .value<pcl::PointCloud<pcl::Normal>::ConstPtr>(); pcl::FPFHEstimation<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> fpfh; // qDebug () << "Input cloud size = "<<cloud->size (); //////////////// THE WORK - COMPUTING FPFH /////////////////// // Create the FPFH estimation class, and pass the input dataset+normals // to it fpfh.setInputCloud(cloud); fpfh.setInputNormals(input_normals); // Create an empty kdtree representation, and pass it to the FPFH // estimation object. Its content will be filled inside the object, // based on the given input dataset (as no other search surface is // given). qDebug() << "Building KD Tree"; pcl::search::KdTree<PointXYZ>::Ptr tree( new pcl::search::KdTree<PointXYZ>); fpfh.setSearchMethod(tree); // Output datasets pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs( new pcl::PointCloud<pcl::FPFHSignature33>()); // Use all neighbors in a sphere of radius 5cm // IMPORTANT: the radius used here has to be larger than the radius used // to estimate the surface normals!!! fpfh.setRadiusSearch(radius); // Compute the features qDebug() << "Computing FPFH features"; fpfh.compute(*fpfhs); qDebug() << "Size of computed features =" << fpfhs->width; ////////////////////////////////////////////////////////////////// FPFHItem *fpfh_item = new FPFHItem(tr("FPFH r=%1").arg(radius), fpfhs, radius); output.append(fpfh_item); } else { qCritical() << "Input item in FPFH Estimation is not a cloud!!!"; } return output; } /////////////////// PARAMETER MODEL ///////////////////////////////// pcl::cloud_composer::PropertiesModel * pcl::cloud_composer::FPFHEstimationToolFactory::createToolParameterModel( QObject *parent) { PropertiesModel *parameter_model = new PropertiesModel(parent); parameter_model->addProperty("Radius", 0.03, Qt::ItemIsEditable | Qt::ItemIsEnabled); return parameter_model; }
40.637168
80
0.627831
yxlao
7dbe880049933ad81ebb8398d21d1dd1d6bf12ef
486
cpp
C++
Game/Source/GargoyleBattle_Dungeon_3.cpp
aNnAm2606/PROJECT-II-BAKARA-SAN
84bbc8cc9f7ea9f5b1b3ece4ea4053c74e7ece7f
[ "MIT" ]
null
null
null
Game/Source/GargoyleBattle_Dungeon_3.cpp
aNnAm2606/PROJECT-II-BAKARA-SAN
84bbc8cc9f7ea9f5b1b3ece4ea4053c74e7ece7f
[ "MIT" ]
7
2022-03-19T21:14:34.000Z
2022-03-19T21:53:13.000Z
Game/Source/GargoyleBattle_Dungeon_3.cpp
aNnAm2606/PROJECT-II-BAKARA-SAN
84bbc8cc9f7ea9f5b1b3ece4ea4053c74e7ece7f
[ "MIT" ]
1
2022-03-08T12:25:02.000Z
2022-03-08T12:25:02.000Z
#include "GargoyleBattle_Dungeon_3.h" #include "App.h" #include "BattleScene.h" #include "TownScene.h" GargoyleBattle_Dungeon_3::GargoyleBattle_Dungeon_3() { } GargoyleBattle_Dungeon_3::~GargoyleBattle_Dungeon_3() { } void GargoyleBattle_Dungeon_3::SetBattlefield() { app->battleScene->SetNextScene(m_OriginScene); app->battleScene->AddEnemy(Character::ECharacterType::ECHARACTER_GARGOYLE, 0, 0); app->battleScene->AddEnemy(Character::ECharacterType::ECHARACTER_GARGOYLE, 0, 1); }
25.578947
82
0.798354
aNnAm2606
7dc1fa1a581e5594ebe010195f234eac9646ae2e
931
cc
C++
GUI/ManualWindow.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
GUI/ManualWindow.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
GUI/ManualWindow.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
#include "QtCore/QFile" #include "ManualWindow.h" #include "ui_ManualWindow.h" using namespace SideCar::GUI; ManualWindow::ManualWindow(const QString& appName, const QString& manualPath) : Super(appName, appName + " Manual"), gui_(new Ui::ManualWindow), manualPath_(manualPath) { gui_->setupUi(this); setObjectName("ManualWindow"); setWindowTitle(appName + " Manual"); gui_->contents_->setReadOnly(true); } void ManualWindow::showEvent(QShowEvent* event) { // Load the manual contents. Done here to facilitate editing, but this should be done just once and cached. // QFile file(manualPath_); if (file.exists() && file.open(QIODevice::ReadOnly)) { gui_->contents_->setHtml(QString(file.readAll())); } else { gui_->contents_->setPlainText("The manual for this application is not " "installed."); } Super::showEvent(event); }
29.09375
111
0.665951
jwillemsen
7dc4808bd90cc71a1087549443b89edad2c30a9d
6,563
cpp
C++
Developments/solidity-develop/test/libsolidity/JSONCompiler.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
Developments/solidity-develop/test/libsolidity/JSONCompiler.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
Developments/solidity-develop/test/libsolidity/JSONCompiler.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @date 2017 * Unit tests for solc/jsonCompiler.cpp. */ #include <string> #include <boost/test/unit_test.hpp> #include <libdevcore/JSON.h> #include <libsolidity/interface/Version.h> #include <solc/jsonCompiler.h> #include "../Metadata.h" #include "../TestHelper.h" using namespace std; namespace dev { namespace solidity { namespace test { namespace { Json::Value compileSingle(string const& _input) { string output(compileJSON(_input.c_str(), dev::test::Options::get().optimize)); Json::Value ret; BOOST_REQUIRE(Json::Reader().parse(output, ret, false)); return ret; } Json::Value compileMulti(string const& _input, bool _callback) { string output( _callback ? compileJSONCallback(_input.c_str(), dev::test::Options::get().optimize, NULL) : compileJSONMulti(_input.c_str(), dev::test::Options::get().optimize) ); Json::Value ret; BOOST_REQUIRE(Json::Reader().parse(output, ret, false)); return ret; } Json::Value compile(string const& _input) { string output(compileStandard(_input.c_str(), NULL)); Json::Value ret; BOOST_REQUIRE(Json::Reader().parse(output, ret, false)); return ret; } } // end anonymous namespace BOOST_AUTO_TEST_SUITE(JSONCompiler) BOOST_AUTO_TEST_CASE(read_version) { string output(version()); BOOST_CHECK(output.find(VersionString) == 0); } BOOST_AUTO_TEST_CASE(read_license) { string output(license()); BOOST_CHECK(output.find("GNU GENERAL PUBLIC LICENSE") != string::npos); } BOOST_AUTO_TEST_CASE(basic_compilation) { char const* input = R"( { "sources": { "fileA": "contract A { }" } } )"; Json::Value result = compileMulti(input, false); BOOST_CHECK(result.isObject()); // Compare with compileJSONCallback BOOST_CHECK_EQUAL( dev::jsonCompactPrint(result), dev::jsonCompactPrint(compileMulti(input, true)) ); BOOST_CHECK(result["contracts"].isObject()); BOOST_CHECK(result["contracts"]["fileA:A"].isObject()); Json::Value contract = result["contracts"]["fileA:A"]; BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["interface"].isString()); BOOST_CHECK_EQUAL(contract["interface"].asString(), "[]"); BOOST_CHECK(contract["bytecode"].isString()); BOOST_CHECK_EQUAL( dev::test::bytecodeSansMetadata(contract["bytecode"].asString()), "60606040523415600e57600080fd5b603580601b6000396000f3006060604052600080fd00" ); BOOST_CHECK(contract["runtimeBytecode"].isString()); BOOST_CHECK_EQUAL( dev::test::bytecodeSansMetadata(contract["runtimeBytecode"].asString()), "6060604052600080fd00" ); BOOST_CHECK(contract["functionHashes"].isObject()); BOOST_CHECK(contract["gasEstimates"].isObject()); BOOST_CHECK_EQUAL( dev::jsonCompactPrint(contract["gasEstimates"]), "{\"creation\":[61,10600],\"external\":{},\"internal\":{}}" ); BOOST_CHECK(contract["metadata"].isString()); BOOST_CHECK(dev::test::isValidMetadata(contract["metadata"].asString())); BOOST_CHECK(result["sources"].isObject()); BOOST_CHECK(result["sources"]["fileA"].isObject()); BOOST_CHECK(result["sources"]["fileA"]["AST"].isObject()); BOOST_CHECK_EQUAL( dev::jsonCompactPrint(result["sources"]["fileA"]["AST"]), "{\"attributes\":{\"absolutePath\":\"fileA\",\"exportedSymbols\":{\"A\":[1]}}," "\"children\":[{\"attributes\":{\"baseContracts\":[null],\"contractDependencies\":[null]," "\"contractKind\":\"contract\",\"documentation\":null,\"fullyImplemented\":true,\"linearizedBaseContracts\":[1]," "\"name\":\"A\",\"nodes\":[null],\"scope\":2},\"id\":1,\"name\":\"ContractDefinition\"," "\"src\":\"0:14:0\"}],\"id\":2,\"name\":\"SourceUnit\",\"src\":\"0:14:0\"}" ); } BOOST_AUTO_TEST_CASE(single_compilation) { Json::Value result = compileSingle("contract A { }"); BOOST_CHECK(result.isObject()); BOOST_CHECK(result["contracts"].isObject()); BOOST_CHECK(result["contracts"][":A"].isObject()); Json::Value contract = result["contracts"][":A"]; BOOST_CHECK(contract.isObject()); BOOST_CHECK(contract["interface"].isString()); BOOST_CHECK_EQUAL(contract["interface"].asString(), "[]"); BOOST_CHECK(contract["bytecode"].isString()); BOOST_CHECK_EQUAL( dev::test::bytecodeSansMetadata(contract["bytecode"].asString()), "60606040523415600e57600080fd5b603580601b6000396000f3006060604052600080fd00" ); BOOST_CHECK(contract["runtimeBytecode"].isString()); BOOST_CHECK_EQUAL( dev::test::bytecodeSansMetadata(contract["runtimeBytecode"].asString()), "6060604052600080fd00" ); BOOST_CHECK(contract["functionHashes"].isObject()); BOOST_CHECK(contract["gasEstimates"].isObject()); BOOST_CHECK_EQUAL( dev::jsonCompactPrint(contract["gasEstimates"]), "{\"creation\":[61,10600],\"external\":{},\"internal\":{}}" ); BOOST_CHECK(contract["metadata"].isString()); BOOST_CHECK(dev::test::isValidMetadata(contract["metadata"].asString())); BOOST_CHECK(result["sources"].isObject()); BOOST_CHECK(result["sources"][""].isObject()); BOOST_CHECK(result["sources"][""]["AST"].isObject()); BOOST_CHECK_EQUAL( dev::jsonCompactPrint(result["sources"][""]["AST"]), "{\"attributes\":{\"absolutePath\":\"\",\"exportedSymbols\":{\"A\":[1]}}," "\"children\":[{\"attributes\":{\"baseContracts\":[null],\"contractDependencies\":[null]," "\"contractKind\":\"contract\",\"documentation\":null,\"fullyImplemented\":true,\"linearizedBaseContracts\":[1]," "\"name\":\"A\",\"nodes\":[null],\"scope\":2},\"id\":1,\"name\":\"ContractDefinition\"," "\"src\":\"0:14:0\"}],\"id\":2,\"name\":\"SourceUnit\",\"src\":\"0:14:0\"}" ); } BOOST_AUTO_TEST_CASE(standard_compilation) { char const* input = R"( { "language": "Solidity", "sources": { "fileA": { "content": "contract A { }" } } } )"; Json::Value result = compile(input); BOOST_CHECK(result.isObject()); // Only tests some assumptions. The StandardCompiler is tested properly in another suite. BOOST_CHECK(result.isMember("sources")); BOOST_CHECK(result.isMember("contracts")); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces
31.401914
115
0.705622
jansenbarabona
7dc6074a80a31cee9949ec855703627d2d6be7c3
27,321
cpp
C++
src/3rdparty/kjs/src/kjs/array_object.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
src/3rdparty/kjs/src/kjs/array_object.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
src/3rdparty/kjs/src/kjs/array_object.cpp
afarcat/QtHtmlView
fff12b6f5c08c2c6db15dd73e4f0b55421827b39
[ "Apache-2.0" ]
null
null
null
/* * This file is part of the KDE libraries * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) * Copyright (C) 2003, 2007 Apple Inc. All rights reserved. * Copyright (C) 2003 Peter Kelly (pmk@post.com) * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com) * Copyright (C) 2008 Janusz Lewandowski (lew21st@gmail.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "array_object.h" #include "array_object.lut.h" #include "error_object.h" #include "lookup.h" #include "operations.h" #include "PropertyNameArray.h" #include <wtf/HashSet.h> #include <stdio.h> // GCC cstring uses these automatically, but not all implementations do. using std::strlen; using std::strcpy; using std::strncpy; using std::memset; using std::memcpy; namespace KJS { /** * @internal * * Class to implement all methods that are properties of the * Object object */ class ArrayObjectFuncImp : public InternalFunctionImp { public: ArrayObjectFuncImp(ExecState *, FunctionPrototype *, int i, int len, const Identifier &); virtual JSValue *callAsFunction(ExecState *, JSObject *thisObj, const List &args); enum { IsArray }; private: int id; }; // ------------------------------ ArrayPrototype ---------------------------- const ClassInfo ArrayPrototype::info = {"Array", &ArrayInstance::info, &arrayTable, nullptr}; /* Source for array_object.lut.h @begin arrayTable 16 toString ArrayProtoFunc::ToString DontEnum|Function 0 toLocaleString ArrayProtoFunc::ToLocaleString DontEnum|Function 0 concat ArrayProtoFunc::Concat DontEnum|Function 1 join ArrayProtoFunc::Join DontEnum|Function 1 pop ArrayProtoFunc::Pop DontEnum|Function 0 push ArrayProtoFunc::Push DontEnum|Function 1 reverse ArrayProtoFunc::Reverse DontEnum|Function 0 shift ArrayProtoFunc::Shift DontEnum|Function 0 slice ArrayProtoFunc::Slice DontEnum|Function 2 sort ArrayProtoFunc::Sort DontEnum|Function 1 splice ArrayProtoFunc::Splice DontEnum|Function 2 unshift ArrayProtoFunc::UnShift DontEnum|Function 1 every ArrayProtoFunc::Every DontEnum|Function 1 forEach ArrayProtoFunc::ForEach DontEnum|Function 1 some ArrayProtoFunc::Some DontEnum|Function 1 indexOf ArrayProtoFunc::IndexOf DontEnum|Function 1 lastIndexOf ArrayProtoFunc::LastIndexOf DontEnum|Function 1 filter ArrayProtoFunc::Filter DontEnum|Function 1 map ArrayProtoFunc::Map DontEnum|Function 1 reduce ArrayProtoFunc::Reduce DontEnum|Function 1 reduceRight ArrayProtoFunc::ReduceRight DontEnum|Function 1 @end */ // ECMA 15.4.4 ArrayPrototype::ArrayPrototype(ExecState *, ObjectPrototype *objProto) : ArrayInstance(objProto, 0) { } bool ArrayPrototype::getOwnPropertySlot(ExecState *exec, const Identifier &propertyName, PropertySlot &slot) { return getStaticFunctionSlot<ArrayProtoFunc, ArrayInstance>(exec, &arrayTable, this, propertyName, slot); } // ------------------------------ ArrayProtoFunc ---------------------------- ArrayProtoFunc::ArrayProtoFunc(ExecState *exec, int i, int len, const Identifier &name) : InternalFunctionImp(static_cast<FunctionPrototype *> (exec->lexicalInterpreter()->builtinFunctionPrototype()), name) , id(i) { put(exec, exec->propertyNames().length, jsNumber(len), DontDelete | ReadOnly | DontEnum); } static JSValue *getProperty(ExecState *exec, JSObject *obj, unsigned index) { PropertySlot slot; if (!obj->getPropertySlot(exec, index, slot)) { return nullptr; } return slot.getValue(exec, obj, index); } // ECMA 15.4.4 JSValue *ArrayProtoFunc::callAsFunction(ExecState *exec, JSObject *thisObj, const List &args) { unsigned length = thisObj->get(exec, exec->propertyNames().length)->toUInt32(exec); JSValue *result = nullptr; // work around gcc 4.0 bug in uninitialized variable warning switch (id) { case ToLocaleString: case ToString: if (!thisObj->inherits(&ArrayInstance::info)) { return throwError(exec, TypeError); } // fall through case Join: { static HashSet<JSObject *> visitedElems; static const UString *empty = new UString(""); static const UString *comma = new UString(","); bool alreadyVisited = !visitedElems.add(thisObj).second; if (alreadyVisited) { return jsString(*empty); } UString separator = *comma; UString str = *empty; if (id == Join && !args[0]->isUndefined()) { separator = args[0]->toString(exec); } for (unsigned int k = 0; k < length; k++) { if (k >= 1) { str += separator; } if (str.isNull()) { JSObject *error = Error::create(exec, GeneralError, "Out of memory"); exec->setException(error); break; } JSValue *element = thisObj->get(exec, k); if (element->isUndefinedOrNull()) { continue; } bool fallback = false; if (id == ToLocaleString) { JSObject *o = element->toObject(exec); JSValue *conversionFunction = o->get(exec, exec->propertyNames().toLocaleString); if (conversionFunction->isObject() && static_cast<JSObject *>(conversionFunction)->implementsCall()) { str += static_cast<JSObject *>(conversionFunction)->call(exec, o, List())->toString(exec); } else // try toString() fallback { fallback = true; } } if (id == ToString || id == Join || fallback) { str += element->toString(exec); if (exec->hadException()) { break; } if (str.isNull()) { JSObject *error = Error::create(exec, GeneralError, "Out of memory"); exec->setException(error); } } if (exec->hadException()) { break; } } visitedElems.remove(thisObj); result = jsString(str); break; } case Concat: { JSObject *arr = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec, List::empty())); int n = 0; JSValue *curArg = thisObj; JSObject *curObj = static_cast<JSObject *>(thisObj); ListIterator it = args.begin(); for (;;) { if (curArg->isObject() && curObj->inherits(&ArrayInstance::info)) { unsigned int k = 0; // Older versions tried to optimize out getting the length of thisObj // by checking for n != 0, but that doesn't work if thisObj is an empty array. length = curObj->get(exec, exec->propertyNames().length)->toUInt32(exec); while (k < length) { if (JSValue *v = getProperty(exec, curObj, k)) { arr->put(exec, n, v); } n++; k++; } } else { arr->put(exec, n, curArg); n++; } if (it == args.end()) { break; } curArg = *it; curObj = static_cast<JSObject *>(it++); // may be 0 } arr->put(exec, exec->propertyNames().length, jsNumber(n), DontEnum | DontDelete); result = arr; break; } case Pop: { if (length == 0) { thisObj->put(exec, exec->propertyNames().length, jsNumber(length), DontEnum | DontDelete); result = jsUndefined(); } else { result = thisObj->get(exec, length - 1); thisObj->put(exec, exec->propertyNames().length, jsNumber(length - 1), DontEnum | DontDelete); } break; } case Push: { for (int n = 0; n < args.size(); n++) { thisObj->put(exec, length + n, args[n]); } length += args.size(); thisObj->put(exec, exec->propertyNames().length, jsNumber(length), DontEnum | DontDelete); result = jsNumber(length); break; } case Reverse: { unsigned int middle = length / 2; for (unsigned int k = 0; k < middle; k++) { unsigned lk1 = length - k - 1; JSValue *obj2 = getProperty(exec, thisObj, lk1); JSValue *obj = getProperty(exec, thisObj, k); if (obj2) { thisObj->put(exec, k, obj2); } else { thisObj->deleteProperty(exec, k); } if (obj) { thisObj->put(exec, lk1, obj); } else { thisObj->deleteProperty(exec, lk1); } } result = thisObj; break; } case Shift: { if (length == 0) { thisObj->put(exec, exec->propertyNames().length, jsNumber(length), DontEnum | DontDelete); result = jsUndefined(); } else { result = thisObj->get(exec, 0); for (unsigned int k = 1; k < length; k++) { if (JSValue *obj = getProperty(exec, thisObj, k)) { thisObj->put(exec, k - 1, obj); } else { thisObj->deleteProperty(exec, k - 1); } } thisObj->deleteProperty(exec, length - 1); thisObj->put(exec, exec->propertyNames().length, jsNumber(length - 1), DontEnum | DontDelete); } break; } case Slice: { // http://developer.netscape.com/docs/manuals/js/client/jsref/array.htm#1193713 or 15.4.4.10 // We return a new array JSObject *resObj = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec, List::empty())); result = resObj; double begin = 0; if (!args[0]->isUndefined()) { begin = args[0]->toInteger(exec); if (begin >= 0) { // false for NaN if (begin > length) { begin = length; } } else { begin += length; if (!(begin >= 0)) { // true for NaN begin = 0; } } } double end = length; if (!args[1]->isUndefined()) { end = args[1]->toInteger(exec); if (end < 0) { // false for NaN end += length; if (end < 0) { end = 0; } } else { if (!(end <= length)) { // true for NaN end = length; } } } //printf( "Slicing from %d to %d \n", begin, end ); int n = 0; int b = static_cast<int>(begin); int e = static_cast<int>(end); for (int k = b; k < e; k++, n++) { if (JSValue *v = getProperty(exec, thisObj, k)) { resObj->put(exec, n, v); } } resObj->put(exec, exec->propertyNames().length, jsNumber(n), DontEnum | DontDelete); break; } case Sort: { #if 0 printf("KJS Array::Sort length=%d\n", length); for (unsigned int i = 0; i < length; ++i) { printf("KJS Array::Sort: %d: %s\n", i, thisObj->get(exec, i)->toString(exec).ascii()); } #endif JSObject *sortFunction = nullptr; if (!args[0]->isUndefined()) { sortFunction = args[0]->toObject(exec); if (!sortFunction->implementsCall()) { sortFunction = nullptr; } } if (thisObj->classInfo() == &ArrayInstance::info) { if (sortFunction) { ((ArrayInstance *)thisObj)->sort(exec, sortFunction); } else { ((ArrayInstance *)thisObj)->sort(exec); } result = thisObj; break; } if (length == 0) { thisObj->put(exec, exec->propertyNames().length, jsNumber(0), DontEnum | DontDelete); result = thisObj; break; } // "Min" sort. Not the fastest, but definitely less code than heapsort // or quicksort, and much less swapping than bubblesort/insertionsort. for (unsigned int i = 0; i < length - 1; ++i) { JSValue *iObj = thisObj->get(exec, i); unsigned int themin = i; JSValue *minObj = iObj; for (unsigned int j = i + 1; j < length; ++j) { JSValue *jObj = thisObj->get(exec, j); double cmp; if (jObj->isUndefined()) { cmp = 1; // don't check minObj because there's no need to differentiate == (0) from > (1) } else if (minObj->isUndefined()) { cmp = -1; } else if (sortFunction) { List l; l.append(jObj); l.append(minObj); cmp = sortFunction->call(exec, exec->dynamicInterpreter()->globalObject(), l)->toNumber(exec); } else { cmp = (jObj->toString(exec) < minObj->toString(exec)) ? -1 : 1; } if (cmp < 0) { themin = j; minObj = jObj; } } // Swap themin and i if (themin > i) { //printf("KJS Array::Sort: swapping %d and %d\n", i, themin ); thisObj->put(exec, i, minObj); thisObj->put(exec, themin, iObj); } } #if 0 printf("KJS Array::Sort -- Resulting array:\n"); for (unsigned int i = 0; i < length; ++i) { printf("KJS Array::Sort: %d: %s\n", i, thisObj->get(exec, i)->toString(exec).ascii()); } #endif result = thisObj; break; } case Splice: { // 15.4.4.12 - oh boy this is huge JSObject *resObj = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec, List::empty())); result = resObj; double start = args[0]->toInteger(exec); uint32_t begin = 0; if (start < 0) { begin = static_cast<uint32_t>(std::max<double>(start + length, 0)); } else { begin = static_cast<uint32_t>(std::min<double>(start, length)); } uint32_t deleteCount = static_cast<uint32_t>(std::min<double>(std::max<double>(args[1]->toInteger(exec), 0), length - begin)); //printf( "Splicing from %d, deleteCount=%d \n", begin, deleteCount ); for (unsigned int k = 0; k < deleteCount; k++) { if (JSValue *v = getProperty(exec, thisObj, k + begin)) { resObj->put(exec, k, v); } } resObj->put(exec, exec->propertyNames().length, jsNumber(deleteCount), DontEnum | DontDelete); unsigned int additionalArgs = maxInt(args.size() - 2, 0); if (additionalArgs != deleteCount) { if (additionalArgs < deleteCount) { for (unsigned int k = begin; k < length - deleteCount; ++k) { if (JSValue *v = getProperty(exec, thisObj, k + deleteCount)) { thisObj->put(exec, k + additionalArgs, v); } else { thisObj->deleteProperty(exec, k + additionalArgs); } } for (unsigned int k = length; k > length - deleteCount + additionalArgs; --k) { thisObj->deleteProperty(exec, k - 1); } } else { for (unsigned int k = length - deleteCount; k > begin; --k) { if (JSValue *obj = getProperty(exec, thisObj, k + deleteCount - 1)) { thisObj->put(exec, k + additionalArgs - 1, obj); } else { thisObj->deleteProperty(exec, k + additionalArgs - 1); } } } } for (unsigned int k = 0; k < additionalArgs; ++k) { thisObj->put(exec, k + begin, args[k + 2]); } thisObj->put(exec, exec->propertyNames().length, jsNumber(length - deleteCount + additionalArgs), DontEnum | DontDelete); break; } case UnShift: { // 15.4.4.13 unsigned int nrArgs = args.size(); for (unsigned int k = length; k > 0; --k) { if (JSValue *v = getProperty(exec, thisObj, k - 1)) { thisObj->put(exec, k + nrArgs - 1, v); } else { thisObj->deleteProperty(exec, k + nrArgs - 1); } } for (unsigned int k = 0; k < nrArgs; ++k) { thisObj->put(exec, k, args[k]); } result = jsNumber(length + nrArgs); thisObj->put(exec, exec->propertyNames().length, result, DontEnum | DontDelete); break; } case Filter: case Map: { JSObject *eachFunction = args[0]->toObject(exec); if (!eachFunction->implementsCall()) { return throwError(exec, TypeError); } JSObject *applyThis = args[1]->isUndefinedOrNull() ? exec->dynamicInterpreter()->globalObject() : args[1]->toObject(exec); JSObject *resultArray; if (id == Filter) { resultArray = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec, List::empty())); } else { List args; args.append(jsNumber(length)); resultArray = static_cast<JSObject *>(exec->lexicalInterpreter()->builtinArray()->construct(exec, args)); } unsigned filterIndex = 0; for (unsigned k = 0; k < length && !exec->hadException(); ++k) { PropertySlot slot; if (!thisObj->getPropertySlot(exec, k, slot)) { continue; } JSValue *v = slot.getValue(exec, thisObj, k); List eachArguments; eachArguments.append(v); eachArguments.append(jsNumber(k)); eachArguments.append(thisObj); JSValue *result = eachFunction->call(exec, applyThis, eachArguments); if (id == Map) { resultArray->put(exec, k, result); } else if (result->toBoolean(exec)) { resultArray->put(exec, filterIndex++, v); } } return resultArray; } case Every: case ForEach: case Some: { //Documentation for these three is available at: //http://developer-test.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:every //http://developer-test.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:forEach //http://developer-test.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:some JSObject *eachFunction = args[0]->toObject(exec); if (!eachFunction->implementsCall()) { return throwError(exec, TypeError); } JSObject *applyThis = args[1]->isUndefinedOrNull() ? exec->dynamicInterpreter()->globalObject() : args[1]->toObject(exec); if (id == Some || id == Every) { result = jsBoolean(id == Every); } else { result = jsUndefined(); } for (unsigned k = 0; k < length && !exec->hadException(); ++k) { PropertySlot slot; if (!thisObj->getPropertySlot(exec, k, slot)) { continue; } List eachArguments; eachArguments.append(slot.getValue(exec, thisObj, k)); eachArguments.append(jsNumber(k)); eachArguments.append(thisObj); bool predicateResult = eachFunction->call(exec, applyThis, eachArguments)->toBoolean(exec); if (id == Every && !predicateResult) { result = jsBoolean(false); break; } if (id == Some && predicateResult) { result = jsBoolean(true); break; } } break; } case IndexOf: { // JavaScript 1.5 Extension by Mozilla // Documentation: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:indexOf unsigned index = 0; double d = args[1]->toInteger(exec); if (d < 0) { d += length; } if (d > 0) { if (d > length) { index = length; } else { index = static_cast<unsigned>(d); } } JSValue *searchElement = args[0]; for (; index < length; ++index) { JSValue *e = getProperty(exec, thisObj, index); if (!e) { continue; } if (strictEqual(exec, searchElement, e)) { return jsNumber(index); } } return jsNumber(-1); } case LastIndexOf: { // JavaScript 1.6 Extension by Mozilla // Documentation: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array:lastIndexOf int index = length - 1; double d = args[1]->toIntegerPreserveNaN(exec); if (d < 0) { d += length; if (d < 0) { return jsNumber(-1); } } if (d < length) { index = static_cast<int>(d); } JSValue *searchElement = args[0]; for (; index >= 0; --index) { JSValue *e = getProperty(exec, thisObj, index); if (!e) { continue; } if (strictEqual(exec, searchElement, e)) { return jsNumber(index); } } return jsNumber(-1); } case Reduce: case ReduceRight: { // JavaScript 1.8 Extensions by Mozilla // Documentation: // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight JSObject *callback = args[0]->toObject(exec); if (!callback->implementsCall()) { return throwError(exec, TypeError); } JSObject *applyThis = args[2]->isUndefinedOrNull() ? exec->dynamicInterpreter()->globalObject() : args[2]->toObject(exec); if (!length && args.size() < 2) { return throwError(exec, TypeError); } unsigned k = 0; unsigned last = length - 1; if (args.size() >= 2) { result = args[1]; } else { for (; k < length && !exec->hadException(); ++k) { PropertySlot slot; if (!thisObj->getPropertySlot(exec, (id == Reduce) ? k : (last - k), slot)) { continue; } result = slot.getValue(exec, thisObj, (id == Reduce) ? k++ : (last - k++)); break; } } for (; k < length && !exec->hadException(); ++k) { PropertySlot slot; if (!thisObj->getPropertySlot(exec, (id == Reduce) ? k : (last - k), slot)) { continue; } JSValue *v = slot.getValue(exec, thisObj, (id == Reduce) ? k : (last - k)); List eachArguments; eachArguments.append(result); eachArguments.append(v); eachArguments.append(jsNumber((id == Reduce) ? k : (last - k))); eachArguments.append(thisObj); result = callback->call(exec, applyThis, eachArguments); } break; } default: assert(0); result = nullptr; break; } return result; } // ------------------------------ ArrayObjectImp ------------------------------- ArrayObjectImp::ArrayObjectImp(ExecState *exec, FunctionPrototype *funcProto, ArrayPrototype *arrayProto) : InternalFunctionImp(funcProto) { static const Identifier *isArrayName = new Identifier("isArray"); // ECMA 15.4.3.1 Array.prototype put(exec, exec->propertyNames().prototype, arrayProto, DontEnum | DontDelete | ReadOnly); putDirectFunction(new ArrayObjectFuncImp(exec, funcProto, ArrayObjectFuncImp::IsArray, 1, *isArrayName), DontEnum); // no. of arguments for constructor put(exec, exec->propertyNames().length, jsNumber(1), ReadOnly | DontDelete | DontEnum); } bool ArrayObjectImp::implementsConstruct() const { return true; } // ECMA 15.4.2 JSObject *ArrayObjectImp::construct(ExecState *exec, const List &args) { // a single numeric argument denotes the array size (!) if (args.size() == 1 && args[0]->isNumber()) { uint32_t n = args[0]->toUInt32(exec); if (n != args[0]->toNumber(exec)) { return throwError(exec, RangeError, "Array size is not a small enough positive integer."); } return new ArrayInstance(exec->lexicalInterpreter()->builtinArrayPrototype(), n); } // otherwise the array is constructed with the arguments in it return new ArrayInstance(exec->lexicalInterpreter()->builtinArrayPrototype(), args); } // ECMA 15.6.1 JSValue *ArrayObjectImp::callAsFunction(ExecState *exec, JSObject * /*thisObj*/, const List &args) { // equivalent to 'new Array(....)' return construct(exec, args); } // ------------------------------ ArrayObjectFuncImp ---------------------------- ArrayObjectFuncImp::ArrayObjectFuncImp(ExecState *exec, FunctionPrototype *funcProto, int i, int len, const Identifier &name) : InternalFunctionImp(funcProto, name), id(i) { putDirect(exec->propertyNames().length, len, DontDelete | ReadOnly | DontEnum); } JSValue *ArrayObjectFuncImp::callAsFunction(ExecState * /*exec*/, JSObject *, const List &args) { switch (id) { case IsArray: { JSObject *jso = args[0]->getObject(); if (!jso) { return jsBoolean(false); } return jsBoolean(jso->inherits(&ArrayInstance::info)); } default: return jsUndefined(); } } }
35.071887
134
0.532411
afarcat
7dc6130c25cc81c91c2ab47777fdc7ae10dee10c
308
cpp
C++
src/functions.cpp
fangzhou-xie/decimal
9439bffda0cc8bad18f0be971788516ff1f5520c
[ "MIT" ]
null
null
null
src/functions.cpp
fangzhou-xie/decimal
9439bffda0cc8bad18f0be971788516ff1f5520c
[ "MIT" ]
null
null
null
src/functions.cpp
fangzhou-xie/decimal
9439bffda0cc8bad18f0be971788516ff1f5520c
[ "MIT" ]
null
null
null
// define some functions #include <Rcpp.h> using namespace Rcpp; #include "utils.h" // [[Rcpp::export]] std::string sum_decimal_cpp(std::vector<std::string> s) { decimal<10> out; for (size_t i = 0; i < s.size(); i++) { auto t = read_decimal(s[i]); out += t; } return toString(out); }
17.111111
57
0.600649
fangzhou-xie
7dcae2839feabc574ae87e7bed82766a135fd751
2,931
cpp
C++
pxr/base/arch/errno.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
3,680
2016-07-26T18:28:11.000Z
2022-03-31T09:55:05.000Z
pxr/base/arch/errno.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
1,759
2016-07-26T19:19:59.000Z
2022-03-31T21:24:00.000Z
pxr/base/arch/errno.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
904
2016-07-26T18:33:40.000Z
2022-03-31T09:55:16.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "pxr/base/arch/errno.h" #include <cerrno> #include <cstring> #if defined(ARCH_OS_WINDOWS) #include <Windows.h> #endif PXR_NAMESPACE_OPEN_SCOPE std::string ArchStrerror() { return ArchStrerror(errno); } std::string ArchStrerror(int errorCode) { char msg_buf[256]; #if defined(_GNU_SOURCE) // from strerror_r(3): // // The GNU-specific strerror_r() returns a pointer to a string // containing the error message. This may be either a pointer to a // string that the function stores in buf, or a pointer to some // (immutable) static string (in which case buf is unused). If the // function stores a string in buf, then at most buflen bytes are stored // (the string may be truncated if buflen is too small and errnum is // unknown). The string always includes a terminating null byte. // return strerror_r(errorCode, msg_buf, 256); #elif !defined(ARCH_COMPILER_MSVC) strerror_r(errorCode, msg_buf, 256); #else strerror_s(msg_buf, 256, errorCode); #endif // _GNU_SOURCE return msg_buf; } #if defined(ARCH_OS_WINDOWS) std::string ArchStrSysError(unsigned long errorCode) { if(errorCode == 0) return std::string(); LPSTR buffer = nullptr; size_t len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buffer, 0, nullptr); std::string message(buffer, len); LocalFree(buffer); return message; } #endif PXR_NAMESPACE_CLOSE_SCOPE
32.566667
78
0.666325
DougRogers-DigitalFish
7dccd426d0bb409edc389c3318f3fc3813d32231
492
cpp
C++
HackerRank/CPP/Strings/StringStream.cpp
AdityaChirravuri/CompetitiveProgramming
642550e8916b3f7939a1fdd52d10f5f8ae43f161
[ "MIT" ]
1
2021-07-13T01:49:25.000Z
2021-07-13T01:49:25.000Z
HackerRank/CPP/Strings/StringStream.cpp
AdityaChirravuri/CompetitiveProgramming
642550e8916b3f7939a1fdd52d10f5f8ae43f161
[ "MIT" ]
null
null
null
HackerRank/CPP/Strings/StringStream.cpp
AdityaChirravuri/CompetitiveProgramming
642550e8916b3f7939a1fdd52d10f5f8ae43f161
[ "MIT" ]
null
null
null
#include <sstream> #include <vector> #include <iostream> using namespace std; vector<int> parseInts(string str) { // Complete this function stringstream ss (str); vector<int>m; int t; char ch; while(ss >> t){ m.push_back(t); ss >> ch; } return m; } int main() { string str; cin >> str; vector<int> integers = parseInts(str); for(int i = 0; i < integers.size(); i++) { cout << integers[i] << "\n"; } return 0; }
16.4
46
0.542683
AdityaChirravuri
7dcd354881ba4f97eca8ca38363310105ce736b8
572
cpp
C++
string-algorithms/hashing/basic_string_hashing.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
string-algorithms/hashing/basic_string_hashing.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
string-algorithms/hashing/basic_string_hashing.cpp
dushimsam/deep-dive-in-algorithms
0c6a04b3115ba789ab4aca68cce51c9a3c3a075a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /*** source :-> * * https://cp-algorithms.com/string/string-hashing.html * * ***/ long long computer_hash(string str) { const int increase = 31; const int m = 1e9 + 9; long long hash_value = 0; long long p = 1; for (int i = 0; i < str.length(); i++) { int dist = str[i] - 'a' + 1; hash_value = (hash_value + (p * dist)) % m; p = (p * increase) % m; } return hash_value; } int main() { string str = "coding"; cout << computer_hash(str); return 0; }
17.333333
56
0.534965
dushimsam
7dcdf1044c758407f6651eb7e1d19dfc26a38866
6,149
cpp
C++
720Core/Logger.cpp
imengyu/720PanoramaViewer
bab70a1a1dd06f35ba0fb2418765fadb5cab2a17
[ "MIT" ]
2
2021-04-27T02:44:31.000Z
2021-06-10T08:29:49.000Z
720Core/Logger.cpp
imengyu/720PanoramaViewer
bab70a1a1dd06f35ba0fb2418765fadb5cab2a17
[ "MIT" ]
null
null
null
720Core/Logger.cpp
imengyu/720PanoramaViewer
bab70a1a1dd06f35ba0fb2418765fadb5cab2a17
[ "MIT" ]
1
2021-09-07T11:31:07.000Z
2021-09-07T11:31:07.000Z
#include "Logger.h" #include "CStringHlp.h" #include "720Core.h" #include <ctime> using namespace std; #undef LogError2 #undef LogWarn2 #undef LogInfo2 #undef Log2 Logger* globalStaticLogger = nullptr; void LoggerInternal::InitConst() { globalStaticLogger = new LoggerInternal(L"App"); } void LoggerInternal::DestroyConst() { delete globalStaticLogger; } Logger* GetLoggerStaticInstance() { return globalStaticLogger; } LoggerInternal::LoggerInternal(const wchar_t* tag) { logTag = tag; } LoggerInternal::~LoggerInternal() { CloseLogFile(); } void LoggerInternal::Log(const wchar_t* str, ...) { if (level <= LogLevelText) { va_list arg; va_start(arg, str); LogInternal(LogLevelText, str, arg); va_end(arg); } } void LoggerInternal::LogWarn(const wchar_t* str, ...) { if (level <= LogLevelWarn) { va_list arg; va_start(arg, str); LogInternal(LogLevelWarn, str, arg); va_end(arg); } } void LoggerInternal::LogError(const wchar_t* str, ...) { if (level <= LogLevelError) { va_list arg; va_start(arg, str); LogInternal(LogLevelError, str, arg); va_end(arg); } } void LoggerInternal::LogInfo(const wchar_t* str, ...) { if (level <= LogLevelInfo) { va_list arg; va_start(arg, str); LogInternal(LogLevelInfo, str, arg); va_end(arg); } } void LoggerInternal::Log2(const wchar_t* str, const char* file, int line, const char* functon, ...) { if (level <= LogLevelText) { va_list arg; va_start(arg, functon); LogInternalWithCodeAndLine(LogLevelText, str, file, line, functon, arg); va_end(arg); } } void LoggerInternal::LogWarn2(const wchar_t* str, const char* file, int line, const char* functon, ...) { if (level <= LogLevelWarn) { va_list arg; va_start(arg, functon); LogInternalWithCodeAndLine(LogLevelWarn, str, file, line, functon, arg); va_end(arg); } } void LoggerInternal::LogError2(const wchar_t* str, const char* file, int line, const char* functon, ...) { if (level <= LogLevelError) { va_list arg; va_start(arg, functon); LogInternalWithCodeAndLine(LogLevelError, str, file, line, functon, arg); va_end(arg); } } void LoggerInternal::LogInfo2(const wchar_t* str, const char* file, int line, const char* functon, ...) { if (level <= LogLevelInfo) { va_list arg; va_start(arg, functon); LogInternalWithCodeAndLine(LogLevelInfo, str, file, line, functon, arg); va_end(arg); } } void LoggerInternal::SetLogLevel(LogLevel logLevel) { this->level = logLevel; } LogLevel LoggerInternal::GetLogLevel() { return this->level; } void LoggerInternal::SetLogOutPut(LogOutPut output) { this->outPut = output; } void LoggerInternal::SetLogOutPutFile(const wchar_t* filePath) { if (logFilePath != filePath) { CloseLogFile(); logFilePath = filePath; #if defined(_MSC_VER) && _MSC_VER > 1600 _wfopen_s(&logFile, (wchar_t*)logFilePath.data(), L"w"); #else logFile = _wfopen(logFilePath.data(), L"w"); #endif } } void LoggerInternal::SetLogOutPutCallback(LogCallBack callback, void* lparam) { callBack = callback; callBackData = lparam; } void LoggerInternal::InitLogConsoleStdHandle() { hOutput = GetStdHandle(STD_OUTPUT_HANDLE); } void LoggerInternal::LogOutputToStdHandle(LogLevel logLevel, const wchar_t* str, size_t len) { switch (logLevel) { case LogLevelInfo: SetConsoleTextAttribute(hOutput, FOREGROUND_INTENSITY | FOREGROUND_BLUE); break; case LogLevelWarn: SetConsoleTextAttribute(hOutput, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN); break; case LogLevelError: SetConsoleTextAttribute(hOutput, FOREGROUND_INTENSITY | FOREGROUND_RED); break; case LogLevelText: SetConsoleTextAttribute(hOutput, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); break; } WriteConsoleW(hOutput, str, len, NULL, NULL); } void LoggerInternal::ResentNotCaputureLog() { if (outPut == LogOutPutCallback && callBack) { std::list< LOG_SLA>::iterator i; for (i = logPendingBuffer.begin(); i != logPendingBuffer.end(); i++) callBack((*i).str.c_str(), (*i).level, callBackData); logPendingBuffer.clear(); } } void LoggerInternal::WritePendingLog(const wchar_t* str, LogLevel logLevel) { LOG_SLA sla = { std::wstring(str), logLevel }; logPendingBuffer.push_back(sla); } void LoggerInternal::LogInternalWithCodeAndLine(LogLevel logLevel, const wchar_t* str, const char* file, int line, const char* functon, va_list arg) { std::wstring format1 = CStringHlp::FormatString(L"%s\n[In] %hs (%d) : %hs", str, file, line, functon); LogInternal(logLevel, format1.c_str(), arg); } void LoggerInternal::LogInternal(LogLevel logLevel, const wchar_t* str, va_list arg) { const wchar_t* levelStr; switch (logLevel) { case LogLevelInfo: levelStr = L"I"; break; case LogLevelWarn: levelStr = L"W"; break; case LogLevelError: levelStr = L"E"; break; case LogLevelText: levelStr = L"T"; break; default: levelStr = L""; break; } time_t time_log = time(NULL); #if defined(_MSC_VER) && _MSC_VER > 1600 struct tm tm_log; localtime_s(&tm_log, &time_log); std::wstring format1 = CStringHlp::FormatString(L"[%02d:%02d:%02d] [%s] %s\n", tm_log.tm_hour, tm_log.tm_min, tm_log.tm_sec, levelStr, str); #else tm* tm_log = localtime(&time_log); std::wstring format1 = CStringHlp::FormatString(L"%s/%s:%02d:%02d:%02d %s\n", logTag.c_str(), levelStr, tm_log->tm_hour, tm_log->tm_min, tm_log->tm_sec, str); #endif std::wstring out = CStringHlp::FormatString(format1.c_str(), arg); LogOutput(logLevel, out.c_str(), str, out.size()); } void LoggerInternal::LogOutput(LogLevel logLevel, const wchar_t* str, const wchar_t* srcStr, size_t len) { #if _DEBUG OutputDebugString(str); #else if (outPut == LogOutPutConsolne) OutputDebugString(str); #endif if (outPut == LogOutPutFile && logFile) fwprintf_s(logFile, L"%s", str); else if (outPut == LogOutPutConsolne) { if (hOutput != NULL) LogOutputToStdHandle(logLevel, str, len); else wprintf_s(L"%s", str); } else if (outPut == LogOutPutCallback && callBack) callBack(str, logLevel, callBackData); else WritePendingLog(str, logLevel); } void LoggerInternal::CloseLogFile() { if (logFile) { fclose(logFile); logFile = nullptr; } }
26.734783
159
0.721581
imengyu
7dcfc29ce50fc95177da56fffa01b77e75cb4225
34,825
cpp
C++
src/add-ons/accelerants/radeon_hd/display.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/add-ons/accelerants/radeon_hd/display.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/add-ons/accelerants/radeon_hd/display.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2006-2013, Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. * * Authors: * Alexander von Gluck, kallisti5@unixzen.com * Bill Randle, billr@neocat.org */ /* * It's dangerous to go alone, take this! * framebuffer -> crtc -> encoder -> transmitter -> connector -> monitor */ #include "display.h" #include <stdlib.h> #include <string.h> #include "accelerant.h" #include "accelerant_protos.h" #include "bios.h" #include "connector.h" #include "displayport.h" #include "encoder.h" #define TRACE_DISPLAY #ifdef TRACE_DISPLAY extern "C" void _sPrintf(const char* format, ...); # define TRACE(x...) _sPrintf("radeon_hd: " x) #else # define TRACE(x...) ; #endif #define ERROR(x...) _sPrintf("radeon_hd: " x) /*! Populate regs with device dependant register locations */ status_t init_registers(register_info* regs, uint8 crtcID) { memset(regs, 0, sizeof(register_info)); radeon_shared_info &info = *gInfo->shared_info; if (info.chipsetID >= RADEON_CEDAR) { // Evergreen uint32 offset = 0; switch (crtcID) { case 0: offset = EVERGREEN_CRTC0_REGISTER_OFFSET; regs->vgaControl = AVIVO_D1VGA_CONTROL; break; case 1: offset = EVERGREEN_CRTC1_REGISTER_OFFSET; regs->vgaControl = AVIVO_D2VGA_CONTROL; break; case 2: offset = EVERGREEN_CRTC2_REGISTER_OFFSET; regs->vgaControl = EVERGREEN_D3VGA_CONTROL; break; case 3: offset = EVERGREEN_CRTC3_REGISTER_OFFSET; regs->vgaControl = EVERGREEN_D4VGA_CONTROL; break; case 4: offset = EVERGREEN_CRTC4_REGISTER_OFFSET; regs->vgaControl = EVERGREEN_D5VGA_CONTROL; break; case 5: offset = EVERGREEN_CRTC5_REGISTER_OFFSET; regs->vgaControl = EVERGREEN_D6VGA_CONTROL; break; default: ERROR("%s: Unknown CRTC %" B_PRIu32 "\n", __func__, crtcID); return B_ERROR; } regs->crtcOffset = offset; regs->grphEnable = EVERGREEN_GRPH_ENABLE + offset; regs->grphControl = EVERGREEN_GRPH_CONTROL + offset; regs->grphSwapControl = EVERGREEN_GRPH_SWAP_CONTROL + offset; regs->grphPrimarySurfaceAddr = EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS + offset; regs->grphSecondarySurfaceAddr = EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS + offset; regs->grphPrimarySurfaceAddrHigh = EVERGREEN_GRPH_PRIMARY_SURFACE_ADDRESS_HIGH + offset; regs->grphSecondarySurfaceAddrHigh = EVERGREEN_GRPH_SECONDARY_SURFACE_ADDRESS_HIGH + offset; regs->grphPitch = EVERGREEN_GRPH_PITCH + offset; regs->grphSurfaceOffsetX = EVERGREEN_GRPH_SURFACE_OFFSET_X + offset; regs->grphSurfaceOffsetY = EVERGREEN_GRPH_SURFACE_OFFSET_Y + offset; regs->grphXStart = EVERGREEN_GRPH_X_START + offset; regs->grphYStart = EVERGREEN_GRPH_Y_START + offset; regs->grphXEnd = EVERGREEN_GRPH_X_END + offset; regs->grphYEnd = EVERGREEN_GRPH_Y_END + offset; regs->modeDesktopHeight = EVERGREEN_DESKTOP_HEIGHT + offset; regs->modeDataFormat = EVERGREEN_DATA_FORMAT + offset; regs->viewportStart = EVERGREEN_VIEWPORT_START + offset; regs->viewportSize = EVERGREEN_VIEWPORT_SIZE + offset; } else if (info.chipsetID >= RADEON_RV770) { // R700 series uint32 offset = 0; switch (crtcID) { case 0: offset = R700_CRTC0_REGISTER_OFFSET; regs->vgaControl = AVIVO_D1VGA_CONTROL; regs->grphPrimarySurfaceAddrHigh = R700_D1GRPH_PRIMARY_SURFACE_ADDRESS_HIGH; break; case 1: offset = R700_CRTC1_REGISTER_OFFSET; regs->vgaControl = AVIVO_D2VGA_CONTROL; regs->grphPrimarySurfaceAddrHigh = R700_D2GRPH_PRIMARY_SURFACE_ADDRESS_HIGH; break; default: ERROR("%s: Unknown CRTC %" B_PRIu32 "\n", __func__, crtcID); return B_ERROR; } regs->crtcOffset = offset; regs->grphEnable = AVIVO_D1GRPH_ENABLE + offset; regs->grphControl = AVIVO_D1GRPH_CONTROL + offset; regs->grphSwapControl = AVIVO_D1GRPH_SWAP_CNTL + offset; regs->grphPrimarySurfaceAddr = R700_D1GRPH_PRIMARY_SURFACE_ADDRESS + offset; regs->grphSecondarySurfaceAddr = R700_D1GRPH_SECONDARY_SURFACE_ADDRESS + offset; regs->grphPitch = AVIVO_D1GRPH_PITCH + offset; regs->grphSurfaceOffsetX = AVIVO_D1GRPH_SURFACE_OFFSET_X + offset; regs->grphSurfaceOffsetY = AVIVO_D1GRPH_SURFACE_OFFSET_Y + offset; regs->grphXStart = AVIVO_D1GRPH_X_START + offset; regs->grphYStart = AVIVO_D1GRPH_Y_START + offset; regs->grphXEnd = AVIVO_D1GRPH_X_END + offset; regs->grphYEnd = AVIVO_D1GRPH_Y_END + offset; regs->modeDesktopHeight = AVIVO_D1MODE_DESKTOP_HEIGHT + offset; regs->modeDataFormat = AVIVO_D1MODE_DATA_FORMAT + offset; regs->viewportStart = AVIVO_D1MODE_VIEWPORT_START + offset; regs->viewportSize = AVIVO_D1MODE_VIEWPORT_SIZE + offset; } else if (info.chipsetID >= RADEON_RS600) { // Avivo+ uint32 offset = 0; switch (crtcID) { case 0: offset = R600_CRTC0_REGISTER_OFFSET; regs->vgaControl = AVIVO_D1VGA_CONTROL; break; case 1: offset = R600_CRTC1_REGISTER_OFFSET; regs->vgaControl = AVIVO_D2VGA_CONTROL; break; default: ERROR("%s: Unknown CRTC %" B_PRIu32 "\n", __func__, crtcID); return B_ERROR; } regs->crtcOffset = offset; regs->grphEnable = AVIVO_D1GRPH_ENABLE + offset; regs->grphControl = AVIVO_D1GRPH_CONTROL + offset; regs->grphSwapControl = AVIVO_D1GRPH_SWAP_CNTL + offset; regs->grphPrimarySurfaceAddr = AVIVO_D1GRPH_PRIMARY_SURFACE_ADDRESS + offset; regs->grphSecondarySurfaceAddr = AVIVO_D1GRPH_SECONDARY_SURFACE_ADDRESS + offset; // Surface Address high only used on r700 and higher regs->grphPrimarySurfaceAddrHigh = 0xDEAD; regs->grphSecondarySurfaceAddrHigh = 0xDEAD; regs->grphPitch = AVIVO_D1GRPH_PITCH + offset; regs->grphSurfaceOffsetX = AVIVO_D1GRPH_SURFACE_OFFSET_X + offset; regs->grphSurfaceOffsetY = AVIVO_D1GRPH_SURFACE_OFFSET_Y + offset; regs->grphXStart = AVIVO_D1GRPH_X_START + offset; regs->grphYStart = AVIVO_D1GRPH_Y_START + offset; regs->grphXEnd = AVIVO_D1GRPH_X_END + offset; regs->grphYEnd = AVIVO_D1GRPH_Y_END + offset; regs->modeDesktopHeight = AVIVO_D1MODE_DESKTOP_HEIGHT + offset; regs->modeDataFormat = AVIVO_D1MODE_DATA_FORMAT + offset; regs->viewportStart = AVIVO_D1MODE_VIEWPORT_START + offset; regs->viewportSize = AVIVO_D1MODE_VIEWPORT_SIZE + offset; } else { // this really shouldn't happen unless a driver PCIID chipset is wrong TRACE("%s, unknown Radeon chipset: %s\n", __func__, info.chipsetName); return B_ERROR; } TRACE("%s, registers for ATI chipset %s crt #%d loaded\n", __func__, info.chipsetName, crtcID); return B_OK; } status_t detect_crt_ranges(uint32 crtid) { edid1_info* edid = &gDisplay[crtid]->edidData; // Scan each display EDID description for monitor ranges for (uint32 index = 0; index < EDID1_NUM_DETAILED_MONITOR_DESC; index++) { edid1_detailed_monitor* monitor = &edid->detailed_monitor[index]; if (monitor->monitor_desc_type == EDID1_MONITOR_RANGES) { edid1_monitor_range range = monitor->data.monitor_range; gDisplay[crtid]->vfreqMin = range.min_v; /* in Hz */ gDisplay[crtid]->vfreqMax = range.max_v; gDisplay[crtid]->hfreqMin = range.min_h; /* in kHz */ gDisplay[crtid]->hfreqMax = range.max_h; return B_OK; } } return B_ERROR; } status_t detect_displays() { // reset known displays for (uint32 id = 0; id < MAX_DISPLAY; id++) { gDisplay[id]->attached = false; gDisplay[id]->powered = false; gDisplay[id]->foundRanges = false; } uint32 displayIndex = 0; for (uint32 id = 0; id < ATOM_MAX_SUPPORTED_DEVICE; id++) { if (gConnector[id]->valid == false) continue; if (displayIndex >= MAX_DISPLAY) continue; if (gConnector[id]->type == VIDEO_CONNECTOR_9DIN) { TRACE("%s: connector(%" B_PRIu32 "): Skipping 9DIN connector " "(not yet supported)\n", __func__, id); continue; } if (gConnector[id]->type == VIDEO_CONNECTOR_DP) { TRACE("%s: connector(%" B_PRIu32 "): Checking DP.\n", __func__, id); if (gConnector[id]->encoderExternal.valid == true) { // If this has a valid external encoder (dp bridge) // normally TRAVIS (LVDS) or NUTMEG (VGA) TRACE("%s: external encoder, performing bridge DDC setup\n", __func__); encoder_external_setup(id, EXTERNAL_ENCODER_ACTION_V3_DDC_SETUP); } edid1_info* edid = &gDisplay[displayIndex]->edidData; gDisplay[displayIndex]->attached = ddc2_dp_read_edid1(id, edid); // TODO: DDC Router switching for DisplayPort (and others?) if (gDisplay[displayIndex]->attached) { TRACE("%s: connector(%" B_PRIu32 "): Found DisplayPort EDID!\n", __func__, id); } } if (gConnector[id]->type == VIDEO_CONNECTOR_LVDS) { display_mode preferredMode; bool lvdsInfoFound = connector_read_mode_lvds(id, &preferredMode); TRACE("%s: connector(%" B_PRIu32 "): bit-banging LVDS for EDID.\n", __func__, id); gDisplay[displayIndex]->attached = connector_read_edid(id, &gDisplay[displayIndex]->edidData); if (!gDisplay[displayIndex]->attached && lvdsInfoFound) { // If we didn't find ddc edid data, fallback to lvdsInfo // We have to call connector_read_mode_lvds first to // collect SS data for the lvds connector TRACE("%s: connector(%" B_PRIu32 "): using AtomBIOS LVDS_Info " "preferred mode\n", __func__, id); gDisplay[displayIndex]->attached = true; memcpy(&gDisplay[displayIndex]->preferredMode, &preferredMode, sizeof(display_mode)); } } // If no display found yet, try more standard detection methods if (gDisplay[displayIndex]->attached == false) { TRACE("%s: connector(%" B_PRIu32 "): bit-banging ddc for EDID.\n", __func__, id); // Bit-bang edid from connector gDisplay[displayIndex]->attached = connector_read_edid(id, &gDisplay[displayIndex]->edidData); // Found EDID data? if (gDisplay[displayIndex]->attached) { TRACE("%s: connector(%" B_PRIu32 "): found EDID data.\n", __func__, id); if (gConnector[id]->type == VIDEO_CONNECTOR_DVII || gConnector[id]->type == VIDEO_CONNECTOR_HDMIB) { // These connectors can share gpio pins for data // communication between digital and analog encoders // (DVI-I is most common) edid1_info* edid = &gDisplay[displayIndex]->edidData; bool analogEncoder = gConnector[id]->encoder.type == VIDEO_ENCODER_TVDAC || gConnector[id]->encoder.type == VIDEO_ENCODER_DAC; bool digitalEncoder = gConnector[id]->encoder.type == VIDEO_ENCODER_TMDS; bool digitalEdid = edid->display.input_type ? true : false; if (digitalEdid && analogEncoder) { // Digital EDID + analog encoder? Lets try a load test gDisplay[displayIndex]->attached = encoder_analog_load_detect(id); } else if (!digitalEdid && digitalEncoder) { // non-digital EDID + digital encoder? Nope. gDisplay[displayIndex]->attached = false; } // Else... everything aligns as it should and attached = 1 } } } if (gDisplay[displayIndex]->attached != true) { // Nothing interesting here, move along continue; } // We found a valid / attached display gDisplay[displayIndex]->connectorIndex = id; // Populate physical connector index from gConnector init_registers(gDisplay[displayIndex]->regs, displayIndex); if (gDisplay[displayIndex]->preferredMode.virtual_width > 0) { // Found a single preferred mode gDisplay[displayIndex]->foundRanges = false; } else { // Use edid data and pull ranges if (detect_crt_ranges(displayIndex) == B_OK) gDisplay[displayIndex]->foundRanges = true; } displayIndex++; } // fallback if no attached monitors were found if (displayIndex == 0) { // This is a hack, however as we don't support HPD just yet, // it tries to prevent a "no displays" situation. ERROR("%s: ERROR: 0 attached monitors were found on display connectors." " Injecting first connector as a last resort.\n", __func__); for (uint32 id = 0; id < ATOM_MAX_SUPPORTED_DEVICE; id++) { // skip TV DAC connectors as likely fallback isn't for TV if (gConnector[id]->encoder.type == VIDEO_ENCODER_TVDAC) continue; gDisplay[0]->attached = true; gDisplay[0]->connectorIndex = id; init_registers(gDisplay[0]->regs, 0); if (detect_crt_ranges(0) == B_OK) gDisplay[0]->foundRanges = true; break; } } // Initial boot state is the first two crtc's powered if (gDisplay[0]->attached == true) gDisplay[0]->powered = true; if (gDisplay[1]->attached == true) gDisplay[1]->powered = true; return B_OK; } void debug_displays() { TRACE("Currently detected monitors===============\n"); for (uint32 id = 0; id < MAX_DISPLAY; id++) { ERROR("Display #%" B_PRIu32 " attached = %s\n", id, gDisplay[id]->attached ? "true" : "false"); uint32 connectorIndex = gDisplay[id]->connectorIndex; if (gDisplay[id]->attached) { uint32 connectorType = gConnector[connectorIndex]->type; uint32 encoderType = gConnector[connectorIndex]->encoder.type; ERROR(" + connector ID: %" B_PRIu32 "\n", connectorIndex); ERROR(" + connector type: %s\n", get_connector_name(connectorType)); ERROR(" + encoder type: %s\n", get_encoder_name(encoderType)); ERROR(" + limits: Vert Min/Max: %" B_PRIu32 "/%" B_PRIu32"\n", gDisplay[id]->vfreqMin, gDisplay[id]->vfreqMax); ERROR(" + limits: Horz Min/Max: %" B_PRIu32 "/%" B_PRIu32"\n", gDisplay[id]->hfreqMin, gDisplay[id]->hfreqMax); } } TRACE("==========================================\n"); } uint32 display_get_encoder_mode(uint32 connectorIndex) { // Is external DisplayPort Bridge? if (gConnector[connectorIndex]->encoderExternal.valid == true && gConnector[connectorIndex]->encoderExternal.isDPBridge == true) { return ATOM_ENCODER_MODE_DP; } // DVO Encoders (should be bridges) switch (gConnector[connectorIndex]->encoder.objectID) { case ENCODER_OBJECT_ID_INTERNAL_DVO1: case ENCODER_OBJECT_ID_INTERNAL_DDI: case ENCODER_OBJECT_ID_INTERNAL_KLDSCP_DVO1: return ATOM_ENCODER_MODE_DVO; } // Find display for connector so we can identify source of edid data int32 crtcID = -1; for (int32 id = 0; id < MAX_DISPLAY; id++) { if (gDisplay[id]->connectorIndex == connectorIndex) { crtcID = id; break; } } bool edidDigital = false; if (crtcID == -1) { ERROR("%s: BUG: executed on connector without assigned display!\n", __func__); } else { edid1_info* edid = &gDisplay[crtcID]->edidData; edidDigital = edid->display.input_type ? true : false; } // Normal encoder situations switch (gConnector[connectorIndex]->type) { case VIDEO_CONNECTOR_DVII: case VIDEO_CONNECTOR_HDMIB: /* HDMI-B is DL-DVI; analog works fine */ // TODO: if audio detected on edid and DCE4, ATOM_ENCODER_MODE_DVI // if audio detected on edid not DCE4, ATOM_ENCODER_MODE_HDMI if (edidDigital) return ATOM_ENCODER_MODE_DVI; else return ATOM_ENCODER_MODE_CRT; break; case VIDEO_CONNECTOR_DVID: case VIDEO_CONNECTOR_HDMIA: default: // TODO: if audio detected on edid and DCE4, ATOM_ENCODER_MODE_DVI // if audio detected on edid not DCE4, ATOM_ENCODER_MODE_HDMI return ATOM_ENCODER_MODE_DVI; case VIDEO_CONNECTOR_LVDS: return ATOM_ENCODER_MODE_LVDS; case VIDEO_CONNECTOR_DP: // dig_connector = radeon_connector->con_priv; // if ((dig_connector->dp_sink_type // == CONNECTOR_OBJECT_ID_DISPLAYPORT) // || (dig_connector->dp_sink_type == CONNECTOR_OBJECT_ID_eDP)) { // return ATOM_ENCODER_MODE_DP; // } // TODO: if audio detected on edid and DCE4, ATOM_ENCODER_MODE_DVI // if audio detected on edid not DCE4, ATOM_ENCODER_MODE_HDMI return ATOM_ENCODER_MODE_DP; case VIDEO_CONNECTOR_EDP: return ATOM_ENCODER_MODE_DP; case VIDEO_CONNECTOR_DVIA: case VIDEO_CONNECTOR_VGA: return ATOM_ENCODER_MODE_CRT; case VIDEO_CONNECTOR_COMPOSITE: case VIDEO_CONNECTOR_SVIDEO: case VIDEO_CONNECTOR_9DIN: return ATOM_ENCODER_MODE_TV; } } void display_crtc_lock(uint8 crtcID, int command) { TRACE("%s\n", __func__); ENABLE_CRTC_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, UpdateCRTC_DoubleBufferRegisters); memset(&args, 0, sizeof(args)); args.ucCRTC = crtcID; args.ucEnable = command; atom_execute_table(gAtomContext, index, (uint32*)&args); } void display_crtc_blank(uint8 crtcID, int command) { TRACE("%s\n", __func__); BLANK_CRTC_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, BlankCRTC); memset(&args, 0, sizeof(args)); args.ucCRTC = crtcID; args.ucBlanking = command; args.usBlackColorRCr = 0; args.usBlackColorGY = 0; args.usBlackColorBCb = 0; atom_execute_table(gAtomContext, index, (uint32*)&args); } void display_crtc_scale(uint8 crtcID, display_mode* mode) { TRACE("%s\n", __func__); ENABLE_SCALER_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, EnableScaler); memset(&args, 0, sizeof(args)); args.ucScaler = crtcID; args.ucEnable = ATOM_SCALER_DISABLE; atom_execute_table(gAtomContext, index, (uint32*)&args); } void display_crtc_dpms(uint8 crtcID, int mode) { radeon_shared_info &info = *gInfo->shared_info; switch (mode) { case B_DPMS_ON: TRACE("%s: crtc %" B_PRIu8 " dpms powerup\n", __func__, crtcID); if (gDisplay[crtcID]->attached == false) return; display_crtc_power(crtcID, ATOM_ENABLE); gDisplay[crtcID]->powered = true; if (info.dceMajor >= 3 && info.dceMajor < 6) display_crtc_memreq(crtcID, ATOM_ENABLE); display_crtc_blank(crtcID, ATOM_BLANKING_OFF); break; case B_DPMS_STAND_BY: case B_DPMS_SUSPEND: case B_DPMS_OFF: TRACE("%s: crtc %" B_PRIu8 " dpms powerdown\n", __func__, crtcID); if (gDisplay[crtcID]->attached == false) return; if (gDisplay[crtcID]->powered == true) display_crtc_blank(crtcID, ATOM_BLANKING); if (info.dceMajor >= 3 && info.dceMajor < 6) display_crtc_memreq(crtcID, ATOM_DISABLE); display_crtc_power(crtcID, ATOM_DISABLE); gDisplay[crtcID]->powered = false; } } void display_dce45_crtc_load_lut(uint8 crtcID) { radeon_shared_info &info = *gInfo->shared_info; register_info* regs = gDisplay[crtcID]->regs; TRACE("%s: crtcID %" B_PRIu8 "\n", __func__, crtcID); uint16* r = info.color_data; uint16* g = r + 256; uint16* b = r + 512; if (info.dceMajor >= 5) { Write32(OUT, NI_INPUT_CSC_CONTROL + regs->crtcOffset, NI_INPUT_CSC_GRPH_MODE(NI_INPUT_CSC_BYPASS) | NI_INPUT_CSC_OVL_MODE(NI_INPUT_CSC_BYPASS)); Write32(OUT, NI_PRESCALE_GRPH_CONTROL + regs->crtcOffset, NI_GRPH_PRESCALE_BYPASS); Write32(OUT, NI_PRESCALE_OVL_CONTROL + regs->crtcOffset, NI_OVL_PRESCALE_BYPASS); Write32(OUT, NI_INPUT_GAMMA_CONTROL + regs->crtcOffset, NI_GRPH_INPUT_GAMMA_MODE(NI_INPUT_GAMMA_USE_LUT) | NI_OVL_INPUT_GAMMA_MODE(NI_INPUT_GAMMA_USE_LUT)); } Write32(OUT, EVERGREEN_DC_LUT_CONTROL + regs->crtcOffset, 0); Write32(OUT, EVERGREEN_DC_LUT_BLACK_OFFSET_BLUE + regs->crtcOffset, 0); Write32(OUT, EVERGREEN_DC_LUT_BLACK_OFFSET_GREEN + regs->crtcOffset, 0); Write32(OUT, EVERGREEN_DC_LUT_BLACK_OFFSET_RED + regs->crtcOffset, 0); Write32(OUT, EVERGREEN_DC_LUT_WHITE_OFFSET_BLUE + regs->crtcOffset, 0xffff); Write32(OUT, EVERGREEN_DC_LUT_WHITE_OFFSET_GREEN + regs->crtcOffset, 0xffff); Write32(OUT, EVERGREEN_DC_LUT_WHITE_OFFSET_RED + regs->crtcOffset, 0xffff); Write32(OUT, EVERGREEN_DC_LUT_RW_MODE, 0); Write32(OUT, EVERGREEN_DC_LUT_WRITE_EN_MASK, 0x00000007); Write32(OUT, EVERGREEN_DC_LUT_RW_INDEX, 0); for (int i = 0; i < 256; i++) { Write32(OUT, EVERGREEN_DC_LUT_30_COLOR + regs->crtcOffset, (r[i] << 20) | (g[i] << 10) | (b[i] << 0)); } if (info.dceMajor >= 5) { Write32(OUT, NI_DEGAMMA_CONTROL + regs->crtcOffset, (NI_GRPH_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) | NI_OVL_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) | NI_ICON_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) | NI_CURSOR_DEGAMMA_MODE(NI_DEGAMMA_BYPASS))); Write32(OUT, NI_GAMUT_REMAP_CONTROL + regs->crtcOffset, (NI_GRPH_GAMUT_REMAP_MODE(NI_GAMUT_REMAP_BYPASS) | NI_OVL_GAMUT_REMAP_MODE(NI_GAMUT_REMAP_BYPASS))); Write32(OUT, NI_REGAMMA_CONTROL + regs->crtcOffset, (NI_GRPH_REGAMMA_MODE(NI_REGAMMA_BYPASS) | NI_OVL_REGAMMA_MODE(NI_REGAMMA_BYPASS))); Write32(OUT, NI_OUTPUT_CSC_CONTROL + regs->crtcOffset, (NI_OUTPUT_CSC_GRPH_MODE(NI_OUTPUT_CSC_BYPASS) | NI_OUTPUT_CSC_OVL_MODE(NI_OUTPUT_CSC_BYPASS))); /* XXX match this to the depth of the crtc fmt block, move to modeset? */ Write32(OUT, 0x6940 + regs->crtcOffset, 0); } } void display_avivo_crtc_load_lut(uint8 crtcID) { radeon_shared_info &info = *gInfo->shared_info; register_info* regs = gDisplay[crtcID]->regs; TRACE("%s: crtcID %" B_PRIu8 "\n", __func__, crtcID); uint16* r = info.color_data; uint16* g = r + 256; uint16* b = r + 512; Write32(OUT, AVIVO_DC_LUTA_CONTROL + regs->crtcOffset, 0); Write32(OUT, AVIVO_DC_LUTA_BLACK_OFFSET_BLUE + regs->crtcOffset, 0); Write32(OUT, AVIVO_DC_LUTA_BLACK_OFFSET_GREEN + regs->crtcOffset, 0); Write32(OUT, AVIVO_DC_LUTA_BLACK_OFFSET_RED + regs->crtcOffset, 0); Write32(OUT, AVIVO_DC_LUTA_WHITE_OFFSET_BLUE + regs->crtcOffset, 0xffff); Write32(OUT, AVIVO_DC_LUTA_WHITE_OFFSET_GREEN + regs->crtcOffset, 0xffff); Write32(OUT, AVIVO_DC_LUTA_WHITE_OFFSET_RED + regs->crtcOffset, 0xffff); Write32(OUT, AVIVO_DC_LUT_RW_SELECT, crtcID); Write32(OUT, AVIVO_DC_LUT_RW_MODE, 0); Write32(OUT, AVIVO_DC_LUT_WRITE_EN_MASK, 0x0000003f); Write32(OUT, AVIVO_DC_LUT_RW_INDEX, 0); for (int i = 0; i < 256; i++) { Write32(OUT, AVIVO_DC_LUT_30_COLOR, (r[i] << 20) | (g[i] << 10) | (b[i] << 0)); } Write32(OUT, AVIVO_D1GRPH_LUT_SEL + regs->crtcOffset, crtcID); } void display_crtc_fb_set(uint8 crtcID, display_mode* mode) { radeon_shared_info &info = *gInfo->shared_info; register_info* regs = gDisplay[crtcID]->regs; uint16* r = info.color_data; uint16* g = r + 256; uint16* b = r + 512; uint32 fbSwap; if (info.dceMajor >= 4) fbSwap = EVERGREEN_GRPH_ENDIAN_SWAP(EVERGREEN_GRPH_ENDIAN_NONE); else fbSwap = R600_D1GRPH_SWAP_ENDIAN_NONE; uint32 fbFormat; uint32 bytesPerPixel; uint32 bitsPerPixel; switch (mode->space) { case B_CMAP8: bytesPerPixel = 1; bitsPerPixel = 8; if (info.dceMajor >= 4) { fbFormat = (EVERGREEN_GRPH_DEPTH(EVERGREEN_GRPH_DEPTH_8BPP) | EVERGREEN_GRPH_FORMAT(EVERGREEN_GRPH_FORMAT_INDEXED)); } else { fbFormat = AVIVO_D1GRPH_CONTROL_DEPTH_8BPP | AVIVO_D1GRPH_CONTROL_8BPP_INDEXED; } // TODO: copy system color map into shared info break; case B_RGB15_LITTLE: bytesPerPixel = 2; bitsPerPixel = 15; if (info.dceMajor >= 4) { fbFormat = (EVERGREEN_GRPH_DEPTH(EVERGREEN_GRPH_DEPTH_16BPP) | EVERGREEN_GRPH_FORMAT(EVERGREEN_GRPH_FORMAT_ARGB1555)); } else { fbFormat = AVIVO_D1GRPH_CONTROL_DEPTH_16BPP | AVIVO_D1GRPH_CONTROL_16BPP_ARGB1555; } break; case B_RGB16_LITTLE: bytesPerPixel = 2; bitsPerPixel = 16; if (info.dceMajor >= 4) { fbFormat = (EVERGREEN_GRPH_DEPTH(EVERGREEN_GRPH_DEPTH_16BPP) | EVERGREEN_GRPH_FORMAT(EVERGREEN_GRPH_FORMAT_ARGB565)); #ifdef __POWERPC__ fbSwap = EVERGREEN_GRPH_ENDIAN_SWAP(EVERGREEN_GRPH_ENDIAN_8IN16); #endif } else { fbFormat = AVIVO_D1GRPH_CONTROL_DEPTH_16BPP | AVIVO_D1GRPH_CONTROL_16BPP_RGB565; #ifdef __POWERPC__ fbSwap = R600_D1GRPH_SWAP_ENDIAN_16BIT; #endif } { // default gamma table uint16 gamma = 0; for (int i = 0; i < 256; i++) { r[i] = gamma; g[i] = gamma; b[i] = gamma; gamma += 4; } } break; case B_RGB24_LITTLE: case B_RGB32_LITTLE: default: bytesPerPixel = 4; bitsPerPixel = 32; if (info.dceMajor >= 4) { fbFormat = (EVERGREEN_GRPH_DEPTH(EVERGREEN_GRPH_DEPTH_32BPP) | EVERGREEN_GRPH_FORMAT(EVERGREEN_GRPH_FORMAT_ARGB8888)); #ifdef __POWERPC__ fbSwap = EVERGREEN_GRPH_ENDIAN_SWAP(EVERGREEN_GRPH_ENDIAN_8IN32); #endif } else { fbFormat = AVIVO_D1GRPH_CONTROL_DEPTH_32BPP | AVIVO_D1GRPH_CONTROL_32BPP_ARGB8888; #ifdef __POWERPC__ fbSwap = R600_D1GRPH_SWAP_ENDIAN_32BIT; #endif } { // default gamma table uint16 gamma = 0; for (int i = 0; i < 256; i++) { r[i] = gamma; g[i] = gamma; b[i] = gamma; gamma += 4; } } break; } Write32(OUT, regs->vgaControl, 0); uint64 fbAddress = gInfo->fb.vramStart; TRACE("%s: Framebuffer at: 0x%" B_PRIX64 "\n", __func__, fbAddress); if (info.chipsetID >= RADEON_RV770) { TRACE("%s: Set SurfaceAddress High: 0x%" B_PRIX32 "\n", __func__, (fbAddress >> 32) & 0xf); Write32(OUT, regs->grphPrimarySurfaceAddrHigh, (fbAddress >> 32) & 0xf); Write32(OUT, regs->grphSecondarySurfaceAddrHigh, (fbAddress >> 32) & 0xf); } TRACE("%s: Set SurfaceAddress: 0x%" B_PRIX64 "\n", __func__, (fbAddress & 0xFFFFFFFF)); Write32(OUT, regs->grphPrimarySurfaceAddr, (fbAddress & 0xFFFFFFFF)); Write32(OUT, regs->grphSecondarySurfaceAddr, (fbAddress & 0xFFFFFFFF)); if (info.chipsetID >= RADEON_R600) { Write32(CRT, regs->grphControl, fbFormat); Write32(CRT, regs->grphSwapControl, fbSwap); } // TODO: Technically if chip >= RS600 int largeAlign = (info.dceMajor >= 2) ? 1 : 0; // Align our framebuffer width uint32 widthAligned = mode->virtual_width; uint32 pitchMask = 0; switch (bytesPerPixel) { case 1: pitchMask = largeAlign ? 255 : 127; break; case 2: pitchMask = largeAlign ? 127 : 31; break; case 3: case 4: pitchMask = largeAlign ? 63 : 15; break; } widthAligned += pitchMask; widthAligned &= ~pitchMask; TRACE("%s: fb: %" B_PRIu32 "x%" B_PRIu32 " (%" B_PRIu32 " bpp)\n", __func__, mode->timing.h_display, mode->timing.v_display, bitsPerPixel); TRACE("%s: fb pitch: %" B_PRIu32 " \n", __func__, widthAligned); Write32(CRT, regs->grphSurfaceOffsetX, 0); Write32(CRT, regs->grphSurfaceOffsetY, 0); Write32(CRT, regs->grphXStart, 0); Write32(CRT, regs->grphYStart, 0); Write32(CRT, regs->grphXEnd, mode->virtual_width); Write32(CRT, regs->grphYEnd, mode->virtual_height); Write32(CRT, regs->grphPitch, widthAligned); Write32(CRT, regs->grphEnable, 1); // Enable Frame buffer Write32(CRT, regs->modeDesktopHeight, mode->virtual_height); uint32 viewportWidth = mode->timing.h_display; uint32 viewportHeight = (mode->timing.v_display + 1) & ~1; Write32(CRT, regs->viewportStart, 0); Write32(CRT, regs->viewportSize, (viewportWidth << 16) | viewportHeight); // Pageflip setup if (info.dceMajor >= 4) { uint32 tmp = Read32(OUT, EVERGREEN_GRPH_FLIP_CONTROL + regs->crtcOffset); tmp &= ~EVERGREEN_GRPH_SURFACE_UPDATE_H_RETRACE_EN; Write32(OUT, EVERGREEN_GRPH_FLIP_CONTROL + regs->crtcOffset, tmp); Write32(OUT, EVERGREEN_MASTER_UPDATE_MODE + regs->crtcOffset, 0); // Pageflip to happen anywhere in vblank display_dce45_crtc_load_lut(crtcID); } else { uint32 tmp = Read32(OUT, AVIVO_D1GRPH_FLIP_CONTROL + regs->crtcOffset); tmp &= ~AVIVO_D1GRPH_SURFACE_UPDATE_H_RETRACE_EN; Write32(OUT, AVIVO_D1GRPH_FLIP_CONTROL + regs->crtcOffset, tmp); Write32(OUT, AVIVO_D1MODE_MASTER_UPDATE_MODE + regs->crtcOffset, 0); // Pageflip to happen anywhere in vblank display_avivo_crtc_load_lut(crtcID); } // update shared info gInfo->shared_info->bytes_per_row = widthAligned * bytesPerPixel; gInfo->shared_info->current_mode = *mode; gInfo->shared_info->bits_per_pixel = bitsPerPixel; } void display_crtc_set(uint8 crtcID, display_mode* mode) { display_timing& displayTiming = mode->timing; TRACE("%s called to do %dx%d\n", __func__, displayTiming.h_display, displayTiming.v_display); SET_CRTC_TIMING_PARAMETERS_PS_ALLOCATION args; int index = GetIndexIntoMasterTable(COMMAND, SetCRTC_Timing); uint16 misc = 0; memset(&args, 0, sizeof(args)); args.usH_Total = B_HOST_TO_LENDIAN_INT16(displayTiming.h_total); args.usH_Disp = B_HOST_TO_LENDIAN_INT16(displayTiming.h_display); args.usH_SyncStart = B_HOST_TO_LENDIAN_INT16(displayTiming.h_sync_start); args.usH_SyncWidth = B_HOST_TO_LENDIAN_INT16(displayTiming.h_sync_end - displayTiming.h_sync_start); args.usV_Total = B_HOST_TO_LENDIAN_INT16(displayTiming.v_total); args.usV_Disp = B_HOST_TO_LENDIAN_INT16(displayTiming.v_display); args.usV_SyncStart = B_HOST_TO_LENDIAN_INT16(displayTiming.v_sync_start); args.usV_SyncWidth = B_HOST_TO_LENDIAN_INT16(displayTiming.v_sync_end - displayTiming.v_sync_start); args.ucOverscanRight = 0; args.ucOverscanLeft = 0; args.ucOverscanBottom = 0; args.ucOverscanTop = 0; if ((displayTiming.flags & B_POSITIVE_HSYNC) == 0) misc |= ATOM_HSYNC_POLARITY; if ((displayTiming.flags & B_POSITIVE_VSYNC) == 0) misc |= ATOM_VSYNC_POLARITY; args.susModeMiscInfo.usAccess = B_HOST_TO_LENDIAN_INT16(misc); args.ucCRTC = crtcID; atom_execute_table(gAtomContext, index, (uint32*)&args); } void display_crtc_set_dtd(uint8 crtcID, display_mode* mode) { display_timing& displayTiming = mode->timing; TRACE("%s called to do %dx%d\n", __func__, displayTiming.h_display, displayTiming.v_display); SET_CRTC_USING_DTD_TIMING_PARAMETERS args; int index = GetIndexIntoMasterTable(COMMAND, SetCRTC_UsingDTDTiming); uint16 misc = 0; memset(&args, 0, sizeof(args)); // Note: the code below assumes H & V borders are both zero uint16 blankStart = MIN(displayTiming.h_sync_start, displayTiming.h_display); uint16 blankEnd = MAX(displayTiming.h_sync_end, displayTiming.h_total); args.usH_Size = B_HOST_TO_LENDIAN_INT16(displayTiming.h_display); args.usH_Blanking_Time = B_HOST_TO_LENDIAN_INT16(blankEnd - blankStart); blankStart = MIN(displayTiming.v_sync_start, displayTiming.v_display); blankEnd = MAX(displayTiming.v_sync_end, displayTiming.v_total); args.usV_Size = B_HOST_TO_LENDIAN_INT16(displayTiming.v_display); args.usV_Blanking_Time = B_HOST_TO_LENDIAN_INT16(blankEnd - blankStart); args.usH_SyncOffset = B_HOST_TO_LENDIAN_INT16(displayTiming.h_sync_start - displayTiming.h_display); args.usH_SyncWidth = B_HOST_TO_LENDIAN_INT16(displayTiming.h_sync_end - displayTiming.h_sync_start); args.usV_SyncOffset = B_HOST_TO_LENDIAN_INT16(displayTiming.v_sync_start - displayTiming.v_display); args.usV_SyncWidth = B_HOST_TO_LENDIAN_INT16(displayTiming.v_sync_end - displayTiming.v_sync_start); args.ucH_Border = 0; args.ucV_Border = 0; if ((displayTiming.flags & B_POSITIVE_HSYNC) == 0) misc |= ATOM_HSYNC_POLARITY; if ((displayTiming.flags & B_POSITIVE_VSYNC) == 0) misc |= ATOM_VSYNC_POLARITY; args.susModeMiscInfo.usAccess = B_HOST_TO_LENDIAN_INT16(misc); args.ucCRTC = crtcID; atom_execute_table(gAtomContext, index, (uint32*)&args); } void display_crtc_ss(pll_info* pll, int command) { TRACE("%s\n", __func__); radeon_shared_info &info = *gInfo->shared_info; if (command == ATOM_ENABLE) { if (pll->ssPercentage == 0) { TRACE("%s: ssPercentage 0, ignoring SS request\n", __func__); return; } if ((pll->ssType & ATOM_EXTERNAL_SS_MASK) != 0) { TRACE("%s: external SS, ignoring SS request\n", __func__); return; } } else { if (pll_usage_count(pll->id) > 1) { // TODO: Check if PLL has SS enabled on any other displays, if so // we need to also skip this function. TRACE("%s: TODO: shared PLL detected!\n", __func__); } } int index = GetIndexIntoMasterTable(COMMAND, EnableSpreadSpectrumOnPPLL); union enableSS { ENABLE_LVDS_SS_PARAMETERS lvds_ss; ENABLE_LVDS_SS_PARAMETERS_V2 lvds_ss_2; ENABLE_SPREAD_SPECTRUM_ON_PPLL_PS_ALLOCATION v1; ENABLE_SPREAD_SPECTRUM_ON_PPLL_V2 v2; ENABLE_SPREAD_SPECTRUM_ON_PPLL_V3 v3; }; union enableSS args; memset(&args, 0, sizeof(args)); if (info.dceMajor >= 5) { args.v3.usSpreadSpectrumAmountFrac = B_HOST_TO_LENDIAN_INT16(0); args.v3.ucSpreadSpectrumType = pll->ssType & ATOM_SS_CENTRE_SPREAD_MODE_MASK; switch (pll->id) { case ATOM_PPLL1: args.v3.ucSpreadSpectrumType |= ATOM_PPLL_SS_TYPE_V3_P1PLL; break; case ATOM_PPLL2: args.v3.ucSpreadSpectrumType |= ATOM_PPLL_SS_TYPE_V3_P2PLL; break; case ATOM_DCPLL: args.v3.ucSpreadSpectrumType |= ATOM_PPLL_SS_TYPE_V3_DCPLL; break; case ATOM_PPLL_INVALID: return; default: ERROR("%s: BUG: Invalid PLL ID!\n", __func__); return; } args.v3.usSpreadSpectrumAmount = B_HOST_TO_LENDIAN_INT16(pll->ssAmount); args.v3.usSpreadSpectrumStep = B_HOST_TO_LENDIAN_INT16(pll->ssStep); args.v3.ucEnable = command; } else if (info.dceMajor >= 4) { args.v2.usSpreadSpectrumPercentage = B_HOST_TO_LENDIAN_INT16(pll->ssPercentage); args.v2.ucSpreadSpectrumType = pll->ssType & ATOM_SS_CENTRE_SPREAD_MODE_MASK; switch (pll->id) { case ATOM_PPLL1: args.v2.ucSpreadSpectrumType |= ATOM_PPLL_SS_TYPE_V2_P1PLL; break; case ATOM_PPLL2: args.v2.ucSpreadSpectrumType |= ATOM_PPLL_SS_TYPE_V3_P2PLL; break; case ATOM_DCPLL: args.v2.ucSpreadSpectrumType |= ATOM_PPLL_SS_TYPE_V3_DCPLL; break; case ATOM_PPLL_INVALID: return; default: ERROR("%s: BUG: Invalid PLL ID!\n", __func__); return; } args.v2.usSpreadSpectrumAmount = B_HOST_TO_LENDIAN_INT16(pll->ssAmount); args.v2.usSpreadSpectrumStep = B_HOST_TO_LENDIAN_INT16(pll->ssStep); args.v2.ucEnable = command; } else if (info.dceMajor >= 3) { args.v1.usSpreadSpectrumPercentage = B_HOST_TO_LENDIAN_INT16(pll->ssPercentage); args.v1.ucSpreadSpectrumType = pll->ssType & ATOM_SS_CENTRE_SPREAD_MODE_MASK; args.v1.ucSpreadSpectrumStep = pll->ssStep; args.v1.ucSpreadSpectrumDelay = pll->ssDelay; args.v1.ucSpreadSpectrumRange = pll->ssRange; args.v1.ucPpll = pll->id; args.v1.ucEnable = command; } else if (info.dceMajor >= 2) { if (command == ATOM_DISABLE) { radeon_gpu_ss_control(pll, false); return; } args.lvds_ss_2.usSpreadSpectrumPercentage = B_HOST_TO_LENDIAN_INT16(pll->ssPercentage); args.lvds_ss_2.ucSpreadSpectrumType = pll->ssType & ATOM_SS_CENTRE_SPREAD_MODE_MASK; args.lvds_ss_2.ucSpreadSpectrumStep = pll->ssStep; args.lvds_ss_2.ucSpreadSpectrumDelay = pll->ssDelay; args.lvds_ss_2.ucSpreadSpectrumRange = pll->ssRange; args.lvds_ss_2.ucEnable = command; } else { ERROR("%s: TODO: Old card SS control\n", __func__); return; } atom_execute_table(gAtomContext, index, (uint32*)&args); } void display_crtc_power(uint8 crtcID, int command) { TRACE("%s\n", __func__); int index = GetIndexIntoMasterTable(COMMAND, EnableCRTC); ENABLE_CRTC_PS_ALLOCATION args; memset(&args, 0, sizeof(args)); args.ucCRTC = crtcID; args.ucEnable = command; atom_execute_table(gAtomContext, index, (uint32*)&args); } void display_crtc_memreq(uint8 crtcID, int command) { TRACE("%s\n", __func__); int index = GetIndexIntoMasterTable(COMMAND, EnableCRTCMemReq); ENABLE_CRTC_PS_ALLOCATION args; memset(&args, 0, sizeof(args)); args.ucCRTC = crtcID; args.ucEnable = command; atom_execute_table(gAtomContext, index, (uint32*)&args); }
30.361813
78
0.724652
Kirishikesan
7dd2919f15af955fbc9110ac596633082ae5fa40
360
cpp
C++
utils/printVector.cpp
juangl/random-algorithms
0d5a934e8a3d23c410f6e72fb57ad5cb67d519da
[ "MIT" ]
1
2019-01-12T23:58:23.000Z
2019-01-12T23:58:23.000Z
utils/printVector.cpp
juangl/random-algorithms
0d5a934e8a3d23c410f6e72fb57ad5cb67d519da
[ "MIT" ]
null
null
null
utils/printVector.cpp
juangl/random-algorithms
0d5a934e8a3d23c410f6e72fb57ad5cb67d519da
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; template <class T> void printVector(const T& vec) { for (int i = 0; i < vec.size(); i++) { cout << vec[i]; if (i != vec.size() - 1) { cout << ", "; } } cout << endl; } template <class T> void printIter(const T& vec) { for (const auto& e : vec) { cout << e << " "; } cout << endl; }
15.652174
40
0.508333
juangl
7dd330da723c44ad111558e0d9e26ce2ee04919b
487
cpp
C++
test/language/expressions/cpp/FloatTypeTest.cpp
PeachOS/zserio
ea01f6906c125a6baab7e8ed865eeb08cd46c37c
[ "BSD-3-Clause" ]
2
2019-02-06T17:50:24.000Z
2019-11-20T16:51:34.000Z
test/language/expressions/cpp/FloatTypeTest.cpp
PeachOS/zserio
ea01f6906c125a6baab7e8ed865eeb08cd46c37c
[ "BSD-3-Clause" ]
1
2019-11-25T16:25:51.000Z
2019-11-25T18:09:39.000Z
test/language/expressions/cpp/FloatTypeTest.cpp
PeachOS/zserio
ea01f6906c125a6baab7e8ed865eeb08cd46c37c
[ "BSD-3-Clause" ]
null
null
null
#include "math.h" #include "gtest/gtest.h" #include "expressions/float_type/FloatTypeExpression.h" namespace expressions { namespace float_type { TEST(FloatTypeTest, result) { FloatTypeExpression floatTypeExpression; const float floatValue = 15.0; floatTypeExpression.setFloatValue(floatValue); const bool result = (floatValue * 2.0 + 1.0 / 0.5 > 1.0); ASSERT_EQ(result, floatTypeExpression.funcResult()); } } // namespace float_type } // namespace expressions
20.291667
61
0.737166
PeachOS
7dd54c8d9c7f6ef4156ffc7006c10936f187e60a
328
cpp
C++
source/Item22_11/main.cpp
hakobyankhachatur/Scott-Meyers-Effective-Modern-C-
41e78619b9622ef7f01746fdebadb5e1da005157
[ "MIT" ]
null
null
null
source/Item22_11/main.cpp
hakobyankhachatur/Scott-Meyers-Effective-Modern-C-
41e78619b9622ef7f01746fdebadb5e1da005157
[ "MIT" ]
null
null
null
source/Item22_11/main.cpp
hakobyankhachatur/Scott-Meyers-Effective-Modern-C-
41e78619b9622ef7f01746fdebadb5e1da005157
[ "MIT" ]
null
null
null
#include <iostream> #include "Widget.h" int main() { std::cout << "Hello, World!" << std::endl; std::shared_ptr<Widget> p1(new Widget); std::cout<<p1.use_count()<<std::endl; std::shared_ptr<Widget> p2(p1); std::cout<<p1.use_count()<<std::endl; std::cout<<p2.use_count()<<std::endl; return 0; }
18.222222
46
0.594512
hakobyankhachatur
7dd8063423dfb331deaeb05626cca1af90f76db3
1,058
cc
C++
geometry/visualization/visualize_nullspace_demo.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
1
2019-04-14T11:40:28.000Z
2019-04-14T11:40:28.000Z
geometry/visualization/visualize_nullspace_demo.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
5
2018-04-18T13:54:29.000Z
2019-08-22T20:04:17.000Z
geometry/visualization/visualize_nullspace_demo.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
1
2018-12-24T03:45:47.000Z
2018-12-24T03:45:47.000Z
#include "eigen.hh" #include "geometry/visualization/visualize_nullspace.hh" #include "viewer/primitives/simple_geometry.hh" #include "viewer/window_3d.hh" namespace geometry { namespace visualization { using Vec3 = Eigen::Vector3d; void go() { const auto view = viewer::get_window3d("Mr. Demo"); view->set_target_from_world( SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero())); const auto geo = view->add_primitive<viewer::SimpleGeometry>(); view->set_continue_time_ms(20); const double level_set = 5.0; const auto func = [level_set](const Eigen::VectorXd& x) { Eigen::Matrix2d H = Eigen::Matrix2d::Identity(); H(1, 1) = 2.0; return x.dot(H * x) - level_set; // return x.dot(Eigen::Vector2d(std::sin(x(0)), 0.0)) - 1.0; // return std::sin(x(0)) + (x(1) * x(1)) - 3.0; }; visualize_nullspace(*geo, func, Eigen::VectorXd::Ones(2)); geo->flip(); view->spin_until_step(); } } // namespace visualization } // namespace geometry int main() { geometry::visualization::go(); }
27.128205
88
0.660681
jpanikulam
7ddbfacb89354b289ede7f6dd88e02e9cdcf382a
2,043
hpp
C++
include/locic/AST/PredicateDecl.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
80
2015-02-19T21:38:57.000Z
2016-05-25T06:53:12.000Z
include/locic/AST/PredicateDecl.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
8
2015-02-20T09:47:20.000Z
2015-11-13T07:49:17.000Z
include/locic/AST/PredicateDecl.hpp
scross99/locic
a24bb380e17f8af69e7389acf8ce354c91a2abf3
[ "MIT" ]
6
2015-02-20T11:26:19.000Z
2016-04-13T14:30:39.000Z
#ifndef LOCIC_AST_PREDICATEDECL_HPP #define LOCIC_AST_PREDICATEDECL_HPP #include <string> #include <locic/AST/Node.hpp> #include <locic/AST/Symbol.hpp> #include <locic/Support/String.hpp> namespace locic { namespace AST { struct TypeDecl; class PredicateDecl { public: enum Kind { TRUE, FALSE, SELFCONST, BRACKET, TYPESPEC, SYMBOL, AND, OR }; static PredicateDecl* True(); static PredicateDecl* False(); static PredicateDecl* SelfConst(); static PredicateDecl* Bracket(Node<PredicateDecl> expr); static PredicateDecl* TypeSpec(Node<TypeDecl> type, Node<TypeDecl> requireType); static PredicateDecl* Symbol(Node<AST::Symbol> symbol); static PredicateDecl* And(Node<PredicateDecl> left, Node<PredicateDecl> right); static PredicateDecl* Or(Node<PredicateDecl> left, Node<PredicateDecl> right); PredicateDecl(const PredicateDecl&) = default; ~PredicateDecl(); Kind kind() const; const Node<PredicateDecl>& bracketExpr() const; Node<TypeDecl>& typeSpecType(); const Node<TypeDecl>& typeSpecType() const; Node<TypeDecl>& typeSpecRequireType(); const Node<TypeDecl>& typeSpecRequireType() const; const Node<AST::Symbol>& symbol() const; const Node<PredicateDecl>& andLeft() const; const Node<PredicateDecl>& andRight() const; const Node<PredicateDecl>& orLeft() const; const Node<PredicateDecl>& orRight() const; std::string toString() const; private: Kind kind_; Node<AST::Symbol> symbol_; struct { Node<PredicateDecl> expr; } bracket_; struct { Node<TypeDecl> type; Node<TypeDecl> requireType; } typeSpec_; struct { Node<PredicateDecl> left; Node<PredicateDecl> right; } and_; struct { Node<PredicateDecl> left; Node<PredicateDecl> right; } or_; PredicateDecl(Kind pKind); }; } } #endif
20.636364
84
0.639256
scross99
7de09a8863662ed3a96921dc1216de15d6dd9b56
593
cpp
C++
src/SML.cpp
aceoyale/SML
513d60be40f1e2629b4475cfdf1b4913c1a5154a
[ "MIT" ]
1
2020-10-08T09:31:54.000Z
2020-10-08T09:31:54.000Z
src/SML.cpp
aceoyale/SML
513d60be40f1e2629b4475cfdf1b4913c1a5154a
[ "MIT" ]
null
null
null
src/SML.cpp
aceoyale/SML
513d60be40f1e2629b4475cfdf1b4913c1a5154a
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> #include "SMLMath.h" #include "SMLMat1x3.h" #include "SMLMat3x1.h" #include "SMLMat4x4.h" #include "SMLDef.h" #include "SMLFunc.h" int main() { Vector a(1.345, 1.23, 3.556); SML::Vector b(2.145, 7.089, 0.0000156); SML::Vector result(a + b); Vector subresult(a - b); std::cout << result.x << " " << result.y << " " << result.z << std::endl; std::cout << " . " << std::endl; std::cout << subresult.x << " " << subresult.y << " " << subresult.z << std::endl; std::cout << "Hello From This Side Of The SML Library!" << std::endl; std::cin.get(); }
25.782609
83
0.598651
aceoyale
7de8e5b6d911a85db251431e73407508ac656775
95,740
cpp
C++
openbabel-2.4.1/src/formats/xml/cmlformat.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
1
2017-09-16T07:36:29.000Z
2017-09-16T07:36:29.000Z
openbabel-2.4.1/src/formats/xml/cmlformat.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
null
null
null
openbabel-2.4.1/src/formats/xml/cmlformat.cpp
sxhexe/reaction-route-search
f7694c84ca1def4a133ade3e1e2e09705cd28312
[ "MIT" ]
null
null
null
/********************************************************************** Copyright (C) 2005 by Chris Morley Some portions Copyright (C) 2006 by Geoffrey R. Hutchison This file is part of the Open Babel project. For more information, see <http://openbabel.org/> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***********************************************************************/ #include <openbabel/babelconfig.h> #include <openbabel/math/matrix3x3.h> #include <openbabel/kinetics.h> #include <openbabel/stereo/tetrahedral.h> #include <openbabel/stereo/cistrans.h> #include <openbabel/atomclass.h> #include <openbabel/xml.h> #include <float.h> #ifdef HAVE_SHARED_POINTER #include <openbabel/reaction.h> #endif #ifdef WIN32 #pragma warning (disable : 4800) #endif #include <sstream> using namespace std; namespace OpenBabel { class CMLFormat : public XMLMoleculeFormat { private: const char* CML1NamespaceURI()const {return "http://cml.sourceforge.net/schema/cmlCore/HTMLDOCS/cmlCore.pdf";} const char* CML2NamespaceURI()const{return "http://www.xml-cml.org/schema/cml2/core";} public: //Constuctor used on startup which registers this format type ID CMLFormat() { OBConversion::RegisterFormat("cml", this, "chemical/x-cml"); OBConversion::RegisterFormat("mrv", this); //subset of Marvin only OBConversion::RegisterOptionParam("1", this); OBConversion::RegisterOptionParam("a", this); OBConversion::RegisterOptionParam("N", this, 1); OBConversion::RegisterOptionParam("m", this); OBConversion::RegisterOptionParam("x", this); OBConversion::RegisterOptionParam("h", this); OBConversion::RegisterOptionParam("c", this); OBConversion::RegisterOptionParam("p", this); OBConversion::RegisterOptionParam("2", this, 0, OBConversion::INOPTIONS); XMLConversion::RegisterXMLFormat(this, true); //this is the default XLMformat XMLConversion::RegisterXMLFormat(this, false,CML1NamespaceURI());//CML1 also XMLConversion::RegisterXMLFormat(this, false,CML2NamespaceURI());//Old CML2 also } virtual const char* NamespaceURI()const{return "http://www.xml-cml.org/schema";} virtual const char* Description() { return "Chemical Markup Language\n" "An XML format for interchange of chemical information.\n\n" "This format writes and reads CML XML files. To write CML1 format rather than\n" "the default CML2, use the ``-x1`` option. To write the array form use ``-xa``\n" "and to specify all hydrogens using the hydrogenCount attribute on atoms use\n" "``-xh``.\n\n" "Crystal structures are written using the <crystal>, <xfract> (,...etc.)\n" "elements if the OBMol has a OBGenericDataType::UnitCell data.\n\n" "All these forms are handled transparently during reading. Only a subset of\n" "CML elements and attributes are recognised, but these include most of those\n" "which define chemical structure, see below.\n\n" "The following are read:\n\n" "- Elements:\n\n" " - molecule, atomArray, atom, bondArray, bond, atomParity, bondStereo\n" " - name, formula, crystal, scalar (contains crystal data)\n" " - string, stringArray, integer, integerArray, float floatArray, builtin\n\n" "- Attributes:\n\n" " - On <molecule>: id, title, ref(in CMLReact)\n" " - On <atom>: id, atomId, atomID, elementType, x2, y2, x3, y3, z3, xy2, xyz3,\n" " xFract, yFract, zFract, xyzFract, hydrogenCount, formalCharge, isotope,\n" " isotopeNumber, spinMultiplicity, radical(from Marvin),\n" " atomRefs4 (for atomParity)\n" " - On <bond>: atomRefs2, order, CML1: atomRef, atomRef1, atomRef2\n\n" "Write Options for CML: -x[flags] (e.g. -x1ac)\n" " 1 write CML1 (rather than CML2)\n" " a write array format for atoms and bonds\n" " A write aromatic bonds as such, not Kekule form\n" " h use hydrogenCount for all hydrogens\n" " m write metadata\n" " x omit XML and namespace declarations\n" " c continuous output: no formatting\n" " p write properties\n" " N<prefix> add namespace prefix to elements\n\n" "Read Options, e.g. -a2\n" " 2 read 2D rather than 3D coordinates if both provided\n\n" "In the absence of hydrogenCount and any explicit hydrogen on\n" "an atom, implicit hydrogen is assumed to be present appropriate\n" "to the radical or spinMultiplicity attributes on the atom or\n" "its normal valency if they are not present.\n\n" "The XML formats require the XML text to be well formed but\n" "generally interpret it fairly tolerantly. Unrecognised elements\n" "and attributes are ignored and there are rather few error messages\n" "when any required structures are not found. This laxity allows, for\n" "instance, the reactant and product molecules to be picked out of a CML\n" "React file using CML. Each format has an element which is regarded as\n" "defining the object that OpenBabel will convert. For CML this is\n" "<molecule>. Files can have multiple objects and these can be treated\n" "the same as with other multiple object formats like SMILES and MDL\n" "Molfile. So conversion can start at the nth object using the ``-fn`` option\n" "and finish before the end using the ``-ln`` option. Multiple object XML files\n" "also can be indexed and searched using FastSearch, although this has\n" "not yet been extensively tested.\n\n"; }; virtual const char* SpecificationURL() {return "http://www.xml-cml.org/";} virtual const char* GetMIMEType() { return "chemical/x-cml"; }; virtual unsigned int Flags() { return READXML | ZEROATOMSOK; }; virtual bool WriteChemObject(OBConversion* pConv); virtual bool WriteMolecule(OBBase* pOb, OBConversion* pConv); protected: virtual bool DoElement(const string& name); virtual bool EndElement(const string& name); virtual const char* EndTag(){ return "/molecule>"; }; private: typedef vector< vector< pair<string,string> > > cmlArray; bool TransferArray(cmlArray& arr); bool TransferElement(cmlArray& arr); bool DoAtoms(); bool DoBonds(); bool DoHCounts(); bool DoMolWideData(); bool ParseFormula(string& formula, OBMol* pmol); void ReadNasaThermo(); void MakeAtomIds(OBMol& mol, vector<string>& atomIDs); void WriteFormula(OBMol mol); //passes copy of mol void WriteMetadataList(OBMol& mol); string getTimestr(); void WriteBondStereo(OBBond* pbond, vector<string>& atomIDs); void WriteCrystal(OBMol& mol); void WriteProperties(OBMol& mol, bool& propertyListWritten); void WriteThermo(OBMol& mol, bool& propertyListWritten); string GetMolID();//for error mesaages bool WriteInChI(OBMol& mol); bool WriteScalarProperty(OBMol& mol, const char* title, double value, const char* dictref=NULL, const char* units=NULL, const char* convention=NULL); bool WriteVibrationData(OBMol& mol); bool WriteRotationData(OBMol& mol); private: map<string,int> AtomMap; //key=atom id, value= ob atom index cmlArray AtomArray; cmlArray BondArray; map<int, int> HCounts; vector< pair<string,string> > cmlBondOrAtom; //for cml1 only vector< pair<string,string> > molWideData; bool inBondArray; //for cml1 only bool inFormula; string RawFormula; xmlChar* prefix; string CurrentAtomID; int CrystalScalarsNeeded, PropertyScalarsNeeded, TransformsNeeded; vector<double> CrystalVals; OBUnitCell* pUnitCell; SpaceGroup _SpaceGroup; string SpaceGroupName; string titleonproperty; }; //////////////////////////////////////////////////////////// //Make an instance of the format class CMLFormat theCMLFormat; /* There are 4 CML styles: CML1, CML2, both with and without array forms. All styles are converted into the same internal structure in AtomArray and BondArray which contains pairs of (attribute)name/value pairs for each atom or bond. At the end of molecule this is analysed in DoAtoms() and DoBonds() to construct an OBMol. */ //Callback routines /////////////////////////////////////////////////////// bool CMLFormat::DoElement(const string& name) { //A linear search is good enough for <20 element names; commonest at start. string value; if(name=="atom") { cmlBondOrAtom.clear(); int IsEmpty = xmlTextReaderIsEmptyElement(reader()); TransferElement(AtomArray); if(IsEmpty==1) //have to push here because end atom may not be called AtomArray.push_back(cmlBondOrAtom); } else if(name=="bond") { cmlBondOrAtom.clear(); int IsEmpty = xmlTextReaderIsEmptyElement(reader()); TransferElement(BondArray); if(IsEmpty==1) BondArray.push_back(cmlBondOrAtom); } else if(name=="molecule" || name=="jobstep") //hack for molpro { //Ignore atoms with "ref" attributes if(xmlTextReaderGetAttribute(reader(), BAD_CAST "ref")) return true; _pmol->Clear(); AtomArray.clear(); BondArray.clear(); HCounts.clear(); inBondArray = false; inFormula = false; RawFormula.erase(); molWideData.clear(); CrystalScalarsNeeded=0; CrystalVals.clear(); pUnitCell = NULL; PropertyScalarsNeeded=0; if(++_embedlevel) return true; //ignore if already inside a molecule _pmol->BeginModify(); AtomMap.clear(); const xmlChar* ptitle = xmlTextReaderGetAttribute(reader(), BAD_CAST "title"); if(!ptitle) ptitle = xmlTextReaderGetAttribute(reader(), BAD_CAST "id"); if(!ptitle) ptitle = xmlTextReaderGetAttribute(reader(), BAD_CAST "molID");//Marvin if(ptitle) _pmol->SetTitle((const char*)ptitle); ptitle = xmlTextReaderGetAttribute(reader(), BAD_CAST "spinMultiplicity"); if(ptitle) _pmol->SetTotalSpinMultiplicity(atoi((const char*)ptitle)); // free((void*)ptitle);//libxml2 doc says "The string must be deallocated by the caller." } else if(name=="atomArray") { if(!inFormula) //do nothing when a child of <formula> { inBondArray=false; TransferArray(AtomArray); } } else if(name=="bondArray") { inBondArray=true; TransferArray(BondArray); } else if(name=="atomParity" || name=="bondStereo") { //Save in molWideData: //the content, the atomRefs4 attribute, and (for atomParity only) the centralAtom string atrefs4("atomRefs4"); value = _pxmlConv->GetAttribute(atrefs4.c_str()); pair<string,string> atomrefdata(atrefs4,value); xmlTextReaderRead(reader()); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); if(pvalue) { value = (const char*)pvalue; Trim(value); pair<string,string> nameAndvalue(name,value); molWideData.push_back(nameAndvalue); molWideData.push_back(atomrefdata); stringstream ss; if(name=="atomParity") ss << AtomArray.size()+1; //index of current atom else ss << BondArray.size(); //index of current bond pair<string,string> atdata("centralAtomOrBond",ss.str()); molWideData.push_back(atdata); } } else if(name=="name") { if(_pmol) _pmol->SetTitle(_pxmlConv->GetContent().c_str()); } else if(name=="formula") { if(!xmlTextReaderIsEmptyElement(reader())) inFormula=true; //Only concise form is currently supported const xmlChar* pformula = xmlTextReaderGetAttribute(reader(), BAD_CAST "concise"); if(pformula) { RawFormula = (const char*)pformula; // free((void*)pformula); } } else if(name=="crystal") { CrystalScalarsNeeded = 6; } else if(name=="scalar") { if(CrystalScalarsNeeded) { xmlTextReaderRead(reader()); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); if(pvalue) { CrystalVals.push_back(atof((const char*)pvalue)); if(--CrystalScalarsNeeded==0) { pUnitCell = new OBUnitCell; pUnitCell->SetOrigin(fileformatInput); pUnitCell->SetData(CrystalVals[0],CrystalVals[1],CrystalVals[2], CrystalVals[3],CrystalVals[4],CrystalVals[5]); _pmol->SetData(pUnitCell); } } } else if(PropertyScalarsNeeded) { //Reads OBPairData(like SDF properties). Name is in scalar title or id attribute const xmlChar* pattr = xmlTextReaderGetAttribute(reader(), BAD_CAST "title"); if(!pattr) pattr = xmlTextReaderGetAttribute(reader(), BAD_CAST "id"); string attr; if(pattr) attr = (const char*)pattr; else attr = titleonproperty; // free((void*)pattr);//"The string must be deallocated by the caller." xmlTextReaderRead(reader()); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); if(titleonproperty.find("ZPE")!=string::npos) { double energy; stringstream ss((const char*)pvalue); ss >> energy; //units are kJ/mol const double CALSTOJOULES = 4.1816; _pmol->SetEnergy(energy/CALSTOJOULES); } else { if(pvalue && !attr.empty()) { OBPairData *dp = new OBPairData; dp->SetAttribute(attr); string val((const char*)pvalue); dp->SetValue(Trim(val)); dp->SetOrigin(fileformatInput); _pmol->SetData(dp); } } PropertyScalarsNeeded=0; } } else if(name=="array" && PropertyScalarsNeeded) { //Read vibrational frequencies and rotational constants from properties xmlTextReaderRead(reader()); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); string value; if(pvalue) value = (const char*)pvalue; vector<string> items; tokenize(items,value); if(titleonproperty.find("vibFreqs")!=string::npos) { vector< vector< vector3 > > vLx; vector<double> vFrequencies, vIntensities; for(unsigned i=0;i<items.size();++i) vFrequencies.push_back(atof(items[i].c_str())); OBVibrationData* vd = new OBVibrationData; vd->SetData(vLx, vFrequencies, vIntensities); vd->SetOrigin(fileformatInput); _pmol->SetData(vd); } else if(titleonproperty.find("rotConsts")!=string::npos) { const double WAVENUM_TO_GHZ=30.0; vector<double> rotConsts; for(unsigned i=0;i<items.size();++i) rotConsts.push_back(atof(items[i].c_str()) * WAVENUM_TO_GHZ); OBRotationData* rd = new OBRotationData; rd->SetData(OBRotationData::UNKNOWN, rotConsts, 1);//rotor type and symmetry number unknown rd->SetOrigin(fileformatInput); _pmol->SetData(rd); } PropertyScalarsNeeded = 0; } else if(name=="symmetry") { const xmlChar* pname = xmlTextReaderGetAttribute(reader(), BAD_CAST "spaceGroup"); if (pname) { SpaceGroupName = (const char*)pname; // free((void*)pname); } } else if(name=="transform3") { xmlTextReaderRead(reader()); const xmlChar* ptransform = xmlTextReaderConstValue(reader()); if (ptransform) { string t = (const char*)ptransform; _SpaceGroup.AddTransform(t); // free((void*)ptransform); } } else if(name=="property") { //***pattr need to be deleted*** const char* pattr = (const char*)xmlTextReaderGetAttribute(reader(), BAD_CAST "dictRef"); if(pattr && !strcmp(pattr,"Thermo_OldNasa")) ReadNasaThermo(); else { if(!pattr) // no dictRef; look for title on scalar pattr = (const char*)xmlTextReaderGetAttribute(reader(), BAD_CAST "title"); if(pattr) titleonproperty = pattr; else titleonproperty.clear(); PropertyScalarsNeeded = 1; } } // CML1 elements else if(name=="string" || name=="float" || name=="integer" || name=="coordinate3"|| name=="coordinate2") { string name = _pxmlConv->GetAttribute("builtin"); xmlTextReaderRead(reader()); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); if(!pvalue) return false; string value = (const char*)pvalue; Trim(value); pair<string,string> nameAndvalue(name,value); cmlBondOrAtom.push_back(nameAndvalue); } else if(name=="stringArray" || name=="floatArray" || name=="integerArray") { string name = _pxmlConv->GetAttribute("builtin"); // cmlArray& arr = (name=="atomRef1" || name=="atomRef2" || name=="order") // ? BondArray : AtomArray; cmlArray& arr = inBondArray ? BondArray : AtomArray; xmlTextReaderRead(reader()); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); if(!pvalue) return false; string value = (const char*)pvalue; vector<string> items; tokenize(items,value); if(arr.size()<items.size()) arr.resize(items.size()); unsigned int i; for(i=0;i<items.size();++i) { pair<string,string> nameAndvalue(name,items[i]); arr[i].push_back(nameAndvalue); } } //The end element event would not be called for <element/>, so call it explicitly. if(xmlTextReaderIsEmptyElement(reader())==1) return EndElement(name); return true; } ////////////////////////////////////////////////////// bool CMLFormat::EndElement(const string& name) { if(name=="atom") { //ok for cml1 but is not called at end of <atom.../> AtomArray.push_back(cmlBondOrAtom); } else if(name=="bond") { BondArray.push_back(cmlBondOrAtom); } else if(name=="formula") inFormula=false; else if(name=="molecule" || name=="jobstep") //hack for molpro { if(!DoAtoms() || !DoBonds() || !DoHCounts() || !DoMolWideData()) return false; if (_pmol->GetDimension()==0) StereoFrom0D(_pmol); // Remove any spurious stereos (due to symmetry) //Use formula only if nothing else provided if(_pmol->NumAtoms()==0 && !RawFormula.empty()) if(!ParseFormula(RawFormula, _pmol)) obErrorLog.ThrowError(_pmol->GetTitle(),"Error in formula", obError); //ensure unbonded atoms are seen as such if(_pmol->NumBonds()==0) FOR_ATOMS_OF_MOL(a, *_pmol) a->ForceNoH(); _pmol->AssignSpinMultiplicity(); _pmol->EndModify(); return (--_embedlevel>=0); //false to stop parsing if no further embedded mols // return false;//means stop parsing } else if(name=="symmetry") { if(!SpaceGroupName.empty()) { const SpaceGroup *group = SpaceGroup::GetSpaceGroup(SpaceGroupName); if ((!group || !(_SpaceGroup == *group)) && _SpaceGroup.IsValid()) group = SpaceGroup::Find(&_SpaceGroup); if (group) pUnitCell->SetSpaceGroup(group); else pUnitCell->SetSpaceGroup(SpaceGroupName); } } return true; } ///////////////////////////////////////////////////////// ///Interprets atoms from AtomArray and writes then to an OBMol bool CMLFormat::DoAtoms() { OBAtomClassData aclass; int dim=0; //dimension of molecule bool use2d = _pxmlConv->IsOption("2", OBConversion::INOPTIONS); int nAtoms=_pmol->NumAtoms();//was 0 cmlArray::iterator AtomIter; for(AtomIter=AtomArray.begin();AtomIter!=AtomArray.end();++AtomIter) { // OBAtom obatom; OBAtom* pAtom = _pmol->NewAtom(); nAtoms++; int nhvy = nAtoms; double x=0,y=0,z=0; bool using3=false, using2=false, usingFract=false; vector<pair<string,string> >::iterator AttributeIter; for(AttributeIter=AtomIter->begin();AttributeIter!=AtomIter->end();++AttributeIter) { string& attrname = AttributeIter->first; string& value = AttributeIter->second; if(attrname=="id" || attrname=="atomId" || attrname=="atomID")//which one correct? { Trim(value); if(AtomMap.count(value)>0) obErrorLog.ThrowError(GetMolID(),"The atom id " + value + " is not unique", obWarning); AtomMap[value] = nhvy;//nAtoms; //If the id begins with "aa", "ab", etc, the number that follows is taken as an atom class if(value[0]=='a' && value[1]>='a' && value[1]<='z') aclass.Add(nAtoms, atoi(value.c_str()+2)); continue; } else if(attrname=="elementType") { int atno, iso=0; atno=etab.GetAtomicNum(value.c_str(),iso); pAtom->SetAtomicNum(atno); if(iso) pAtom->SetIsotope(iso); continue; } //If more than one set of coordinates provided, //prefer 3D over 2D over 3Dfractional, //but if use2d is true, prefer 2D over 3D else if((attrname=="x3" || attrname=="y3" || attrname=="z3" || attrname=="xyz3") && !use2d) { using3 = true; usingFract = false; } else if((attrname=="x2" || attrname=="y2" || attrname=="z2" || attrname=="xy2") && !using3) { using2 = true; usingFract = false; } else if(pUnitCell && !using3 && !using2 && (attrname=="xFract" || attrname=="yFract" || attrname=="zFract")) usingFract=true; if ((using3 && attrname=="x3") || (using2 && attrname=="x2") || (usingFract && attrname=="xFract")) { x=strtod(value.c_str(),NULL); } else if ((using3 && attrname=="y3") || (using2 && attrname=="y2") || (usingFract && attrname=="yFract")) { y=strtod(value.c_str(),NULL); } else if ((using3 && attrname=="z3") || (using2 && attrname=="z2") || (usingFract && attrname=="zFract")) { z=strtod(value.c_str(),NULL); } else if(using2 && attrname=="xy2") { vector<string> vals; tokenize(vals,value); if(vals.size()==2) { x=strtod(vals[0].c_str(),NULL); y=strtod(vals[1].c_str(),NULL); } } else if(using3 && attrname=="xyz3") { vector<string> vals; tokenize(vals,value); if(vals.size()==3) { x=strtod(vals[0].c_str(),NULL); y=strtod(vals[1].c_str(),NULL); z=strtod(vals[2].c_str(),NULL); } } if(attrname=="hydrogenCount") { //Actually adding H atoms to the structure is deferred until the explicit //structure is complete, because hydrogenCount may include explicit H, bug#3014855 HCounts[nAtoms] = atoi(value.c_str()); /* int nhvy = nAtoms; int i; for(i=0;i<atoi(value.c_str());++i) { OBAtom* hatom = _pmol->NewAtom(); hatom->SetAtomicNum(1); hatom->SetType("H"); _pmol->AddBond(nhvy,_pmol->NumAtoms(),1); ++nAtoms; } */ } else if(attrname=="formalCharge") pAtom->SetFormalCharge(atoi(value.c_str())); else if(attrname=="label") { OBPairData *label = new OBPairData(); label->SetAttribute("label"); label->SetValue(value.c_str()); pAtom->SetData(label); } else if(attrname=="color") { OBPairData *color = new OBPairData(); color->SetAttribute("color"); color->SetValue(value.c_str()); pAtom->SetData(color); } else if(attrname=="radius") { OBPairData *radius = new OBPairData(); radius->SetAttribute("radius"); radius->SetValue(value.c_str()); pAtom->SetData(radius); } else if(attrname=="spinMultiplicity") pAtom->SetSpinMultiplicity(atoi(value.c_str())); /*else if(attrname=="atomRefs4")//from atomParity element (but there is no such thing!) { vector<string> ids; tokenize(ids, value); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); int parity = 0; if (pvalue) parity = atoi((const char*)pvalue); if (parity != 0) { // Should be +1 or -1 TetSym ts; ts.atomrefs = ids; ts.parity = parity; tetsyms.push_back(ts); } }*/ else if(attrname=="radical") //Marvin extension { int spin=0; if(value=="monovalent") spin=2; else if(value=="divalent") spin=3; else if(value=="divalent3") spin=3; else if(value=="divalent1") spin=1; pAtom->SetSpinMultiplicity(spin); } else if(attrname=="isotopeNumber" || attrname=="isotope") pAtom->SetIsotope(atoi(value.c_str())); } //each attribute //Save atom coordinates if(using3 || usingFract) dim=3; else if(using2) { dim=2; z=0.0; } else dim=0; if(usingFract) { //Coordinates are fractional vector3 v; v.Set(x, y, z); v = pUnitCell->FractionalToCartesian(v); pAtom->SetVector(v); } else pAtom->SetVector(x, y, z); }//each atom if(aclass.size()>0) _pmol->SetData((new OBAtomClassData(aclass))); _pmol->SetDimension(dim); return true; } ///////////////////////////////////////////////////////////////////// ///Interprets bonds from BondArray and writes then to an OBMol bool CMLFormat::DoBonds() { vector<pair<string,string> >::iterator AttributeIter; cmlArray::iterator BondIter; bool HaveWarned = false; for(BondIter=BondArray.begin();BondIter!=BondArray.end();++BondIter) { int indx1=0,indx2=0, ord=0; string bondstereo, BondStereoRefs; string colour; string label; bool PossibleBond = false; for(AttributeIter=BondIter->begin();AttributeIter!=BondIter->end();++AttributeIter) { string attrname = AttributeIter->first; string value = AttributeIter->second; Trim(value); if(attrname.compare(0, 7, "atomRef")==0) //generic { PossibleBond = true; string::size_type pos = value.find(' '); if(!HaveWarned && (attrname=="atomRefs1" || (attrname=="atomRefs2" && pos==string::npos))) { obErrorLog.ThrowError(GetMolID(), attrname + " is not legal CML in this context, " "but OpenBabel will attempt to understand what was meant.", obWarning); HaveWarned = true; } if(indx1==0) { if(pos!=string::npos) { indx1 = AtomMap[value.substr(0,pos)]; string temp =value.substr(pos+1); indx2 = AtomMap[Trim(temp)]; //C4239 indx2 = AtomMap[Trim(value.substr(pos+1))]; } else indx1 = AtomMap[value]; } else { if(indx2==0) indx2 = AtomMap[value]; else indx1=-1; //forces error } } else if(attrname=="order") { const char bo = value[0]; if(bo=='S') ord=1; else if(bo=='D') ord=2; else if(bo=='T') ord=3; else if(bo=='A') ord=5; else { char* endptr; ord = strtol(value.c_str(), &endptr, 10); } } else if(attrname=="color") colour=value[0]; else if(attrname=="label") label = value; } if(PossibleBond) { if(indx1<=0 || indx2<=0) { obErrorLog.ThrowError(GetMolID(),"Incorrect bond attributes", obError); return false; } if(ord==0) //Bonds are single if order is not specified { ord=1; //But unspecied bond order means cannot assign spinmultiplicity _pmol->SetIsPatternStructure(); } _pmol->AddBond(indx1,indx2,ord,0); if(!colour.empty()) { OBPairData *dp = new OBPairData(); dp->SetAttribute("color"); dp->SetValue(colour.c_str()); _pmol->GetBond(_pmol->NumBonds()-1)->SetData(dp); } if(!label.empty()) { OBPairData *dp = new OBPairData(); dp->SetAttribute("label"); dp->SetValue(label.c_str()); _pmol->GetBond(_pmol->NumBonds()-1)->SetData(dp); } } } return true; } ///////////////////////////////////////////////////////////////// bool CMLFormat::DoHCounts() { //Add extra H atoms so that each atom has the value of its attribute hydrogenCount map<int,int>::iterator iter; for(iter=HCounts.begin();iter!=HCounts.end();++iter) { int idx = iter->first; int explH = _pmol->GetAtom(idx)->ExplicitHydrogenCount(false); //excludes H isotopes if(explH > iter->second) { map<string,int>::iterator it; for(it=AtomMap.begin();it!=AtomMap.end();++it) if(it->second == idx) break; stringstream ss; ss << "In atom " << it->first << " the number of explicit hydrogens exceeds the hydrogenCount attribute."; obErrorLog.ThrowError(__FUNCTION__, ss.str(), obError); return false; } if(iter->second == 0) //ensure no Hs are ever added _pmol->GetAtom(idx)->ForceNoH(); else { //add extra hydrogens for(unsigned i=0;i<iter->second - explH;++i) { OBAtom* hatom = _pmol->NewAtom(); hatom->SetAtomicNum(1); hatom->SetType("H"); _pmol->AddBond(idx, _pmol->NumAtoms(), 1); } } } return true; } bool CMLFormat::DoMolWideData() { //Handle atomParity and bondStereo vector<pair<string,string> >::iterator AttributeIter; for(AttributeIter=molWideData.begin();AttributeIter!=molWideData.end();++AttributeIter) { string name = AttributeIter->first; string value = AttributeIter->second; if(name=="atomParity" || name=="bondStereo") { vector<unsigned int> AtomRefIdx; string nextname = (++AttributeIter)->first; string atrefsvalue = AttributeIter->second; if(nextname=="atomRefs4" && !atrefsvalue.empty()) { vector<string> ids; tokenize(ids, atrefsvalue); int i; for(i=0;i<4;++i) AtomRefIdx.push_back(AtomMap[ids[i]]); } nextname = (++AttributeIter)->first; if(!(nextname=="centralAtomOrBond")) return false; int Idx = atoi(AttributeIter->second.c_str()); if(name=="atomParity") { OBAtom* patom = _pmol->GetAtom(Idx); if(!patom) return false; OBStereo::Ref center = patom->GetId(); OBStereo::Ref from = _pmol->GetAtom(AtomRefIdx[0])->GetId(); if (from == center) from = OBStereo::ImplicitRef; OBStereo::Refs refs; vector<unsigned int>::const_iterator idx_cit=AtomRefIdx.begin(); ++idx_cit; for (; idx_cit!=AtomRefIdx.end(); ++idx_cit) { OBStereo::Ref id = _pmol->GetAtom(*idx_cit)->GetId(); if (id == center) id = OBStereo::ImplicitRef; refs.push_back(id); } int parity = atoi(value.c_str()); OBStereo::Winding winding = OBStereo::Clockwise; // parity > 0 if (parity < 0) winding = OBStereo::AntiClockwise; else if (parity == 0) // What to do with parity of 0? return false; OBTetrahedralStereo::Config cfg = OBTetrahedralStereo::Config( center, from, refs, winding, OBStereo::ViewFrom); OBTetrahedralStereo *th = new OBTetrahedralStereo(_pmol); th->SetConfig(cfg); _pmol->SetData(th); } else //bondStereo { OBBond* pbond1=NULL; OBBond* pbond2=NULL; if(atrefsvalue.empty()) // ToDo { OBBond* pDBond = _pmol->GetBond(Idx); //With no atomRefs4, the specification is either W, H, if(value=="W") { pDBond->SetWedge(); } else if(value=="H") { pDBond->SetHash(); } // ... or ordinary cis/trans if(value!="C" && value!="T") continue; //which is valid only with one substituent on each C OBAtom* pAt1 = pDBond->GetBeginAtom(); OBAtom* pAt2 = pDBond->GetEndAtom(); FOR_NBORS_OF_ATOM(a1,pAt1) { if(!a1->IsHydrogen() && &*a1!=pAt2) break; pbond1 = _pmol->GetBond(pAt1->GetIdx(),a1->GetIdx()); } FOR_NBORS_OF_ATOM(a2,pAt2) { if(!a2->IsHydrogen() && &*a2!=pAt1) break; pbond2 = _pmol->GetBond(pAt2->GetIdx(),a2->GetIdx()); } } else { pbond1 = _pmol->GetBond(AtomRefIdx[0],AtomRefIdx[1]); pbond2 = _pmol->GetBond(AtomRefIdx[2],AtomRefIdx[3]); } if(!pbond1 || !pbond2) continue; // Create the list of 4 atomrefs OBStereo::Ref begin, end; begin = _pmol->GetAtom(AtomRefIdx[1])->GetId(); end = _pmol->GetAtom(AtomRefIdx[2])->GetId(); OBStereo::Refs refs(4); refs[0] = _pmol->GetAtom(AtomRefIdx[0])->GetId(); refs[1] = OBStereo::ImplicitRef; FOR_NBORS_OF_ATOM(nbr, _pmol->GetAtomById(begin)) if (nbr->GetId()!=end && nbr->GetId()!=refs[0]) { refs[1] = nbr->GetId(); break; } OBStereo::Ref tmpref = _pmol->GetAtom(AtomRefIdx[3])->GetId(); OBStereo::Ref finalref = OBStereo::ImplicitRef; FOR_NBORS_OF_ATOM(nbr, _pmol->GetAtomById(end)) if (nbr->GetId()!=begin && nbr->GetId()!=tmpref) { finalref = nbr->GetId(); break; } if (value=="C") { // for Cis (tmpref and refs[0] on same side) refs[2] = finalref; refs[3] = tmpref; } else { // for Trans refs[2] = tmpref; refs[3] = finalref; } // Create the new stereo object OBCisTransStereo::Config ct_cfg = OBCisTransStereo::Config( begin, end, refs, OBStereo::ShapeU); OBCisTransStereo *ct = new OBCisTransStereo(_pmol); ct->SetConfig(ct_cfg); _pmol->SetData(ct); } } } //Clear here to aid embedded molecules AtomArray.clear(); BondArray.clear(); molWideData.clear(); return true; } ////////////////////////////////////////////////////////// bool CMLFormat::TransferArray(cmlArray& arr) { //Reads attributes of the current node, e.g. atomID="a1 a2 a3" //parses each of them into their separate items, e.g. a1, a2, a3 //and pushes them as a pairs in each of the members of the array // e.g. ("atomID", "a1") in AtomArray[0], ("atomID", "a2") in AtomArray[1] if(xmlTextReaderHasAttributes(reader())) { int ret = xmlTextReaderMoveToFirstAttribute(reader()); while(ret==1) { const xmlChar* pname = xmlTextReaderConstName(reader()); string name((const char*)pname); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); string value; if(pvalue) value = (const char*)pvalue; vector<string> items; tokenize(items,value); if(arr.size()<items.size()) arr.resize(items.size()); unsigned int i; for(i=0;i<items.size();++i) { pair<string,string> nameAndvalue(name,items[i]); arr[i].push_back(nameAndvalue); } ret = xmlTextReaderMoveToNextAttribute(reader()); } } return true; } bool CMLFormat::TransferElement(cmlArray& arr) { //Reads the attributes of the current node, e.g. <atom id="a1" elementType="C"/> //pushes each of them as a pairs into each of the members of the array // e.g. ("id", "a1") and (elementType", "C") will be put into AtomArray[n] //where n is the number of times this routine has been called before. if(xmlTextReaderHasAttributes(reader())) { int ret = xmlTextReaderMoveToFirstAttribute(reader()); while(ret==1) { const xmlChar* pname = xmlTextReaderConstName(reader()); string name((const char*)pname); const xmlChar* pvalue = xmlTextReaderConstValue(reader()); string value; if(pvalue) { value = (const char*)pvalue; Trim(value); } pair<string,string> nameAndvalue(name,value); cmlBondOrAtom.push_back(nameAndvalue); ret = xmlTextReaderMoveToNextAttribute(reader()); } } return true; } bool CMLFormat::ParseFormula(string& formula, OBMol* pmol) { vector<string> items; tokenize(items, formula); vector<string>::iterator iSymbol, iNumber; for(iSymbol=items.begin();iSymbol!=items.end();++iSymbol) { iNumber = iSymbol+1; if(iNumber==items.end()) return false; int n=atoi(iNumber->c_str()); int atno, iso=0; atno=etab.GetAtomicNum(iSymbol++->c_str(),iso); if(atno<=0 || n<=0) return false; int i; for(i=0;i<n;++i) { OBAtom* pAtom = pmol->NewAtom(); pAtom->ForceNoH(); pAtom->SetAtomicNum(atno); if(iso) pAtom->SetIsotope(iso); } } return true; } void CMLFormat::ReadNasaThermo() { //Do all NasaThermo data here OBNasaThermoData* pTD = new OBNasaThermoData; pTD->SetOrigin(fileformatInput); _pmol->SetData(pTD); for(;;) { xmlTextReaderRead(reader()); int typ = xmlTextReaderNodeType(reader()); if(typ==XML_READER_TYPE_SIGNIFICANT_WHITESPACE) continue; const char* pname = (const char*)xmlTextReaderConstLocalName(reader()); if(typ==XML_READER_TYPE_END_ELEMENT) { if(!strcmp(pname,"property"))//end of element return; else continue; } const char * pattr = (const char*)xmlTextReaderGetAttribute(reader(), BAD_CAST "dictRef"); xmlTextReaderRead(reader()); const char* pvalue = (const char*)xmlTextReaderConstValue(reader()); if(pattr && pvalue) { if(!strcmp(pattr,"NasaLowT")) pTD->SetLoT(atof(pvalue)); else if(!strcmp(pattr,"NasaHighT")) pTD->SetHiT(atof(pvalue)); else if(!strcmp(pattr,"NasaMidT")) pTD->SetMidT(atof(pvalue)); else if(!strcmp(pattr,"NasaCoeffs")) { vector<string> vals; tokenize(vals, pvalue); for(int i=0;i<14;++i) pTD->SetCoeff(i, atof(vals[i].c_str())); } } } } void CMLFormat::WriteMetadataList(OBMol& mol) { static const xmlChar C_METADATALIST[] = "metadataList"; static const xmlChar C_METADATA[] = "metadata"; static const xmlChar C_TITLE[] = "title"; static const xmlChar C_NAME[] = "name"; static const xmlChar C_CONTENT[] = "content"; xmlTextWriterStartElement(writer(), C_METADATALIST); if(mol.HasData(OBGenericDataType::CommentData)) { OBCommentData *cd = (OBCommentData*)mol.GetData(OBGenericDataType::CommentData); xmlTextWriterStartElement(writer(), C_METADATA); xmlTextWriterWriteAttribute(writer(), C_NAME, BAD_CAST "dc:description"); xmlTextWriterWriteAttribute(writer(), C_CONTENT, BAD_CAST cd->GetData().c_str()); xmlTextWriterEndElement(writer()); } xmlTextWriterStartElement(writer(), C_METADATA); xmlTextWriterWriteAttribute(writer(), C_NAME, BAD_CAST "dc:source"); xmlTextWriterWriteAttribute(writer(), C_CONTENT, BAD_CAST "unknown"); xmlTextWriterEndElement(writer()); xmlTextWriterStartElement(writer(), C_METADATA); xmlTextWriterWriteAttribute(writer(), C_NAME, BAD_CAST "dc:creator"); string version("OpenBabel version "); version += BABEL_VERSION; xmlTextWriterWriteAttribute(writer(), C_CONTENT, BAD_CAST version.c_str()); xmlTextWriterEndElement(writer()); xmlTextWriterStartElement(writer(), C_METADATA); xmlTextWriterWriteAttribute(writer(), C_NAME, BAD_CAST "dc:contributor"); xmlTextWriterWriteAttribute(writer(), C_CONTENT, BAD_CAST "unknown"); xmlTextWriterEndElement(writer()); xmlTextWriterStartElement(writer(), C_METADATA); xmlTextWriterWriteAttribute(writer(), C_NAME, BAD_CAST "dc:date"); xmlTextWriterWriteAttribute(writer(), C_CONTENT, BAD_CAST getTimestr().c_str()); xmlTextWriterEndElement(writer()); /* xmlTextWriterStartElement(writer(), C_METADATA); xmlTextWriterWriteAttribute(writer(), C_NAME, BAD_CAST "cmlm:structure"); xmlTextWriterWriteAttribute(writer(), C_CONTENT, BAD_CAST "yes"); xmlTextWriterEndElement(writer()); */ xmlTextWriterEndElement(writer()); } string CMLFormat::getTimestr() { const int TIME_STR_SIZE = 64; time_t akttime; /* Systemtime */ char timestr[TIME_STR_SIZE + 1] = ""; /* Timestring */ size_t time_res; /* Result of strftime */ /* ---- Get the system-time ---- */ akttime = time((time_t *) NULL); time_res = strftime(timestr, TIME_STR_SIZE, "%a %b %d %H:%M:%S %Z %Y", localtime((time_t *) &akttime) ); return string(timestr); } ///////////////////////////////////////////////////////////// bool CMLFormat::WriteMolecule(OBBase* pOb, OBConversion* pConv) { static const xmlChar C_MOLECULE[] = "molecule"; static const xmlChar C_CML[] = "cml"; static const xmlChar C_ATOMARRAY[] = "atomArray"; static const xmlChar C_BONDARRAY[] = "bondArray"; static const xmlChar C_ATOM[] = "atom"; static const xmlChar C_BOND[] = "bond"; static const xmlChar C_ID[] = "id"; // static const xmlChar C_TITLE[] = "title"; static const xmlChar C_NAME[] = "name"; static const xmlChar C_ATOMPARITY[] = "atomParity"; static const xmlChar C_BONDSTEREO[] = "bondStereo"; static const xmlChar C_X2[] = "x2"; static const xmlChar C_Y2[] = "y2"; static const xmlChar C_X3[] = "x3"; static const xmlChar C_Y3[] = "y3"; static const xmlChar C_Z3[] = "z3"; static const xmlChar C_XFRACT[] = "xFract"; static const xmlChar C_YFRACT[] = "yFract"; static const xmlChar C_ZFRACT[] = "zFract"; static const xmlChar C_ATOMID[] = "atomID"; static const xmlChar C_ELEMENTTYPE[] = "elementType"; static const xmlChar C_ISOTOPE[] = "isotope"; static const xmlChar C_SPINMULTIPLICITY[] = "spinMultiplicity"; static const xmlChar C_HYDROGENCOUNT[] = "hydrogenCount"; static const xmlChar C_FORMALCHARGE[] = "formalCharge"; static const xmlChar C_ATOMREFS2[] = "atomRefs2"; static const xmlChar C_ATOMREF1[] = "atomRef1"; static const xmlChar C_ATOMREF2[] = "atomRef2"; static const xmlChar C_ORDER[] = "order"; static const xmlChar C_ATOMREFS4[] = "atomRefs4"; static const xmlChar C_DESCRIPTION[] = "description"; /* defined in other functions static const xmlChar C_FORMULA[] = "formula"; static const xmlChar C_CONCISE[] = "concise"; static const xmlChar C_PROPERTYLIST[] = "propertyList"; static const xmlChar C_PROPERTY[] = "property"; static const xmlChar C_SCALAR[] = "scalar"; */ static const xmlChar C_LABEL[] = "label"; static const xmlChar C_COLOR[] = "color"; static const xmlChar C_RADIUS[] = "radius"; //CML1 static const xmlChar C_STRING[] = "string"; static const xmlChar C_INTEGER[] = "integer"; static const xmlChar C_FLOAT[] = "float"; static const xmlChar C_BUILTIN[] = "builtin"; static const xmlChar C_STRINGARRAY[] = "stringArray"; static const xmlChar C_INTEGERARRAY[] = "integerArray"; static const xmlChar C_FLOATARRAY[] = "floatArray"; /* used as ordinary text atomRef */ const xmlChar* C_X3orFRACT = C_X3; //Non-fraction coordinates are the default const xmlChar* C_Y3orFRACT = C_Y3; const xmlChar* C_Z3orFRACT = C_Z3; _pxmlConv = XMLConversion::GetDerived(pConv,false); if(!_pxmlConv) return false; bool cml1 = _pxmlConv->IsOption("1"); bool arrayform = _pxmlConv->IsOption("a"); bool WriteAromaticBonds = _pxmlConv->IsOption("A"); prefix = BAD_CAST _pxmlConv->IsOption("N"); xmlChar* uri=NULL; //Write the header on the first object (incl OBReaction) //unless x option set or if has been called from elsewhere (e.g. CMLReact) if(!_pxmlConv->IsOption("MolsNotStandalone") && _pxmlConv->GetOutputIndex()==1) { if(!_pxmlConv->IsOption("x")) { xmlTextWriterStartDocument(writer(), NULL, NULL, NULL); if(cml1) uri = BAD_CAST CML1NamespaceURI(); else uri=BAD_CAST NamespaceURI();// not the old CML2NamespaceURI(); } //If more than one molecule to be output, write <cml> at start and </cml> at end. if(!_pxmlConv->IsLast()) { xmlTextWriterStartElementNS(writer(), prefix, C_CML, uri); uri=NULL; } } OBMol* pmol = dynamic_cast<OBMol*>(pOb); if(pmol==NULL) { #ifdef HAVE_SHARED_POINTER OBReaction* pReact = dynamic_cast<OBReaction*>(pOb); if(!pReact) return false; //Use CMLReact to convert OBReaction object OBFormat* pCMLRFormat = pConv->FindFormat("cmlr"); if(!pCMLRFormat) { obErrorLog.ThrowError(__FUNCTION__, "Cannot find CMLReact format", obError); return false; } //Disable list option and supress topping and tailing in CMLReactFormat. _pxmlConv->AddOption("l", OBConversion::OUTOPTIONS); _pxmlConv->AddOption("ReactionsNotStandalone", OBConversion::OUTOPTIONS); bool ret = pCMLRFormat->WriteMolecule(pOb,_pxmlConv); _pxmlConv->RemoveOption("ReactionsNotStandalone", OBConversion::OUTOPTIONS); return ret; #else return false; #endif } OBMol &mol = *pmol; int numbonds = mol.NumBonds(); //Capture this before deleting Hs bool UseHydrogenCount=false; if(_pxmlConv->IsOption("h")) { pmol->DeleteHydrogens(); UseHydrogenCount=true; } bool UseFormulaWithNoBonds=false; //before 2.3.1 was true; int dim = mol.GetDimension(); xmlTextWriterStartElementNS(writer(), prefix, C_MOLECULE, uri); const char* id = mol.GetTitle(); if(*id) { string name(id); //If name is a filename with a path, remove path and extension string::size_type pos; pos = name.find_last_of("/\\:"); if(pos!=string::npos) { name.erase(0, pos+1); pos = name.rfind('.'); if(pos!=string::npos) name.erase(pos); } if(!isalpha(name[0])) //since ids have to start with a letter, add "id" to those that don't... name = "id" + name; xmlTextWriterWriteAttribute(writer(), C_ID, BAD_CAST name.c_str()); if(!isalpha(name[0])) //...and write <name> orig title </name> { xmlTextWriterStartElementNS(writer(), prefix, C_NAME, NULL); xmlTextWriterWriteFormatString(writer(),"%s", id); xmlTextWriterEndElement(writer());//name } } int TotalCharge = mol.GetTotalCharge(); if(TotalCharge!=0) xmlTextWriterWriteFormatAttribute(writer(), C_FORMALCHARGE, "%d", TotalCharge); int TotalSpin = mol.GetTotalSpinMultiplicity(); if(TotalSpin!=1) xmlTextWriterWriteFormatAttribute(writer(), C_SPINMULTIPLICITY, "%d", TotalSpin); if(_pxmlConv->IsOption("m") && _pxmlConv->GetOutputIndex()==1) //only on first molecule WriteMetadataList(mol); pUnitCell = NULL; if (!cml1 && mol.HasData(OBGenericDataType::UnitCell)) { WriteCrystal(mol);//Output will be in crystallographic form UseFormulaWithNoBonds = false; } WriteInChI(mol); // Create map (tetStereos) from atom Ids to tetstereos std::map<unsigned int, OBTetrahedralStereo::Config > tetStereos; std::map<unsigned int, OBTetrahedralStereo::Config >::const_iterator tetStereo_cit; if (mol.GetDimension()!=3) { std::vector<OBGenericData*> vdata = mol.GetAllData(OBGenericDataType::StereoData); for (std::vector<OBGenericData*>::iterator data = vdata.begin(); data != vdata.end(); ++data) if (((OBStereoBase*)*data)->GetType() == OBStereo::Tetrahedral) { OBTetrahedralStereo *ts = dynamic_cast<OBTetrahedralStereo*>(*data); // Always get the clockwise version (it's the default anyway) as this has // a positive signed volume (i.e. CML atomParity of 1) OBTetrahedralStereo::Config cfg = ts->GetConfig(OBStereo::Clockwise); if(cfg.specified) tetStereos[cfg.center] = cfg; } } vector<string> atomIds; if(mol.NumAtoms()>0) { //if molecule has no bonds and atoms doesn't have coordinates, just output formula if(numbonds==0 && UseFormulaWithNoBonds && !mol.Has2D()) WriteFormula(mol); else { xmlTextWriterStartElementNS(writer(), prefix, C_ATOMARRAY, NULL); MakeAtomIds(mol, atomIds);//Pre-construct to take into account atom class data stringstream id, eltyp, iso, chg, spn, hct, x, y, z; bool anyChg=false, anySpin=false, anyIsotope=false; double X, Y, Z; //atom coordinates OBAtom *patom; vector<OBAtom*>::iterator i; for (patom = mol.BeginAtom(i);patom;patom = mol.NextAtom(i)) { string el(etab.GetSymbol(patom->GetAtomicNum())); if(el=="Xx") el="R"; int charge = patom->GetFormalCharge(); int spin = patom->GetSpinMultiplicity(); int isotope =patom->GetIsotope(); int hcount=patom->ImplicitHydrogenCount() + patom->ExplicitHydrogenCount(); //includes H isotopes X = patom->GetX(); Y = patom->GetY(); Z = patom->GetZ(); if(pUnitCell) { //Convert to fractional coordinates vector3 v = patom->GetVector(); v = pUnitCell->CartesianToFractional(v); X = v.x(); Y = v.y(); Z = v.z(); C_X3orFRACT = C_XFRACT; C_Y3orFRACT = C_YFRACT; C_Z3orFRACT = C_ZFRACT; dim=3; //should already be, but make sure } if(arrayform) { if(charge) anyChg = true; if(spin) anySpin = true; if(isotope) anyIsotope = true; id << " " << atomIds[patom->GetIdx()]; eltyp << " " << el; iso << " " << isotope; chg << " " << charge; spn << " " << spin; hct << " " << hcount; x << " " << X; y << " " << Y; z << " " << Z; } else { //Non-array form xmlTextWriterStartElementNS(writer(), prefix, C_ATOM, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_ID,"%s", atomIds[patom->GetIdx()].c_str()); if(!cml1) { xmlTextWriterWriteFormatAttribute(writer(), C_ELEMENTTYPE,"%s", el.c_str()); if(isotope) xmlTextWriterWriteFormatAttribute(writer(), C_ISOTOPE,"%d", isotope); if(charge) xmlTextWriterWriteFormatAttribute(writer(), C_FORMALCHARGE,"%d", charge); if(spin) xmlTextWriterWriteFormatAttribute(writer(), C_SPINMULTIPLICITY,"%d", spin); if(UseHydrogenCount && hcount) xmlTextWriterWriteFormatAttribute(writer(), C_HYDROGENCOUNT,"%d", hcount); if(patom->HasData("label")) xmlTextWriterWriteFormatAttribute(writer(), C_LABEL,"%s", patom->GetData("label")->GetValue().c_str()); if(patom->HasData("color")) xmlTextWriterWriteFormatAttribute(writer(), C_COLOR,"%s", patom->GetData("color")->GetValue().c_str()); if(patom->HasData("radius")) xmlTextWriterWriteFormatAttribute(writer(), C_RADIUS,"%s", patom->GetData("radius")->GetValue().c_str()); if(dim==2) { xmlTextWriterWriteFormatAttribute(writer(), C_X2,"%f", X); xmlTextWriterWriteFormatAttribute(writer(), C_Y2,"%f", Y); } if(dim==3) { xmlTextWriterWriteFormatAttribute(writer(), C_X3orFRACT,"%f", X); xmlTextWriterWriteFormatAttribute(writer(), C_Y3orFRACT,"%f", Y); xmlTextWriterWriteFormatAttribute(writer(), C_Z3orFRACT,"%f", Z); } if( (tetStereo_cit=tetStereos.find(patom->GetId())) != tetStereos.end() ) { OBTetrahedralStereo::Config cfg = tetStereo_cit->second; OBStereo::Refs refs = cfg.refs; vector<string> atomrefs; // According to http://cml.sourceforge.net/schema/cmlCore/HTMLDOCS/cmlCore.pdf, // "if there are only 3 ligands, the current atom should be included // in the 4 atomRefs.". if (cfg.from == OBStereo::ImplicitRef) // e.g. for [S@@](Cl)(Br)I atomrefs.push_back(atomIds[mol.GetAtomById(cfg.center)->GetIdx()]); // Add the central atom again else atomrefs.push_back(atomIds[mol.GetAtomById(cfg.from)->GetIdx()]); for (OBStereo::RefIter ref = refs.begin(); ref!=refs.end(); ++ref) { if ( (OBStereo::Ref)*ref == OBStereo::ImplicitRef) // e.g. for Cl[S@@](Br)I atomrefs.push_back(atomIds[mol.GetAtomById(cfg.center)->GetIdx()]); // Add the central atom again else atomrefs.push_back(atomIds[mol.GetAtomById(*ref)->GetIdx()]); } xmlTextWriterStartElementNS(writer(), prefix, C_ATOMPARITY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_ATOMREFS4, "%s %s %s %s", atomrefs[0].c_str(), atomrefs[1].c_str(), atomrefs[2].c_str(), atomrefs[3].c_str()); // Set the atomParity - this is always 1 as the atomRefs are arranged // to make this so xmlTextWriterWriteFormatString(writer(), "%d", 1); xmlTextWriterEndElement(writer());//atomParity } } else { //CML1 xmlTextWriterStartElementNS(writer(), prefix, C_STRING, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "elementType"); xmlTextWriterWriteFormatString(writer(),"%s", el.c_str()); xmlTextWriterEndElement(writer()); if(charge) { xmlTextWriterStartElementNS(writer(), prefix, C_INTEGER, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "formalCharge"); xmlTextWriterWriteFormatString(writer(),"%d", charge); xmlTextWriterEndElement(writer()); } if(UseHydrogenCount && hcount) { xmlTextWriterStartElementNS(writer(), prefix, C_INTEGER, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "hydrogenCount"); xmlTextWriterWriteFormatString(writer(),"%d", hcount); xmlTextWriterEndElement(writer()); } if(dim==2 || dim==3) { xmlTextWriterStartElementNS(writer(), prefix, C_FLOAT, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s%d", "x",dim); xmlTextWriterWriteFormatString(writer(),"%f", X); xmlTextWriterEndElement(writer()); xmlTextWriterStartElementNS(writer(), prefix, C_FLOAT, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s%d", "y",dim); xmlTextWriterWriteFormatString(writer(),"%f", Y); xmlTextWriterEndElement(writer()); } if(dim==3) { xmlTextWriterStartElementNS(writer(), prefix, C_FLOAT, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s%d", "z",dim); xmlTextWriterWriteFormatString(writer(),"%f", Z); xmlTextWriterEndElement(writer()); } //Stereochemistry currently not written for CML1 } xmlTextWriterEndElement(writer());//atom } } if(arrayform) { if(!cml1) { xmlTextWriterWriteFormatAttribute(writer(), C_ATOMID,"%s", id.str().c_str()); xmlTextWriterWriteFormatAttribute(writer(), C_ELEMENTTYPE,"%s", eltyp.str().c_str()); if(anyIsotope) xmlTextWriterWriteFormatAttribute(writer(), C_ISOTOPE,"%s", iso.str().c_str()); if(anyChg) xmlTextWriterWriteFormatAttribute(writer(), C_FORMALCHARGE,"%s", chg.str().c_str()); if(anySpin) xmlTextWriterWriteFormatAttribute(writer(), C_SPINMULTIPLICITY,"%s", spn.str().c_str()); if(UseHydrogenCount) xmlTextWriterWriteFormatAttribute(writer(), C_HYDROGENCOUNT,"%s", hct.str().c_str()); if(dim==2) { xmlTextWriterWriteFormatAttribute(writer(), C_X2,"%s", x.str().c_str()); xmlTextWriterWriteFormatAttribute(writer(), C_Y2,"%s", y.str().c_str()); } if(dim==3) { xmlTextWriterWriteFormatAttribute(writer(), C_X3orFRACT,"%s", x.str().c_str()); xmlTextWriterWriteFormatAttribute(writer(), C_Y3orFRACT,"%s", y.str().c_str()); xmlTextWriterWriteFormatAttribute(writer(), C_Z3orFRACT,"%s", z.str().c_str()); } } else { //CML1 xmlTextWriterStartElementNS(writer(), prefix, C_STRINGARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "atomID"); xmlTextWriterWriteFormatString(writer(),"%s", id.str().c_str()); xmlTextWriterEndElement(writer()); xmlTextWriterStartElementNS(writer(), prefix, C_STRINGARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "elementType"); xmlTextWriterWriteFormatString(writer(),"%s", eltyp.str().c_str()); xmlTextWriterEndElement(writer()); if(anyChg) { xmlTextWriterStartElementNS(writer(), prefix, C_INTEGERARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "formalCharge"); xmlTextWriterWriteFormatString(writer(),"%s", chg.str().c_str()); xmlTextWriterEndElement(writer()); } if(UseHydrogenCount) { xmlTextWriterStartElementNS(writer(), prefix, C_INTEGERARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "hydrogenCount"); xmlTextWriterWriteFormatString(writer(),"%s", hct.str().c_str()); xmlTextWriterEndElement(writer()); } if(dim==2 || dim==3) { xmlTextWriterStartElementNS(writer(), prefix, C_FLOATARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s%d", "x",dim); xmlTextWriterWriteFormatString(writer(),"%s", x.str().c_str()); xmlTextWriterEndElement(writer()); xmlTextWriterStartElementNS(writer(), prefix, C_FLOATARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s%d", "y",dim); xmlTextWriterWriteFormatString(writer(),"%s", y.str().c_str()); xmlTextWriterEndElement(writer()); } if(dim==3) { xmlTextWriterStartElementNS(writer(), prefix, C_FLOATARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s%d", "z",dim); xmlTextWriterWriteFormatString(writer(),"%s", z.str().c_str()); xmlTextWriterEndElement(writer()); } } } xmlTextWriterEndElement(writer());//atomArray } } // Create map (ctStereos) from bond Idxs to cistrans stereos std::map<unsigned int, OBCisTransStereo* > ctStereos; std::map<unsigned int, OBCisTransStereo* >::const_iterator ctStereo_cit; if (mol.GetDimension()!=3) { std::vector<OBGenericData*> vdata = mol.GetAllData(OBGenericDataType::StereoData); for (std::vector<OBGenericData*>::iterator data = vdata.begin(); data != vdata.end(); ++data) if (((OBStereoBase*)*data)->GetType() == OBStereo::CisTrans) { OBCisTransStereo *ct = dynamic_cast<OBCisTransStereo*>(*data); if(ct->GetConfig().specified) { unsigned int dblbond = mol.GetBond(mol.GetAtomById(ct->GetConfig().begin), mol.GetAtomById(ct->GetConfig().end ))->GetIdx(); ctStereos[dblbond] = ct; } } } if(mol.NumBonds()>0) { xmlTextWriterStartElementNS(writer(), prefix, C_BONDARRAY, NULL); stringstream ord; string ref1, ref2; OBBond *pbond; vector<OBBond*>::iterator ib; for (pbond = mol.BeginBond(ib);pbond;pbond = mol.NextBond(ib)) { int bo = pbond->GetBO(); if(!arrayform) { if(bo==5 || (WriteAromaticBonds && pbond->IsAromatic())) //aromatic ord << 'A'; else ord << bo; ref1 = atomIds[pbond->GetBeginAtomIdx()]; ref2 = atomIds[pbond->GetEndAtomIdx()]; xmlTextWriterStartElementNS(writer(), prefix, C_BOND, NULL); // xmlTextWriterWriteFormatAttribute(writer(), C_ID,"b%d", pbond->GetIdx()); remove bond id if(!cml1) { xmlTextWriterWriteFormatAttribute(writer(), C_ATOMREFS2,"%s %s", ref1.c_str(), ref2.c_str()); xmlTextWriterWriteFormatAttribute(writer(), C_ORDER,"%s", ord.str().c_str()); if(pbond->HasData("color")) xmlTextWriterWriteFormatAttribute(writer(), C_COLOR,"%s", pbond->GetData("color")->GetValue().c_str()); if(pbond->HasData("label")) xmlTextWriterWriteFormatAttribute(writer(), C_LABEL,"%s", pbond->GetData("label")->GetValue().c_str()); if( (ctStereo_cit=ctStereos.find(pbond->GetIdx())) != ctStereos.end() ) { OBCisTransStereo *ct = ctStereo_cit->second; OBCisTransStereo::Config ct_cfg = ct->GetConfig(); // Find a non-implicit ref at either end of the dbl bond OBStereo::Ref beginref, endref; beginref = (ct_cfg.refs[0] == OBStereo::ImplicitRef) ? ct_cfg.refs[1] : ct_cfg.refs[0]; endref = (ct_cfg.refs[2] == OBStereo::ImplicitRef) ? ct_cfg.refs[3] : ct_cfg.refs[2]; char cis_or_trans = ct->IsCis(beginref, endref) ? 'C' : 'T'; // Prepare the "atomrefs4" vector<string> atomrefs(4); atomrefs[0] = atomIds[mol.GetAtomById(beginref)->GetIdx()]; atomrefs[1] = atomIds[mol.GetAtomById(ct_cfg.begin)->GetIdx()]; atomrefs[2] = atomIds[mol.GetAtomById(ct_cfg.end)->GetIdx()]; atomrefs[3] = atomIds[mol.GetAtomById(endref)->GetIdx()]; // Create the XML tags xmlTextWriterStartElementNS(writer(), prefix, C_BONDSTEREO, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_ATOMREFS4, "%s %s %s %s", atomrefs[0].c_str(), atomrefs[1].c_str(), atomrefs[2].c_str(), atomrefs[3].c_str()); xmlTextWriterWriteFormatString(writer(),"%c", cis_or_trans); xmlTextWriterEndElement(writer());//bondStereo } } else { //CML1 xmlTextWriterStartElementNS(writer(), prefix, C_STRING, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "atomRef"); xmlTextWriterWriteFormatString(writer(),"%s", ref1.c_str()); xmlTextWriterEndElement(writer()); xmlTextWriterStartElementNS(writer(), prefix, C_STRING, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "atomRef"); xmlTextWriterWriteFormatString(writer(),"%s", ref2.c_str()); xmlTextWriterEndElement(writer()); xmlTextWriterStartElementNS(writer(), prefix, C_STRING, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "order"); xmlTextWriterWriteFormatString(writer(),"%d", bo); xmlTextWriterEndElement(writer()); } xmlTextWriterEndElement(writer());//bond ord.str(""); //clear (For array form it accumulates.) } else { if(bo==5 || (WriteAromaticBonds && pbond->IsAromatic())) //aromatic ord << " " << 'A'; else ord << " " << bo; ref1 += ' ' + atomIds[pbond->GetBeginAtomIdx()]; ref2 += ' ' + atomIds[pbond->GetEndAtomIdx()]; } } if(arrayform) { if(!cml1) { xmlTextWriterWriteFormatAttribute(writer(), C_ATOMREF1, "%s", ref1.c_str()); xmlTextWriterWriteFormatAttribute(writer(), C_ATOMREF2, "%s", ref2.c_str()); xmlTextWriterWriteFormatAttribute(writer(), C_ORDER, "%s", ord.str().c_str()); } else { //CML1 xmlTextWriterStartElementNS(writer(), prefix, C_STRINGARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "atomRef"); xmlTextWriterWriteFormatString(writer(),"%s", ref1.c_str()); xmlTextWriterEndElement(writer()); xmlTextWriterStartElementNS(writer(), prefix, C_STRINGARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "atomRef"); xmlTextWriterWriteFormatString(writer(),"%s", ref2.c_str()); xmlTextWriterEndElement(writer()); xmlTextWriterStartElementNS(writer(), prefix, C_STRINGARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_BUILTIN,"%s", "order"); xmlTextWriterWriteFormatString(writer(),"%s", ord.str().c_str()); xmlTextWriterEndElement(writer()); } } xmlTextWriterEndElement(writer());//bondArray //When array form, write bondStereo here if(arrayform) { for (pbond = mol.BeginBond(ib);pbond;pbond = mol.NextBond(ib)) { if(pbond->GetBO()==2 || pbond->IsWedge() || pbond->IsHash()) WriteBondStereo(pbond, atomIds); } } } bool propertyListWritten=false; if(mol.HasData(ThermoData)) WriteThermo(mol, propertyListWritten); if(_pxmlConv->IsOption("p")) WriteProperties(mol, propertyListWritten); if(propertyListWritten) xmlTextWriterEndElement(writer());//propertList xmlTextWriterEndElement(writer());//molecule //Note that nothing will be written unless the next block is executed //IsLast() MUST return true for the last molecule. if(!_pxmlConv->IsOption("MolsNotStandalone") && _pxmlConv->IsLast()) { xmlTextWriterEndDocument(writer()); OutputToStream(); } return true; } ///Constructs a unique id for each atom. void CMLFormat::MakeAtomIds(OBMol& mol, vector<string>& atomIDs) { /* If there is no atom class data for the atom, the id is a followed by the atom index. If there is atom class data then it is aa followed by the atom class. If a subsequent atom has the same atom class, its id is ab followed by the atom class, and so on. */ stringstream ss; map<int,char> acmap; //key=atom calss; value=last letter used as second in id OBAtomClassData* pac = static_cast<OBAtomClassData*>(mol.GetData("Atom Class")); atomIDs.push_back("Error"); //atom idex stats at 1. atomIDs[0] is not used for (unsigned int idx=1; idx<=mol.NumAtoms(); ++idx) { ss.str(""); ss << 'a'; if(pac && pac->HasClass(idx)) { int ac = pac->GetClass(idx); char ch2='a'; //default 2nd char if(acmap.count(ac)>0) ch2 = acmap[ac]+1; if(ch2>'z') obErrorLog.ThrowError(_pmol->GetTitle(),"CML: too many atoms with same atom class." , obError); ss << ch2 << ac; acmap[ac] = ch2; } else ss << idx; atomIDs.push_back(ss.str()); } } void CMLFormat::WriteFormula(OBMol mol) { //mol is a copy static const xmlChar C_FORMULA[] = "formula"; static const xmlChar C_CONCISE[] = "concise"; if(mol.NumAtoms()==1) mol.AddHydrogens(false,false); xmlTextWriterStartElementNS(writer(), prefix, C_FORMULA, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_CONCISE,"%s", mol.GetSpacedFormula().c_str()); xmlTextWriterEndElement(writer());//formula } void CMLFormat::WriteBondStereo(OBBond* pbond, vector<string>& atomIDs) { static const xmlChar C_ATOMREFS4[] = "atomRefs4"; static const xmlChar C_BONDSTEREO[] = "bondStereo"; char ch=0; if(pbond->IsWedge()) ch='W'; else if(pbond->IsHash()) ch='H'; if(ch) //this line here because element may not be written with double bond xmlTextWriterStartElementNS(writer(), prefix, C_BONDSTEREO, NULL); else { //double bond stereo int ud1=0, ud2=0; int idx1=0, idx2=0; OBAtom* patomA = pbond->GetBeginAtom(); FOR_BONDS_OF_ATOM(b1,patomA) { if(b1->IsUp() || b1->IsDown() ) { idx1=(b1->GetNbrAtom(patomA))->GetIdx(); ud1 = b1->IsDown() ? -1 : 1; // Conjugated double bonds have to be treated differently, see comments // in OBMol2Smi::GetCisTransBondSymbol(). Reverse symbol for other than first double bond. if((b1->GetNbrAtom(patomA))->HasDoubleBond()) ud1 = -ud1; break; } } OBAtom* patomB = pbond->GetEndAtom(); FOR_BONDS_OF_ATOM(b2,patomB) { if(b2->IsUp() || b2->IsDown() ) { idx2=(b2->GetNbrAtom(patomB))->GetIdx(); ud2 = b2->IsDown() ? -1 : 1; break; } } if(!ud1 || !ud2) return; xmlTextWriterStartElementNS(writer(), prefix, C_BONDSTEREO, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_ATOMREFS4, "%s %s %s %s", // "a%d a%d a%d a%d", idx1, patomA->GetIdx(), patomB->GetIdx(), idx2); atomIDs[idx1].c_str(), atomIDs[patomA->GetIdx()].c_str(), atomIDs[patomB->GetIdx()].c_str(), atomIDs[idx2].c_str()); ch = (ud1==ud2) ? 'C' : 'T'; } xmlTextWriterWriteFormatString(writer(),"%c", ch); xmlTextWriterEndElement(writer());//bondStereo } void CMLFormat::WriteCrystal(OBMol& mol) { static const xmlChar C_CRYSTAL[] = "crystal"; static const xmlChar C_SCALAR[] = "scalar"; // static const xmlChar C_Z[] = "z"; static const xmlChar C_TITLE[] = "title"; static const xmlChar C_UNITS[] = "units"; static const xmlChar C_SYMMETRY[] = "symmetry"; static const xmlChar C_SPACEGROUP[] = "spaceGroup"; static const xmlChar C_TRANSFORM3[] = "transform3"; pUnitCell = (OBUnitCell*)mol.GetData(OBGenericDataType::UnitCell); xmlTextWriterStartElementNS(writer(), prefix, C_CRYSTAL, NULL); // xmlTextWriterWriteFormatAttribute(writer(), C_z,"%d", number of molecules per cell); xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s", "a"); xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s", "units:angstrom"); xmlTextWriterWriteFormatString(writer(),"%f", pUnitCell->GetA()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s", "b"); xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s", "units:angstrom"); xmlTextWriterWriteFormatString(writer(),"%f", pUnitCell->GetB()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s", "c"); xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s", "units:angstrom"); xmlTextWriterWriteFormatString(writer(),"%f", pUnitCell->GetC()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s", "alpha"); xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s", "units:degree"); xmlTextWriterWriteFormatString(writer(),"%f", pUnitCell->GetAlpha()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s", "beta"); xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s", "units:degree"); xmlTextWriterWriteFormatString(writer(),"%f", pUnitCell->GetBeta()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s", "gamma"); xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s", "units:degree"); xmlTextWriterWriteFormatString(writer(),"%f", pUnitCell->GetGamma()); xmlTextWriterEndElement(writer());//scalar const SpaceGroup *group = pUnitCell->GetSpaceGroup(); string s; if (group) { xmlTextWriterStartElementNS(writer(), prefix, C_SYMMETRY, NULL); xmlTextWriterWriteAttribute (writer(), C_SPACEGROUP, (const xmlChar*)group->GetHallName().c_str()); transform3dIterator ti; const transform3d *t = group->BeginTransform(ti); string s; while(t) { s = t->DescribeAsValues() + " 0 0 0 1"; xmlTextWriterWriteElement(writer(), C_TRANSFORM3, (const xmlChar*)s.c_str()); t = group->NextTransform(ti); } xmlTextWriterEndElement(writer());//symmetry } else { //s = pUnitCell.GetSpaceGroupName(); s = pUnitCell->GetSpaceGroupName(); if (s.length()) { xmlTextWriterStartElementNS(writer(), prefix, C_SYMMETRY, NULL); xmlTextWriterWriteAttribute (writer(), C_SPACEGROUP, (const xmlChar*)s.c_str()); xmlTextWriterEndElement(writer());//symmetry } } xmlTextWriterEndElement(writer());//crystal } void CMLFormat::WriteProperties(OBMol& mol, bool& propertyListWritten) { static const xmlChar C_DICTREF[] = "dictRef"; static const xmlChar C_PROPERTYLIST[] = "propertyList"; static const xmlChar C_PROPERTY[] = "property"; static const xmlChar C_SCALAR[] = "scalar"; static const xmlChar C_TITLE[] = "title"; vector<OBGenericData*>::iterator k; vector<OBGenericData*> vdata = mol.GetData(); for (k = vdata.begin();k != vdata.end();++k) { if ((*k)->GetDataType() == OBGenericDataType::PairData && (*k)->GetOrigin() != local //internal OBPairData is not written && (*k)->GetAttribute()!= "InChI" //InChI is output in <identifier> && (*k)->GetAttribute()!= "PartialCharges")//annotation not needed since partial charges are not output in this format { if(!propertyListWritten) { xmlTextWriterStartElementNS(writer(), prefix, C_PROPERTYLIST, NULL); propertyListWritten=true; } xmlTextWriterStartElementNS(writer(), prefix, C_PROPERTY, NULL); //Title is now on <property>. If the attribute name has a namespace, use dictRef instead. string att((*k)->GetAttribute()); xmlTextWriterWriteFormatAttribute(writer(), (att.find(':')==string::npos) ? C_TITLE : C_DICTREF, "%s",att.c_str()); xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); //Title used to be on <scalar>... //xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s",(*k)->GetAttribute().c_str()); xmlTextWriterWriteFormatString(writer(),"%s", (static_cast<OBPairData*>(*k))->GetValue().c_str()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterEndElement(writer());//property } } static const double CALSTOJOULES = 4.184; //Energy is output when it is not zero //This is the molecular energy, probably originally in Hartrees, // stored in OB as kcal/mol, but output here in kJ/mol if(fabs(mol.GetEnergy()) > 1e-3) WriteScalarProperty(mol, "Energy", mol.GetEnergy() * CALSTOJOULES, "me:ZPE", "kJ/mol", "computational"); //spinMultiplicity is written only when it is not 1 int smult = mol.GetTotalSpinMultiplicity(); if(smult!=1) WriteScalarProperty(mol, "SpinMultiplicity", smult, "me:spinMultiplicity"); if(mol.HasData(OBGenericDataType::VibrationData)) WriteVibrationData(mol); if(mol.HasData(OBGenericDataType::RotationData)) WriteRotationData(mol); } void CMLFormat::WriteThermo(OBMol& mol, bool& propertyListWritten) { static const xmlChar C_PROPERTYLIST[] = "propertyList"; static const xmlChar C_PROPERTY[] = "property"; static const xmlChar C_SCALAR[] = "scalar"; static const xmlChar C_ARRAY[] = "array"; static const xmlChar C_DICTREF[] = "dictRef"; static const xmlChar C_SIZE[] = "size"; OBNasaThermoData* pThermoData = static_cast<OBNasaThermoData*>(mol.GetData(ThermoData)); if(!propertyListWritten) { xmlTextWriterStartElementNS(writer(), prefix, C_PROPERTYLIST, NULL); propertyListWritten=true; } xmlTextWriterStartElementNS(writer(), prefix, C_PROPERTY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","Thermo_OldNasa"); xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","NasaLowT"); xmlTextWriterWriteFormatString(writer(),"%.1f", pThermoData->GetLoT()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","NasaHighT"); xmlTextWriterWriteFormatString(writer(),"%.1f", pThermoData->GetHiT()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","NasaMidT"); xmlTextWriterWriteFormatString(writer(),"%.1f", pThermoData->GetMidT()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","Phase"); xmlTextWriterWriteFormatString(writer(),"%c", pThermoData->GetPhase()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterStartElementNS(writer(), prefix, C_ARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","NasaCoeffs"); xmlTextWriterWriteFormatAttribute(writer(), C_SIZE,"%d",14); for(int i=0;i<14;++i) xmlTextWriterWriteFormatString(writer()," %e", pThermoData->GetCoeff(i)); xmlTextWriterEndElement(writer());//array xmlTextWriterEndElement(writer());//property } std::string getSeparator() { #ifdef WIN32 return "\\"; #else return "/"; #endif } ///Returns molecule title or molecule number if there is no title together with the file name string CMLFormat::GetMolID() { stringstream molID; if(strlen(_pmol->GetTitle())==0) molID << "Mol #" << _pxmlConv->GetOutputIndex()+1; else molID << _pmol->GetTitle(); string fn(_pxmlConv->GetInFilename()); //Get file name: remove path string::size_type pos = fn.rfind(getSeparator()); if(pos!=string::npos) fn.erase(0,pos+1); molID << " (in " << fn << ')'; return molID.str(); } bool CMLFormat::WriteInChI(OBMol& mol) { //If OBPair data has an entry with attribute "inchi" it is not //output in the property list but as a separate element in the form: //<identifier convention="iupac:inchi" value="InChI=1/CH4/h1H4"/> static const xmlChar C_IDENTIFIER[] = "identifier"; static const xmlChar C_CONVENTION[] = "convention"; static const xmlChar C_VALUE[] = "value"; OBPairData* pData = dynamic_cast<OBPairData*>(mol.GetData("InChI")); if(pData) { xmlTextWriterStartElementNS(writer(), prefix, C_IDENTIFIER, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_CONVENTION,"%s","iupac:inchi"); xmlTextWriterWriteFormatAttribute(writer(), C_VALUE,"%s", pData->GetValue().c_str()); xmlTextWriterEndElement(writer());//identifier return true; } return false; //not written } bool CMLFormat::WriteVibrationData(OBMol& mol) { static const xmlChar C_PROPERTY[] = "property"; static const xmlChar C_SCALAR[] = "scalar"; static const xmlChar C_ARRAY[] = "array"; static const xmlChar C_DICTREF[] = "dictRef"; static const xmlChar C_UNITS[] = "units"; static const xmlChar C_TITLE[] = "title"; OBVibrationData* vd = (OBVibrationData*)mol.GetData(OBGenericDataType::VibrationData); xmlTextWriterStartElementNS(writer(), prefix, C_PROPERTY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s","Vibrational Frequencies"); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","me:vibFreqs"); xmlTextWriterStartElementNS(writer(), prefix, C_ARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s","cm-1"); double imaginaryFrequency = 0.0; //A negative frequency is output separately as an imaginary frequency (for transition states) for (unsigned int i=0; i<vd->GetNumberOfFrequencies(); ++i) { double freq = vd->GetFrequencies()[i]; if(freq>0.0) xmlTextWriterWriteFormatString(writer(),"%.2lf ", freq); else imaginaryFrequency = -freq; } xmlTextWriterEndElement(writer());//array xmlTextWriterEndElement(writer());//property if(imaginaryFrequency>0.0) WriteScalarProperty(mol, "ImaginaryFrequency", imaginaryFrequency, "me:imFreqs", "cm-1"); return true; } bool CMLFormat::WriteRotationData(OBMol& mol) { static const xmlChar C_PROPERTY[] = "property"; static const xmlChar C_SCALAR[] = "scalar"; static const xmlChar C_ARRAY[] = "array"; static const xmlChar C_DICTREF[] = "dictRef"; static const xmlChar C_UNITS[] = "units"; static const xmlChar C_TITLE[] = "title"; OBRotationData* rd = (OBRotationData*)mol.GetData(OBGenericDataType::RotationData); xmlTextWriterStartElementNS(writer(), prefix, C_PROPERTY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s","Rotational Constants"); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","me:rotConsts"); xmlTextWriterStartElementNS(writer(), prefix, C_ARRAY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s","cm-1"); const double WAVENUM_TO_GHZ=30.0; for (unsigned int i=0; i<rd->GetRotConsts().size(); ++i) if(rd->GetRotConsts()[i]!=0.0) xmlTextWriterWriteFormatString(writer(),"%.3lf ", rd->GetRotConsts()[i]/WAVENUM_TO_GHZ); xmlTextWriterEndElement(writer());//array xmlTextWriterEndElement(writer());//property xmlTextWriterStartElementNS(writer(), prefix, C_PROPERTY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s","Symmetry Number"); xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s","me:symmetryNumber"); xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); xmlTextWriterWriteFormatString(writer(),"%d ", rd->GetSymmetryNumber()); xmlTextWriterEndElement(writer());//scalar xmlTextWriterEndElement(writer());//property return true; } bool CMLFormat::WriteScalarProperty(OBMol& mol, const char* title, double value, const char* dictref, const char* units, const char* convention) { static const xmlChar C_PROPERTY[] = "property"; static const xmlChar C_SCALAR[] = "scalar"; static const xmlChar C_DICTREF[] = "dictRef"; static const xmlChar C_UNITS[] = "units"; static const xmlChar C_TITLE[] = "title"; static const xmlChar C_CONVENTION[] = "convention"; static const xmlChar C_ZPEADDED[] = "zeroPointVibEnergyAdded"; xmlTextWriterStartElementNS(writer(), prefix, C_PROPERTY, NULL); xmlTextWriterWriteFormatAttribute(writer(), C_TITLE,"%s",title); if(dictref) xmlTextWriterWriteFormatAttribute(writer(), C_DICTREF,"%s",dictref); xmlTextWriterStartElementNS(writer(), prefix, C_SCALAR, NULL); if(units) xmlTextWriterWriteFormatAttribute(writer(), C_UNITS,"%s",units); if(convention) { xmlTextWriterWriteFormatAttribute(writer(), C_CONVENTION,"%s",convention); if(strcmp(convention, "computational")==0) xmlTextWriterWriteFormatAttribute(writer(), C_ZPEADDED,"%s","false"); } xmlTextWriterWriteFormatString(writer(),"%.2lf ", value); xmlTextWriterEndElement(writer());//scalar xmlTextWriterEndElement(writer());//property return true; } bool CMLFormat::WriteChemObject(OBConversion* pConv) { int OIndex = pConv->GetOutputIndex(); OBBase* pOb = pConv->GetChemObject(); if(dynamic_cast<OBMol*> (pOb)) { //With an OBMol object, do the same as if this function wasn't defined, //i.e.access the functionality in OBMoleculeFormat //restore output index which is (unhelpfully) incremented by GetChemObject pConv->SetOutputIndex(OIndex); return XMLMoleculeFormat::WriteChemObject(pConv); } //With OBReaction object, handle directly in CMLFormat::WriteMolecule bool ret = WriteMolecule(pOb,pConv); delete pOb; return ret; } }//namespace
39.742632
129
0.553823
sxhexe
7de9e2dfb07f68c7edf63741cba4d4dcb53ce302
1,018
cpp
C++
inference-engine/src/inference_engine/builders/ie_output_layer_layer.cpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
1
2021-07-30T17:03:50.000Z
2021-07-30T17:03:50.000Z
inference-engine/src/inference_engine/builders/ie_output_layer_layer.cpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
null
null
null
inference-engine/src/inference_engine/builders/ie_output_layer_layer.cpp
fujunwei/dldt
09497b7724de4be92629f7799b8538b483d809a2
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <builders/ie_output_layer.hpp> #include <string> using namespace InferenceEngine; Builder::OutputLayer::OutputLayer(const std::string& name): LayerDecorator("Output", name) { getLayer()->getInputPorts().resize(1); } Builder::OutputLayer::OutputLayer(const Layer::Ptr& layer): LayerDecorator(layer) { checkType("Output"); } Builder::OutputLayer::OutputLayer(const Layer::CPtr& layer): LayerDecorator(layer) { checkType("Output"); } Builder::OutputLayer& Builder::OutputLayer::setName(const std::string& name) { getLayer()->setName(name); return *this; } const Port& Builder::OutputLayer::getPort() const { return getLayer()->getInputPorts()[0]; } Builder::OutputLayer& Builder::OutputLayer::setPort(const Port &port) { getLayer()->getInputPorts()[0] = port; return *this; } REG_VALIDATOR_FOR(Output, [] (const InferenceEngine::Builder::Layer::CPtr& input_layer, bool partial) {});
26.789474
106
0.717092
fujunwei
8fbb8e224adec7c19b35abc8842255960b940af2
18,000
cpp
C++
src_main/materialsystem/shaderapidx9/d3d_async.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
25
2018-02-28T15:04:42.000Z
2021-08-16T03:49:00.000Z
src_main/materialsystem/shaderapidx9/d3d_async.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
1
2019-09-20T11:06:03.000Z
2019-09-20T11:06:03.000Z
src_main/materialsystem/shaderapidx9/d3d_async.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
9
2019-07-31T11:58:20.000Z
2021-08-31T11:18:15.000Z
// Copyright © 1996-2018, Valve Corporation, All rights reserved. // // Purpose: Methods for muti-core dx9 threading #include "d3d_async.h" #include <cstdlib> #include "ShaderAPIDX8_Global.h" #include "UtlDict.h" #include "UtlStringMap.h" #include "UtlVector.h" #include "base/include/windows/windows_light.h" #include "datacache/idatacache.h" #include "ishadersystem.h" #include "locald3dtypes.h" #include "materialsystem/imaterialsystem.h" #include "materialsystem/imaterialsystemhardwareconfig.h" #include "materialsystem/ishader.h" #include "materialsystem/shader_vcs_version.h" #include "recording.h" #include "shaderapidx8.h" #include "tier0/include/fasttimer.h" #include "tier0/include/vprof.h" #include "tier1/convar.h" #include "tier1/utlbuffer.h" #include "tier1/utlsymbol.h" #include "utllinkedlist.h" #include "tier0/include/memdbgon.h" template <class T, int QSIZE> class FixedWorkQueue { T Data[QSIZE]; char pad0[256]; volatile int n_added; int write_index; char pad1[256]; // make sure these don't share cache lines volatile int n_removed; int read_index; public: FixedWorkQueue() { read_index = write_index = 0; n_added = n_removed = 0; } int IsEmpty() { return (n_added == n_removed); } int IsFull() { return (n_added - n_removed) >= QSIZE; } T GetWorkUnit() { if (IsEmpty()) return 0; return Data[read_index]; } void MarkUnitDone() { n_removed++; read_index = (read_index + 1) % QSIZE; } void AddWorkUnit(T unit) { while (IsFull()) Sleep(0); Data[write_index] = unit; n_added++; write_index = (write_index + 1) % QSIZE; } }; #define N_PUSH_BUFFERS 500 static volatile PushBuffer *PushBuffers[N_PUSH_BUFFERS]; FixedWorkQueue<PushBuffer *, N_PUSH_BUFFERS> PBQueue; void __cdecl OurThreadInit(void *ourthis) { ((Direct3DDevice9Wrapper *)ourthis)->RunThread(); } void Direct3DDevice9Wrapper::RunThread() { SetThreadAffinityMask(GetCurrentThread(), 2); for (;;) { PushBuffer *Pbuf = PBQueue.GetWorkUnit(); if (!Pbuf) { ; // Sleep(0); } else { ExecutePushBuffer(Pbuf); PBQueue.MarkUnitDone(); Pbuf->m_State = PUSHBUFFER_AVAILABLE; } } } #define MAXIMUM_NUMBER_OF_BUFFERS_LOCKED_AT_ONCE 16 struct RememberedPointer { void *m_pKey; void *m_pRememberedPtr; } RememberedPointerHistory[MAXIMUM_NUMBER_OF_BUFFERS_LOCKED_AT_ONCE]; void Direct3DDevice9Wrapper::SetASyncMode(bool onoff) { if (onoff) { if (!async_thread_handle_) { // allocate push buffers if we need to if (PushBuffers[0] == NULL) { for (int i = 0; i < N_PUSH_BUFFERS; i++) PushBuffers[i] = new PushBuffer; } // create thread and init communications memset(RememberedPointerHistory, 0, sizeof(RememberedPointerHistory)); SetThreadAffinityMask(GetCurrentThread(), 1); async_thread_handle_ = _beginthread(OurThreadInit, 128 * 1024, this); } } else { Synchronize(); } } PushBuffer *Direct3DDevice9Wrapper::FindFreePushBuffer( PushBufferState newstate) { for (;;) { for (int i = 0; i < N_PUSH_BUFFERS; i++) { if (PushBuffers[i]->m_State == PUSHBUFFER_AVAILABLE) { PushBuffers[i]->m_State = newstate; return (PushBuffer *)PushBuffers[i]; } } // hmm, out of push buffers. better sleep and try again later SubmitPushBufferAndGetANewOne(); Sleep(0); } } void Direct3DDevice9Wrapper::GetPushBuffer() { current_push_buffer_ = FindFreePushBuffer(PUSHBUFFER_BEING_FILLED); output_ptr_ = current_push_buffer_->m_BufferData; push_buffer_free_slots_ = PUSHBUFFER_NELEMS - 1; // leave room for end marker } void Direct3DDevice9Wrapper::SubmitPushBufferAndGetANewOne() { // submit the current push buffer if (current_push_buffer_) { if (output_ptr_ == current_push_buffer_ ->m_BufferData) // haven't done anyting, don't bother return; *(output_ptr_) = PBCMD_END; // mark end current_push_buffer_->m_State = PUSHBUFFER_SUBMITTED; // here, enqueue for task PBQueue.AddWorkUnit(current_push_buffer_); } GetPushBuffer(); } void Direct3DDevice9Wrapper::SubmitIfNotBusy() { if (PBQueue.IsEmpty()) SubmitPushBufferAndGetANewOne(); } void Direct3DDevice9Wrapper::Synchronize() { if (ASyncMode()) { SubmitPushBufferAndGetANewOne(); // here, wait for queue to become empty while (!PBQueue.IsEmpty()) { // Sleep(1); } } } void Direct3DDevice9Wrapper::AsynchronousLock(IDirect3DIndexBuffer9 *ib, size_t offset, size_t size, void **ptr, DWORD flags, LockedBufferContext *lb) { if (size <= sizeof(PushBuffers[0]->m_BufferData)) { // can use one of our pushbuffers for this lb->m_pPushBuffer = FindFreePushBuffer(PUSHBUFFER_BEING_USED_FOR_LOCKEDDATA); *(ptr) = lb->m_pPushBuffer->m_BufferData; Assert(*ptr); lb->m_pMallocedMemory = NULL; } else // out of buffer space or size too big { lb->m_pPushBuffer = NULL; lb->m_pMallocedMemory = new uint8_t[size]; *(ptr) = lb->m_pMallocedMemory; } // now, push lock commands AllocatePushBufferSpace(1 + N_DWORDS_IN_PTR + 3); *(output_ptr_++) = PBCMD_ASYNC_LOCK_IB; *((LPDIRECT3DINDEXBUFFER *)output_ptr_) = ib; output_ptr_ += N_DWORDS_IN_PTR; *(output_ptr_++) = offset; *(output_ptr_++) = size; *(output_ptr_++) = flags; } void Direct3DDevice9Wrapper::AsynchronousLock(IDirect3DVertexBuffer9 *vb, size_t offset, size_t size, void **ptr, DWORD flags, LockedBufferContext *lb) { // we have commands in flight. Need to use temporary memory for this lock. // if the size needed is < the amount of space in a push buffer, we can use // a push buffer for the buffer. Otherwise, we're going to malloc one. if (size <= sizeof(PushBuffers[0]->m_BufferData)) { // can use one of our pushbuffers for this lb->m_pPushBuffer = FindFreePushBuffer(PUSHBUFFER_BEING_USED_FOR_LOCKEDDATA); *(ptr) = lb->m_pPushBuffer->m_BufferData; Assert(*ptr); lb->m_pMallocedMemory = NULL; } else // out of buffer space or size too big { lb->m_pPushBuffer = NULL; lb->m_pMallocedMemory = new uint8_t[size]; *(ptr) = lb->m_pMallocedMemory; } // now, push lock commands AllocatePushBufferSpace(1 + N_DWORDS_IN_PTR + 3); *(output_ptr_++) = PBCMD_ASYNC_LOCK_VB; *((LPDIRECT3DVERTEXBUFFER *)output_ptr_) = vb; output_ptr_ += N_DWORDS_IN_PTR; *(output_ptr_++) = offset; *(output_ptr_++) = size; *(output_ptr_++) = flags; } inline void RememberLockedPointer(void *key, void *value) { int repl = -1; int i; for (i = 0; i < MAXIMUM_NUMBER_OF_BUFFERS_LOCKED_AT_ONCE; i++) { if (RememberedPointerHistory[i].m_pKey == key) break; if ((repl == -1) && (RememberedPointerHistory[i].m_pRememberedPtr == 0)) repl = i; } if (i != MAXIMUM_NUMBER_OF_BUFFERS_LOCKED_AT_ONCE) { RememberedPointerHistory[i].m_pRememberedPtr = value; if (value == NULL) RememberedPointerHistory[i].m_pKey = NULL; } else { if (repl == -1) { Assert(0); } else { RememberedPointerHistory[repl].m_pKey = key; RememberedPointerHistory[repl].m_pRememberedPtr = value; } } } inline void *RecallLockedPointer(void *key) { for (int i = 0; i < MAXIMUM_NUMBER_OF_BUFFERS_LOCKED_AT_ONCE; i++) if (RememberedPointerHistory[i].m_pKey == key) return RememberedPointerHistory[i].m_pRememberedPtr; return NULL; } void Direct3DDevice9Wrapper::HandleAsynchronousLockVBCommand( uint32_t const *dptr) { dptr++; LPDIRECT3DVERTEXBUFFER vb = *((LPDIRECT3DVERTEXBUFFER *)dptr); dptr += N_DWORDS_IN_PTR; uint32_t offset = *(dptr++); uint32_t size = *(dptr++); uint32_t flags = *(dptr++); void *locked_ptr = 0; vb->Lock(offset, size, &locked_ptr, flags); RememberLockedPointer(vb, locked_ptr); } void Direct3DDevice9Wrapper::HandleAsynchronousUnLockVBCommand( uint32_t const *dptr) { dptr++; LPDIRECT3DVERTEXBUFFER vb = *((LPDIRECT3DVERTEXBUFFER *)dptr); dptr += N_DWORDS_IN_PTR; LockedBufferContext lb = *((LockedBufferContext *)dptr); dptr += N_DWORDS(LockedBufferContext); size_t unlock_size = *(dptr++); void *locked_data = RecallLockedPointer(vb); Assert(locked_data); if (lb.m_pPushBuffer) { Assert(!lb.m_pMallocedMemory); if (locked_data) memcpy(locked_data, lb.m_pPushBuffer->m_BufferData, unlock_size); lb.m_pPushBuffer->m_State = PUSHBUFFER_AVAILABLE; } else if (lb.m_pMallocedMemory) { Assert(!lb.m_pPushBuffer); if (locked_data) memcpy(locked_data, lb.m_pMallocedMemory, unlock_size); delete[](uint8_t *) lb.m_pMallocedMemory; } // now, actually unlock RememberLockedPointer(vb, NULL); vb->Unlock(); } void Direct3DDevice9Wrapper::HandleAsynchronousLockIBCommand( uint32_t const *dptr) { dptr++; LPDIRECT3DINDEXBUFFER ib = *((LPDIRECT3DINDEXBUFFER *)dptr); Assert(ib); dptr += N_DWORDS_IN_PTR; uint32_t offset = *(dptr++); uint32_t size = *(dptr++); uint32_t flags = *(dptr++); void *locked_ptr = 0; ib->Lock(offset, size, &locked_ptr, flags); RememberLockedPointer(ib, locked_ptr); } void Direct3DDevice9Wrapper::HandleAsynchronousUnLockIBCommand( uint32_t const *dptr) { dptr++; LPDIRECT3DINDEXBUFFER ib = *((LPDIRECT3DINDEXBUFFER *)dptr); dptr += N_DWORDS_IN_PTR; LockedBufferContext lb = *((LockedBufferContext *)dptr); dptr += N_DWORDS(LockedBufferContext); size_t unlock_size = *(dptr++); void *locked_data = RecallLockedPointer(ib); Assert(locked_data); if (lb.m_pPushBuffer) { Assert(!lb.m_pMallocedMemory); if (locked_data) memcpy(locked_data, lb.m_pPushBuffer->m_BufferData, unlock_size); lb.m_pPushBuffer->m_State = PUSHBUFFER_AVAILABLE; } else if (lb.m_pMallocedMemory) { Assert(!lb.m_pPushBuffer); if (locked_data) memcpy(locked_data, lb.m_pMallocedMemory, unlock_size); delete[](uint8_t *) lb.m_pMallocedMemory; } // now, actually unlock RememberLockedPointer(ib, NULL); ib->Unlock(); } static inline void *FetchPtr(uint32_t const *mem) { void **p = (void **)mem; return *p; } #define CALC_STATS 1 #if CALC_STATS int n_commands_executed = 0; int n_pbs_executed = 0; #endif void Direct3DDevice9Wrapper::ExecutePushBuffer(PushBuffer const *pb) { uint32_t const *dptr = pb->m_BufferData; n_pbs_executed++; for (;;) { n_commands_executed++; switch (dptr[0]) { case PBCMD_END: n_commands_executed--; // doesn't count return; case PBCMD_SET_RENDERSTATE: { Dx9Device()->SetRenderState((D3DRENDERSTATETYPE)dptr[1], dptr[2]); dptr += 3; break; } case PBCMD_SET_SAMPLER_STATE: { Dx9Device()->SetSamplerState(dptr[1], (D3DSAMPLERSTATETYPE)dptr[2], dptr[3]); dptr += 4; break; } case PBCMD_DRAWPRIM: { Dx9Device()->DrawPrimitive((D3DPRIMITIVETYPE)dptr[1], dptr[2], dptr[3]); dptr += 4; break; } case PBCMD_DRAWINDEXEDPRIM: { Dx9Device()->DrawIndexedPrimitive((D3DPRIMITIVETYPE)dptr[1], dptr[2], dptr[3], dptr[4], dptr[5], dptr[6]); dptr += 7; break; } case PBCMD_SET_STREAM_SOURCE: { Dx9Device()->SetStreamSource( dptr[1], (IDirect3DVertexBuffer9 *)FetchPtr(dptr + 2), dptr[3], dptr[4]); dptr += 4 + N_DWORDS(IDirect3DVertexBuffer9 *); break; } case PBCMD_SET_TEXTURE: { Dx9Device()->SetTexture(dptr[1], (IDirect3DBaseTexture *)FetchPtr(dptr + 2)); dptr += 2 + N_DWORDS_IN_PTR; break; } case PBCMD_SET_RENDER_TARGET: { Dx9Device()->SetRenderTarget(dptr[1], (IDirect3DSurface *)FetchPtr(dptr + 2)); dptr += 2 + N_DWORDS_IN_PTR; break; } case PBCMD_SET_PIXEL_SHADER: { Dx9Device()->SetPixelShader( (IDirect3DPixelShader9 *)FetchPtr(dptr + 1)); dptr += 1 + N_DWORDS_IN_PTR; break; } case PBCMD_SET_INDICES: { Dx9Device()->SetIndices((IDirect3DIndexBuffer9 *)FetchPtr(dptr + 1)); dptr += 1 + N_DWORDS_IN_PTR; break; } case PBCMD_SET_DEPTH_STENCIL_SURFACE: { Dx9Device()->SetDepthStencilSurface( (IDirect3DSurface9 *)FetchPtr(dptr + 1)); dptr += 1 + N_DWORDS_IN_PTR; break; } case PBCMD_SETVIEWPORT: { Dx9Device()->SetViewport((D3DVIEWPORT9 const *)(dptr + 1)); dptr += 1 + N_DWORDS(D3DVIEWPORT9); break; } case PBCMD_SET_VERTEX_SHADER: { Dx9Device()->SetVertexShader( (IDirect3DVertexShader9 *)FetchPtr(dptr + 1)); dptr += 1 + N_DWORDS_IN_PTR; break; } case PBCMD_ASYNC_LOCK_VB: { HandleAsynchronousLockVBCommand(dptr); dptr += 1 + N_DWORDS_IN_PTR + 3; break; } case PBCMD_ASYNC_UNLOCK_VB: { HandleAsynchronousUnLockVBCommand(dptr); dptr += 1 + N_DWORDS_IN_PTR + N_DWORDS(LockedBufferContext) + 1; break; } case PBCMD_ASYNC_LOCK_IB: { HandleAsynchronousLockIBCommand(dptr); dptr += 1 + N_DWORDS_IN_PTR + 3; break; } case PBCMD_ASYNC_UNLOCK_IB: { HandleAsynchronousUnLockIBCommand(dptr); dptr += 1 + N_DWORDS_IN_PTR + N_DWORDS(LockedBufferContext) + 1; break; } case PBCMD_UNLOCK_VB: { IDirect3DVertexBuffer9 *p = (IDirect3DVertexBuffer9 *)FetchPtr(dptr + 1); p->Unlock(); dptr += 1 + N_DWORDS_IN_PTR; break; } case PBCMD_UNLOCK_IB: { IDirect3DIndexBuffer9 *p = (IDirect3DIndexBuffer9 *)FetchPtr(dptr + 1); p->Unlock(); dptr += 1 + N_DWORDS_IN_PTR; break; } case PBCMD_SET_VERTEX_SHADER_CONSTANT: { Dx9Device()->SetVertexShaderConstantF(dptr[1], (float const *)dptr + 3, dptr[2]); dptr += 3 + 4 * dptr[2]; break; } case PBCMD_SET_BOOLEAN_VERTEX_SHADER_CONSTANT: { Dx9Device()->SetVertexShaderConstantB(dptr[1], (int const *)dptr + 3, dptr[2]); dptr += 3 + dptr[2]; break; } case PBCMD_SET_INTEGER_VERTEX_SHADER_CONSTANT: { Dx9Device()->SetVertexShaderConstantI(dptr[1], (int const *)dptr + 3, dptr[2]); dptr += 3 + 4 * dptr[2]; break; } case PBCMD_SET_PIXEL_SHADER_CONSTANT: { Dx9Device()->SetPixelShaderConstantF(dptr[1], (float const *)dptr + 3, dptr[2]); dptr += 3 + 4 * dptr[2]; break; } case PBCMD_SET_BOOLEAN_PIXEL_SHADER_CONSTANT: { Dx9Device()->SetPixelShaderConstantB(dptr[1], (int const *)dptr + 3, dptr[2]); dptr += 3 + dptr[2]; break; } case PBCMD_SET_INTEGER_PIXEL_SHADER_CONSTANT: { Dx9Device()->SetPixelShaderConstantI(dptr[1], (int const *)dptr + 3, dptr[2]); dptr += 3 + 4 * dptr[2]; break; } case PBCMD_BEGIN_SCENE: { Dx9Device()->BeginScene(); dptr++; break; } case PBCMD_END_SCENE: { Dx9Device()->EndScene(); dptr++; break; } case PBCMD_CLEAR: { dptr++; int count = *(dptr++); D3DRECT const *pRects = 0; if (count) { pRects = (D3DRECT const *)dptr; dptr += count * N_DWORDS(D3DRECT); } int flags = *(dptr++); D3DCOLOR color = *((D3DCOLOR const *)(dptr++)); float z = *((float const *)(dptr++)); int stencil = *(dptr++); Dx9Device()->Clear(count, pRects, flags, color, z, stencil); break; } case PBCMD_SET_VERTEXDECLARATION: { Dx9Device()->SetVertexDeclaration( (IDirect3DVertexDeclaration9 *)FetchPtr(dptr + 1)); dptr += 1 + N_DWORDS_IN_PTR; break; } case PBCMD_SETCLIPPLANE: { Dx9Device()->SetClipPlane(dptr[1], (float const *)dptr + 2); dptr += 6; } break; case PBCMD_STRETCHRECT: { dptr++; IDirect3DSurface9 *pSourceSurface = (IDirect3DSurface9 *)FetchPtr(dptr); dptr += N_DWORDS_IN_PTR; RECT const *pSourceRect = 0; if (*(dptr++)) pSourceRect = (RECT const *)dptr; dptr += N_DWORDS(RECT); IDirect3DSurface9 *pDestSurface = (IDirect3DSurface9 *)FetchPtr(dptr); dptr += N_DWORDS_IN_PTR; RECT const *pDestRect = 0; if (*(dptr++)) pDestRect = (RECT const *)dptr; dptr += N_DWORDS(RECT); D3DTEXTUREFILTERTYPE Filter = (D3DTEXTUREFILTERTYPE) * (dptr++); Dx9Device()->StretchRect(pSourceSurface, pSourceRect, pDestSurface, pDestRect, Filter); } break; case PBCMD_PRESENT: { dptr++; RECT const *pSourceRect = 0; if (*(dptr++)) pSourceRect = (RECT const *)dptr; dptr += N_DWORDS(RECT); RECT const *pDestRect = 0; if (*(dptr++)) pDestRect = (RECT const *)dptr; dptr += N_DWORDS(RECT); HWND hDestWindowOverride = (HWND) * (dptr++); RGNDATA const *pDirtyRegion = 0; if (*(dptr++)) pDirtyRegion = (RGNDATA const *)dptr; dptr += N_DWORDS(RGNDATA); Dx9Device()->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion); break; } } } }
30.821918
80
0.618778
ArcadiusGFN