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
109
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
48.5k
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
83e058a2001fcf61af5b1aa8f04a126b1cb30ba7
459
hpp
C++
include/rive/constraints/targeted_constraint.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
139
2020-08-17T20:10:24.000Z
2022-03-28T12:22:44.000Z
include/rive/constraints/targeted_constraint.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
89
2020-08-28T16:41:01.000Z
2022-03-28T19:10:49.000Z
include/rive/constraints/targeted_constraint.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
19
2020-10-19T00:54:40.000Z
2022-02-28T05:34:17.000Z
#ifndef _RIVE_TARGETED_CONSTRAINT_HPP_ #define _RIVE_TARGETED_CONSTRAINT_HPP_ #include "rive/generated/constraints/targeted_constraint_base.hpp" #include <stdio.h> namespace rive { class TransformComponent; class TargetedConstraint : public TargetedConstraintBase { protected: TransformComponent* m_Target = nullptr; public: void buildDependencies() override; StatusCode onAddedDirty(CoreContext* context) override; }; } // namespace rive #endif
24.157895
66
0.812636
kariem2k
83e0eb15225bda6935122b0f804610d14d20a668
3,597
cpp
C++
src/material/deferredMaterial.cpp
mfirmin/audio-demo
767e2fc1b7afb53cd5aafad90ae562661a154373
[ "MIT" ]
1
2021-09-13T20:22:29.000Z
2021-09-13T20:22:29.000Z
src/material/deferredMaterial.cpp
mfirmin/audio-demo
767e2fc1b7afb53cd5aafad90ae562661a154373
[ "MIT" ]
null
null
null
src/material/deferredMaterial.cpp
mfirmin/audio-demo
767e2fc1b7afb53cd5aafad90ae562661a154373
[ "MIT" ]
1
2021-09-13T20:22:31.000Z
2021-09-13T20:22:31.000Z
#include "deferredMaterial.hpp" #include "gl/shaderUtils.hpp" #include "light/light.hpp" #include <GL/glew.h> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <string> #include <sstream> DeferredMaterial::DeferredMaterial(glm::vec3 color, float specularCoefficient, float shininess) : Material(color, specularCoefficient, shininess) { } void DeferredMaterial::create() { if (getProgram() != 0) { // already initialized return; } std::string vertexShaderSource = R"( #version 330 layout(location = 0) in vec3 position; layout(location = 1) in vec3 normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; out vec3 vNormalEyespace; out vec4 vPositionEyespace; void main() { vNormalEyespace = (transpose(inverse(viewMatrix * modelMatrix)) * vec4(normal, 0.0)).xyz; vPositionEyespace = viewMatrix * modelMatrix * vec4(position, 1.0); gl_Position = projectionMatrix * vPositionEyespace; } )"; std::string fragmentShaderSource = R"( #version 330 layout(location = 0) out vec4 position; layout(location = 1) out vec3 normal; layout(location = 2) out vec4 albedo; layout(location = 3) out vec4 emissive; uniform mat4 viewMatrix; uniform vec3 color; uniform float specularCoefficient; // todo: shininess? // uniform float shininess; uniform vec3 emissiveColor; uniform float emissiveStrength; uniform float emissiveEnabled; in vec3 vNormalEyespace; in vec4 vPositionEyespace; void main() { vec3 N = normalize(vNormalEyespace); vec3 E = normalize(-vPositionEyespace.xyz); if (dot(N, E) < 0.0) { N = -N; } position = vPositionEyespace; normal = N; albedo = vec4(color, specularCoefficient); if (emissiveEnabled > 0.5) { emissive = vec4(emissiveColor, emissiveStrength); } } )"; if (!compile(vertexShaderSource, fragmentShaderSource)) { return; } GLuint shader = getProgram(); glUseProgram(shader); auto projectionMatrixLocation = glGetUniformLocation(shader, "projectionMatrix"); auto viewMatrixLocation = glGetUniformLocation(shader, "viewMatrix"); auto modelMatrixLocation = glGetUniformLocation(shader, "modelMatrix"); auto colorLocation = glGetUniformLocation(shader, "color"); auto specularCoefficientLocation = glGetUniformLocation(shader, "specularCoefficient"); auto emissiveColorLocation = glGetUniformLocation(shader, "emissiveColor"); auto emissiveStrengthLocation = glGetUniformLocation(shader, "emissiveStrength"); auto emissiveEnabledLocation = glGetUniformLocation(shader, "emissiveEnabled"); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0))); glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0))); glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, glm::value_ptr(glm::mat4(1.0))); glUniform3fv(colorLocation, 1, glm::value_ptr(getColor())); glUniform1f(specularCoefficientLocation, getSpecularCoefficient()); glUniform3fv(emissiveColorLocation, 1, glm::value_ptr(getColor())); glUniform1f(emissiveStrengthLocation, 0.0f); glUniform1f(emissiveEnabledLocation, 0.0f); glUseProgram(0); } DeferredMaterial::~DeferredMaterial() {}
33
147
0.666389
mfirmin
83e893e9f021dbd7327ca9ac7bed37ba91434a57
7,862
cpp
C++
kbar.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
kbar.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
kbar.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
1
2021-08-20T16:15:01.000Z
2021-08-20T16:15:01.000Z
// // DEKAF(tm): Lighter, Faster, Smarter(tm) // // Copyright (c) 2000-2003, Ridgeware, Inc. // // +-------------------------------------------------------------------------+ // | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\| // |/+---------------------------------------------------------------------+/| // |/| |/| // |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\| // |/| |/| // |\| OPEN SOURCE LICENSE |\| // |/| |/| // |\| Permission is hereby granted, free of charge, to any person |\| // |/| obtaining a copy of this software and associated |/| // |\| documentation files (the "Software"), to deal in the |\| // |/| Software without restriction, including without limitation |/| // |\| the rights to use, copy, modify, merge, publish, |\| // |/| distribute, sublicense, and/or sell copies of the Software, |/| // |\| and to permit persons to whom the Software is furnished to |\| // |/| do so, subject to the following conditions: |/| // |\| |\| // |/| The above copyright notice and this permission notice shall |/| // |\| be included in all copies or substantial portions of the |\| // |/| Software. |/| // |\| |\| // |/| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY |/| // |\| KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE |\| // |/| WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |/| // |\| PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS |\| // |/| OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR |/| // |\| OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR |\| // |/| OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE |/| // |\| SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |\| // |/| |/| // |/+---------------------------------------------------------------------+/| // |\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ | // +-------------------------------------------------------------------------+ // #include "kstring.h" #include "kbar.h" #include "kwriter.h" #include "klog.h" namespace dekaf2 { //----------------------------------------------------------------------------- KBAR::KBAR (uint64_t iExpected/*=0*/, uint32_t iWidth/*=DEFAULT_WIDTH*/, uint64_t iFlags/*=SLIDER*/, int chDone/*='%'*/, KOutStream& Out/*=KOut*/) //----------------------------------------------------------------------------- : m_iFlags(iFlags) , m_iWidth(iWidth) , m_iExpected(iExpected) , m_iSoFar(0) , m_chDone(chDone) , m_Out(Out) , m_bSliding(false) { if (m_iExpected && (m_iFlags & SLIDER)) { _SliderAction (KPS_START, 0, 0); m_bSliding = true; } } // constructor //----------------------------------------------------------------------------- KBAR::~KBAR() //----------------------------------------------------------------------------- { Finish(); } //----------------------------------------------------------------------------- bool KBAR::Start (uint64_t iExpected) //----------------------------------------------------------------------------- { m_iExpected = iExpected; if (m_iExpected && (m_iFlags & SLIDER)) { m_iSoFar = 0; _SliderAction (KPS_START, 0, 0); m_bSliding = true; } return (true); } // Start //----------------------------------------------------------------------------- bool KBAR::Adjust (uint64_t iExpected) //----------------------------------------------------------------------------- { if (iExpected > m_iSoFar) { m_iExpected = iExpected; return (true); } else { return (false); } } // Adjust //----------------------------------------------------------------------------- bool KBAR::Move (int64_t iDelta) //----------------------------------------------------------------------------- { uint64_t iWant = m_iSoFar + iDelta; bool fOK = true; if (iWant > m_iExpected) { iWant = m_iExpected; fOK = false; } if ((iWant < m_iSoFar) && (m_iFlags & SLIDER)) { iWant = m_iSoFar; // cannot go backwards fOK = false; } iDelta = iWant - m_iSoFar; if (m_bSliding) { if (KLog::getInstance().GetLevel()) { kDebugLog (1, "kbar: {:3}%, {} of {}", ((m_iSoFar+iDelta))*100/m_iExpected, m_iSoFar+iDelta, m_iExpected); } else { _SliderAction (KPS_ADD, m_iSoFar, m_iSoFar+iDelta); } } m_iSoFar += iDelta; return (fOK); } // Move //----------------------------------------------------------------------------- KString KBAR::GetBar (int chBlank/*=' '*/) //----------------------------------------------------------------------------- { KString sBar; if (!m_iExpected) { return sBar; } double nPercentNow = ((double)m_iSoFar / (double)m_iExpected); if (nPercentNow > 100.0) { nPercentNow = 100.0; } uint32_t iNumBarsNow = (int) (nPercentNow * (double)(m_iWidth)); kDebug (1, "{} out of {}, {}%, {} out of {} bars", m_iSoFar, m_iExpected, nPercentNow, iNumBarsNow, m_iWidth); for (uint32_t ii=1; ii<=m_iWidth; ++ii) { if (ii <= iNumBarsNow) { sBar += m_chDone; } else { sBar += chBlank; } } return (sBar); } // GetBar //----------------------------------------------------------------------------- void KBAR::RepaintSlider () //----------------------------------------------------------------------------- { if (m_iFlags & SLIDER) { _SliderAction (KPS_START, 0, 0); _SliderAction (KPS_ADD, 0, m_iSoFar); } } // RepaintSlider //----------------------------------------------------------------------------- void KBAR::Finish () //----------------------------------------------------------------------------- { if (m_bSliding) { _SliderAction (KPS_END, m_iSoFar, m_iExpected); m_bSliding = false; } m_iExpected = m_iSoFar; } // Finish //----------------------------------------------------------------------------- void KBAR::Break (KStringView sMsg/*="!!!"*/) //----------------------------------------------------------------------------- { if (m_bSliding) { m_Out.WriteLine (sMsg); m_bSliding = false; } } // Break //----------------------------------------------------------------------------- void KBAR::_SliderAction (int iAction, uint64_t iSoFarLast, uint64_t iSoFarNow) //----------------------------------------------------------------------------- { if (KLog::getInstance().GetLevel()) // progress bar only makes sense when NOT klogging { return; } double nPercentLast = ((double)iSoFarLast / (double)m_iExpected); if (nPercentLast > 100.0) { nPercentLast = 100.0; } double nPercentNow = ((double)iSoFarNow / (double)m_iExpected); if (nPercentNow > 100.0) { nPercentNow = 100.0; } uint32_t iNumBarsLast = (int) (nPercentLast * (double)(m_iWidth)); uint32_t iNumBarsNow = (int) (nPercentNow * (double)(m_iWidth)); uint32_t ii; switch (iAction) { case KPS_START: m_Out.Write('v'); for (ii=0; ii<m_iWidth; ++ii) { m_Out.Write('_'); } m_Out.Write("v\n|"); break; case KPS_ADD: for (ii=iNumBarsLast; ii<iNumBarsNow; ++ii) { m_Out.Write(m_chDone); } break; case KPS_END: for (ii=iNumBarsLast; ii<m_iWidth; ++ii) { m_Out.Write(' '); } m_Out.Write("|\n"); } m_Out.Flush(); } // _SliderAction } // of namespace dekaf2
28.078571
146
0.407148
ridgeware
83ea2428af336f95fb2326f096ec03a630611643
5,743
cpp
C++
src/programs/advection.cpp
pedrospeixoto/sweet
224248181e92615467c94b4e163596017811b5eb
[ "MIT" ]
null
null
null
src/programs/advection.cpp
pedrospeixoto/sweet
224248181e92615467c94b4e163596017811b5eb
[ "MIT" ]
null
null
null
src/programs/advection.cpp
pedrospeixoto/sweet
224248181e92615467c94b4e163596017811b5eb
[ "MIT" ]
1
2019-03-27T01:17:59.000Z
2019-03-27T01:17:59.000Z
#include <sweet/DataArray.hpp> #if SWEET_GUI #include "sweet/VisSweet.hpp" #endif #include <sweet/SimulationVariables.hpp> #include "sweet/Operators2D.hpp" #include <unistd.h> #include <stdio.h> SimulationVariables simVars; class SimulationSWE { public: DataArray<2> h; DataArray<2> u; DataArray<2> v; DataArray<2> hu; DataArray<2> hv; DataArray<2> h_t; Operators2D op; public: SimulationSWE() : h(simVars.disc.res), u(simVars.disc.res), v(simVars.disc.res), hu(simVars.disc.res), hv(simVars.disc.res), h_t(simVars.disc.res), op(simVars.disc.res, simVars.sim.domain_size, simVars.disc.use_spectral_basis_diffs) { reset(); } void reset() { simVars.timecontrol.current_timestep_nr = 0; h.set_all(simVars.setup.h0); if (std::isinf(simVars.bogus.var[0])) { u.set_all(0); v.set_all(0); } else { u.set_all(simVars.bogus.var[0]); v.set_all(simVars.bogus.var[1]); } double center_x = 0.7; double center_y = 0.6; if (simVars.setup.scenario == 0) { /* * radial dam break */ double radius = 0.2; for (std::size_t j = 0; j < simVars.disc.res[1]; j++) { for (std::size_t i = 0; i < simVars.disc.res[0]; i++) { double x = ((double)i+0.5)/(double)simVars.disc.res[0]; double y = ((double)j+0.5)/(double)simVars.disc.res[1]; double dx = x-center_x; double dy = y-center_y; if (radius*radius >= dx*dx+dy*dy) h.set(j,i, simVars.setup.h0+1.0); } } } if (simVars.setup.scenario == 1) { /* * fun with Gaussian */ for (std::size_t j = 0; j < simVars.disc.res[1]; j++) { for (std::size_t i = 0; i < simVars.disc.res[0]; i++) { double x = ((double)i+0.5)/(double)simVars.disc.res[0]; double y = ((double)j+0.5)/(double)simVars.disc.res[1]; double dx = x-center_x; double dy = y-center_y; h.set(j,i, simVars.setup.h0+std::exp(-50.0*(dx*dx + dy*dy))); } } } } void run_timestep() { double dt = simVars.sim.CFL*std::min(simVars.disc.cell_size[0]/u.reduce_maxAbs(), simVars.disc.cell_size[1]/v.reduce_maxAbs()); if (std::isinf(dt)) dt = simVars.sim.CFL*simVars.disc.cell_size[0]/0.000001; simVars.timecontrol.current_timestep_size = dt; // 0: staggered // 1: non-staggered // 2: up/downwinding #define GRID_LAYOUT_AND_ADVECTION 2 #if ADVECTION_METHOD == 0 // staggered h -= dt*( op.diff_b_x(op.avg_f_x(h)*u) + op.diff_b_y(op.avg_f_y(h)*v) ); #endif #if ADVECTION_METHOD == 1 // non-staggered h = h - dt*( op.diff_c_x(h*u) + op.diff_c_y(h*v) ); #endif #if ADVECTION_METHOD == 2 h += dt* ( ( // u is positive op.shift_right(h)*u.return_value_if_positive() // inflow -h*op.shift_left(u.return_value_if_positive()) // outflow // u is negative +(h*u.return_value_if_negative()) // outflow -op.shift_left(h*u.return_value_if_negative()) // inflow )*(1.0/simVars.disc.cell_size[0]) // here we see a finite-difference-like formulation + ( // v is positive op.shift_up(h)*v.return_value_if_positive() // inflow -h*op.shift_down(v.return_value_if_positive()) // outflow // v is negative +(h*v.return_value_if_negative()) // outflow -op.shift_down(h*v.return_value_if_negative()) // inflow )*(1.0/simVars.disc.cell_size[1]) ); #endif simVars.timecontrol.current_timestep_nr++; } bool should_quit() { return false; } /** * postprocessing of frame: do time stepping */ void vis_post_frame_processing(int i_num_iterations) { if (simVars.timecontrol.run_simulation_timesteps) for (int i = 0; i < i_num_iterations; i++) run_timestep(); } void vis_get_vis_data_array( const DataArray<2> **o_dataArray, double *o_aspect_ratio ) { switch (simVars.misc.vis_id) { case 0: *o_dataArray = &h; break; case 1: *o_dataArray = &u; break; case 2: *o_dataArray = &v; break; } *o_aspect_ratio = simVars.sim.domain_size[1] / simVars.sim.domain_size[0]; } const char* vis_get_status_string() { static char title_string[1024]; sprintf(title_string, "Timestep: %i, timestep size: %e", simVars.timecontrol.current_timestep_nr, simVars.timecontrol.current_timestep_size); return title_string; } void vis_pause() { simVars.timecontrol.run_simulation_timesteps = !simVars.timecontrol.run_simulation_timesteps; } void vis_keypress(int i_key) { switch(i_key) { case 'v': simVars.misc.vis_id++; break; case 'V': simVars.misc.vis_id--; break; } } }; int main(int i_argc, char *i_argv[]) { const char *bogus_var_names[] = { "velocity-u", "velocity-v", nullptr }; if (!simVars.setupFromMainParameters(i_argc, i_argv, bogus_var_names)) { std::cout << std::endl; std::cout << "Program-specific options:" << std::endl; std::cout << " --velocity-u [advection velocity u]" << std::endl; std::cout << " --velocity-v [advection velocity v]" << std::endl; return -1; } if (std::isinf(simVars.bogus.var[0]) || std::isinf(simVars.bogus.var[1])) { std::cout << "Both velocities have to be set, see parameters --velocity-u, --velocity-v" << std::endl; return -1; } SimulationSWE *simulationSWE = new SimulationSWE; #if SWEET_GUI VisSweet<SimulationSWE> visSweet(simulationSWE); #else simulationSWE->reset(); while (!simulationSWE->should_quit()) { simulationSWE->run_timestep(); if (simVars.misc.verbosity > 2) std::cout << simVars.timecontrol.current_simulation_time << std::endl; if (simVars.timecontrol.current_simulation_time > simVars.timecontrol.max_simulation_time) break; } #endif delete simulationSWE; return 0; }
19.940972
143
0.640432
pedrospeixoto
83ec4d6f63c2476238bc4eb8701c2d307a2ee4c5
46,974
cpp
C++
DESIRE-Modules/Script-AngelScript/src/API/CoreAPI_Math_AngelScript.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2020-10-04T18:50:01.000Z
2020-10-04T18:50:01.000Z
DESIRE-Modules/Script-AngelScript/src/API/CoreAPI_Math_AngelScript.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
null
null
null
DESIRE-Modules/Script-AngelScript/src/API/CoreAPI_Math_AngelScript.cpp
nyaki-HUN/DESIRE
dd579bffa77bc6999266c8011bc389bb96dee01d
[ "BSD-2-Clause" ]
1
2018-09-18T08:03:33.000Z
2018-09-18T08:03:33.000Z
#include "stdafx_AngelScript.h" #include "API/AngelScriptAPI.h" #include "Engine/Core/Math/Math.h" #include "Engine/Core/Math/Matrix4.h" #include "Engine/Core/Math/Rand.h" #include "Engine/Core/Math/Transform.h" static Vector3* Vector3_Cross(const Vector3& vec0, const Vector3& vec1) { return new Vector3(vec0.Cross(vec1)); } static Vector3* Transform_GetPosition(const Transform& transform) { return new Vector3(transform.GetPosition()); } static Quat* Transform_GetRotation(const Transform& transform) { return new Quat(transform.GetRotation()); } static Vector3* Transform_GetScale(const Transform& transform) { return new Vector3(transform.GetScale()); } void RegisterCoreAPI_Math_AngelScript(asIScriptEngine& engine) { int32_t result = asSUCCESS; // Vector3 result = engine.RegisterObjectType("Vector3", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector3", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Vector3>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector3", asBEHAVE_FACTORY, "Vector3@ f()", asFUNCTION(AngelScriptAPI<Vector3>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector3", asBEHAVE_FACTORY, "Vector3@ f(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector3>::FactoryWithArgs<const Vector3&>), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector3", asBEHAVE_FACTORY, "Vector3@ f(float, float, float)", asFUNCTION((AngelScriptAPI<Vector3>::FactoryWithArgs<float, float, float>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void SetX(float)", asMETHOD(Vector3, SetX), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void SetY(float)", asMETHOD(Vector3, SetY), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void SetZ(float)", asMETHOD(Vector3, SetZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "float GetX() const", asMETHOD(Vector3, GetX), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "float GetY() const", asMETHOD(Vector3, GetY), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "float GetZ() const", asMETHOD(Vector3, GetZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void opAssign(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector3>::OpAssign<Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ opNeg()", asFUNCTION(AngelScriptAPI<Vector3>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ opAdd(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Vector3>::OpAdd<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ opSub(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Vector3>::OpSub<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ opMul(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Vector3>::OpMul<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ opMul(float) const", asFUNCTION(AngelScriptAPI<Vector3>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ opMul_r(float) const", asFUNCTION(AngelScriptAPI<Vector3>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ opDiv(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Vector3>::OpDiv<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ opDiv(float) const", asFUNCTION(AngelScriptAPI<Vector3>::OpDiv<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void opAddAssign(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector3>::OpAddAssign<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void subAssign(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector3>::OpSubAssign<const Vector3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void opMulAssign(float)", asFUNCTION(AngelScriptAPI<Vector3>::OpMulAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void opDivAssign(float)", asFUNCTION(AngelScriptAPI<Vector3>::OpDivAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "float Dot(const Vector3& in) const", asMETHOD(Vector3, Dot), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "Vector3@ Cross(const Vector3& in) const", asFUNCTION(Vector3_Cross), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "float LengthSqr() const", asMETHOD(Vector3, LengthSqr), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "float Length() const", asMETHOD(Vector3, Length), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "void Normalize()", asMETHOD(Vector3, Normalize), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // result = engine.RegisterObjectMethod("Vector3", "Vector3@ Normalized() const", asMETHOD(Vector3, Normalized), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // Vector3 Abs() const; ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "float GetMaxElement() const", asMETHOD(Vector3, GetMaxElement), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector3", "float GetMinElement() const", asMETHOD(Vector3, GetMinElement), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace("Vector3"); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector3@ Max(const Vector3& in, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Vector3>::StaticFunc<const Vector3&, const Vector3&, &Vector3::Max>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector3@ Min(const Vector3& in, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Vector3>::StaticFunc<const Vector3&, const Vector3&, &Vector3::Min>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector3@ Zero()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::Zero>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector3@ One()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::One>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector3@ AxisX()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::AxisX>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector3@ AxisY()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::AxisY>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector3@ AxisZ()", asFUNCTION(AngelScriptGenericAPI<Vector3>::StaticFunc<&Vector3::AxisZ>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS); // Vector4 result = engine.RegisterObjectType("Vector4", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Vector4>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f()", asFUNCTION(AngelScriptAPI<Vector4>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f(const Vector4& in)", asFUNCTION(AngelScriptAPI<Vector4>::FactoryWithArgs<const Vector4&>), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f(float, float, float, float)", asFUNCTION((AngelScriptAPI<Vector4>::FactoryWithArgs<float, float, float, float>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f(const Vector3& in, float)", asFUNCTION((AngelScriptAPI<Vector4>::FactoryWithArgs<const Vector3&, float>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Vector4", asBEHAVE_FACTORY, "Vector4@ f(const Vector3& in)", asFUNCTION(AngelScriptAPI<Vector4>::FactoryWithArgs<const Vector3&>), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void SetXYZ(const Vector3& in)", asMETHOD(Vector4, SetXYZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // Vector3 GetXYZ() const ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void SetX(float)", asMETHOD(Vector4, SetX), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void SetY(float)", asMETHOD(Vector4, SetY), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void SetZ(float)", asMETHOD(Vector4, SetZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void SetW(float)", asMETHOD(Vector4, SetW), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float GetX() const", asMETHOD(Vector4, GetX), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float GetY() const", asMETHOD(Vector4, GetY), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float GetZ() const", asMETHOD(Vector4, GetZ), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float GetW() const", asMETHOD(Vector4, GetW), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void opAssign(const Vector4& in)", asFUNCTION(AngelScriptAPI<Vector4>::OpAssign<Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "Vector4@ opNeg()", asFUNCTION(AngelScriptAPI<Vector4>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "Vector4@ opAdd(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Vector4>::OpAdd<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "Vector4@ opSub(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Vector4>::OpSub<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "Vector4@ opMul(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Vector4>::OpMul<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "Vector4@ opMul(float) const", asFUNCTION(AngelScriptAPI<Vector4>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "Vector4@ opMul_r(float) const", asFUNCTION(AngelScriptAPI<Vector4>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "Vector4@ opDiv(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Vector4>::OpDiv<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "Vector4@ opDiv(float) const", asFUNCTION(AngelScriptAPI<Vector4>::OpDiv<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void opAddAssign(const Vector4& in)", asFUNCTION(AngelScriptAPI<Vector4>::OpAddAssign<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void subAssign(const Vector4& in)", asFUNCTION(AngelScriptAPI<Vector4>::OpSubAssign<const Vector4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void opMulAssign(float)", asFUNCTION(AngelScriptAPI<Vector4>::OpMulAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void opDivAssign(float)", asFUNCTION(AngelScriptAPI<Vector4>::OpDivAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float GetMaxElement() const", asMETHOD(Vector4, GetMaxElement), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float GetMinElement() const", asMETHOD(Vector4, GetMinElement), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float Dot(const Vector4& in) const", asMETHOD(Vector4, Dot), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float LengthSqr() const", asMETHOD(Vector4, LengthSqr), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "float Length() const", asMETHOD(Vector4, Length), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Vector4", "void Normalize()", asMETHOD(Vector4, Normalize), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // result = engine.RegisterObjectMethod("Vector4", "Vector4@ Normalized() const", asMETHOD(Vector4, Normalized), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // Vector4 Abs() const ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace("Vector4"); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector4@ Max(const Vector4& in, const Vector4& in)", asFUNCTION((AngelScriptGenericAPI<Vector4>::StaticFunc<const Vector4&, const Vector4&, &Vector4::Max>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector4@ Min(const Vector4& in, const Vector4& in)", asFUNCTION((AngelScriptGenericAPI<Vector4>::StaticFunc<const Vector4&, const Vector4&, &Vector4::Min>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector4@ AxisX()", asFUNCTION(AngelScriptGenericAPI<Vector4>::StaticFunc<&Vector4::AxisX>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector4@ AxisY()", asFUNCTION(AngelScriptGenericAPI<Vector4>::StaticFunc<&Vector4::AxisY>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector4@ AxisZ()", asFUNCTION(AngelScriptGenericAPI<Vector4>::StaticFunc<&Vector4::AxisZ>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Vector4@ AxisW()", asFUNCTION(AngelScriptGenericAPI<Vector4>::StaticFunc<&Vector4::AxisW>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS); // Quat result = engine.RegisterObjectType("Quat", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Quat>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_FACTORY, "Quat@ f()", asFUNCTION(AngelScriptAPI<Quat>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_FACTORY, "Quat@ f(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::FactoryWithArgs<const Quat&>), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_FACTORY, "Quat@ f(float, float, float, float)", asFUNCTION((AngelScriptAPI<Quat>::FactoryWithArgs<float, float, float, float>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "void opAssign(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::OpAssign<Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "Quat@ opNeg()", asFUNCTION(AngelScriptAPI<Quat>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "Quat@ opAdd(const Quat& in) const", asFUNCTION(AngelScriptAPI<Quat>::OpAdd<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "Quat@ opSub(const Quat& in) const", asFUNCTION(AngelScriptAPI<Quat>::OpSub<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "Quat@ opMul(const Quat& in) const", asFUNCTION(AngelScriptAPI<Quat>::OpMul<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "void opAddAssign(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::OpAddAssign<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "void subAssign(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::OpSubAssign<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "void opMulAssign(const Quat& in)", asFUNCTION(AngelScriptAPI<Quat>::OpMulAssign<const Quat&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "float Dot(const Quat& in) const", asMETHOD(Quat, Dot), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "float Norm()", asMETHOD(Quat, Norm), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "float Length() const", asMETHOD(Quat, Length), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // Quat Conjugate() const; ASSERT(result >= asSUCCESS); // Vector3 EulerAngles() const; ASSERT(result >= asSUCCESS); // Vector3 RotateVec(const Vector3& vec) const; ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Quat", "void Normalize()", asMETHOD(Quat, Normalize), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // result = engine.RegisterObjectMethod("Quat", "Quat@ Normalized() const", asMETHOD(Quat, Normalized), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace("Quat"); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Quat@ Identity()", asFUNCTION(AngelScriptGenericAPI<Quat>::StaticFunc<&Quat::Identity>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Quat@ CreateRotation(float, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<float, const Vector3&, &Quat::CreateRotation>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Quat@ CreateRotationX(float)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<float, &Quat::CreateRotationX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Quat@ CreateRotationY(float)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<float, &Quat::CreateRotationY>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Quat@ CreateRotationZ(float)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<float, &Quat::CreateRotationZ>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Quat@ CreateRotationFromEulerAngles(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Quat>::StaticFunc<const Vector3&, &Quat::CreateRotationFromEulerAngles>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS); // Matrix3 result = engine.RegisterObjectType("Matrix3", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Matrix3>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_FACTORY, "Matrix3@ f()", asFUNCTION(AngelScriptAPI<Matrix3>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_FACTORY, "Matrix3@ f(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::FactoryWithArgs<const Matrix3&>), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_FACTORY, "Matrix3@ f(const Vector3& in, const Vector3& in, const Vector3& in)", asFUNCTION((AngelScriptAPI<Matrix3>::FactoryWithArgs<const Vector3&, const Vector3&, const Vector3&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix3", asBEHAVE_FACTORY, "Matrix3@ f(const Quat& in)", asFUNCTION(AngelScriptAPI<Matrix3>::FactoryWithArgs<const Quat&>), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectProperty("Matrix3", "Vector3& m_col0", asOFFSET(Matrix3, m_col0)); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectProperty("Matrix3", "Vector3& m_col1", asOFFSET(Matrix3, m_col1)); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectProperty("Matrix3", "Vector3& m_col2", asOFFSET(Matrix3, m_col2)); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void SetCol(int, const Vector3& in)", asMETHOD(Matrix3, SetCol), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "Vector3& GetCol(int) const", asMETHOD(Matrix3, GetCol), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void SetRow0(const Vector3& in)", asMETHOD(Matrix3, SetRow0), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // Vector3 GetRow0() const ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void opAssign(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::OpAssign<Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opNeg()", asFUNCTION(AngelScriptAPI<Matrix3>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opAdd(const Matrix3& in) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpAdd<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opSub(const Matrix3& in) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpSub<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opMul(float) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opMul_r(float) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "Vector3@ opMul(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpMul_2<Vector3>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "Matrix3@ opMul(const Matrix3& in) const", asFUNCTION(AngelScriptAPI<Matrix3>::OpMul<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void opAddAssign(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::OpAddAssign<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void subAssign(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::OpSubAssign<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void opMulAssign(float)", asFUNCTION(AngelScriptAPI<Matrix3>::OpMulAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void opMulAssign(const Matrix3& in)", asFUNCTION(AngelScriptAPI<Matrix3>::OpMulAssign<const Matrix3&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void AppendScale(const Vector3& in)", asMETHOD(Matrix3, AppendScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void PrependScale(const Vector3& in)", asMETHOD(Matrix3, PrependScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void Transpose()", asMETHOD(Matrix3, Transpose), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "void Invert()", asMETHOD(Matrix3, Invert), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix3", "float CalculateDeterminant() const", asMETHOD(Matrix3, CalculateDeterminant), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace("Matrix3"); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix3@ Identity()", asFUNCTION(AngelScriptGenericAPI<Matrix3>::StaticFunc<&Matrix3::Identity>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix3@ CreateRotationX(float)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<float, &Matrix3::CreateRotationX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix3@ CreateRotationY(float)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<float, &Matrix3::CreateRotationY>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix3@ CreateRotationZ(float)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<float, &Matrix3::CreateRotationZ>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix3@ CreateRotationZYX(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<const Vector3&, &Matrix3::CreateRotationZYX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix3@ CreateRotation(float, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<float, const Vector3&, &Matrix3::CreateRotation>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix3@ CreateScale(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix3>::StaticFunc<const Vector3&, &Matrix3::CreateScale>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Quat", asBEHAVE_FACTORY, "Quat@ f(const Matrix3& in)", asFUNCTION((AngelScriptAPI<Quat>::FactoryWithArgs<const Matrix3&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); // Matrix4 result = engine.RegisterObjectType("Matrix4", 0, asOBJ_REF | asOBJ_SCOPED); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_RELEASE, "void f()", asFUNCTION(AngelScriptAPI<Matrix4>::Release), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f()", asFUNCTION(AngelScriptAPI<Matrix4>::Factory), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::FactoryWithArgs<const Matrix4&>), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f(const Vector4& in, const Vector4& in, const Vector4& in, const Vector4& in)", asFUNCTION((AngelScriptAPI<Matrix4>::FactoryWithArgs<const Vector4&, const Vector4&, const Vector4&, const Vector4&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f(const Matrix3& in, const Vector3& in)", asFUNCTION((AngelScriptAPI<Matrix4>::FactoryWithArgs<const Matrix3&, const Vector3&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectBehaviour("Matrix4", asBEHAVE_FACTORY, "Matrix4@ f(const Quat& in, const Vector3& in)", asFUNCTION((AngelScriptAPI<Matrix4>::FactoryWithArgs<const Quat&, const Vector3&>)), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void SetUpper3x3(const Matrix3& in)", asMETHOD(Matrix4, SetUpper3x3), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // Matrix3 GetUpper3x3() const ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void SetTranslation(const Vector3& in)", asMETHOD(Matrix4, SetTranslation), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // Vector3 GetTranslation() const ASSERT(result >= asSUCCESS); result = engine.RegisterObjectProperty("Matrix4", "Vector4& m_col0", asOFFSET(Matrix4, m_col0)); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectProperty("Matrix4", "Vector4& m_col1", asOFFSET(Matrix4, m_col1)); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectProperty("Matrix4", "Vector4& m_col2", asOFFSET(Matrix4, m_col2)); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectProperty("Matrix4", "Vector4& m_col3", asOFFSET(Matrix4, m_col3)); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void SetCol(int, const Vector4& in)", asMETHOD(Matrix4, SetCol), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Vector4& GetCol(int) const", asMETHOD(Matrix4, GetCol), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void SetRow0(const Vector4& in)", asMETHOD(Matrix4, SetRow0), asCALL_THISCALL); ASSERT(result >= asSUCCESS); // Vector4 GetRow0() const ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void opAssign(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::OpAssign<Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opNeg()", asFUNCTION(AngelScriptAPI<Matrix4>::OpNeg), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opAdd(const Matrix4& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpAdd<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opSub(const Matrix4& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpSub<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opMul(float) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opMul_r(float) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Vector4@ opMul(const Vector4& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul_2<Vector4>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Vector4@ opMul(const Vector3& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul_2<Vector3>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "Matrix4@ opMul(const Matrix4& in) const", asFUNCTION(AngelScriptAPI<Matrix4>::OpMul<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void opAddAssign(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::OpAddAssign<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void subAssign(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::OpSubAssign<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void opMulAssign(float)", asFUNCTION(AngelScriptAPI<Matrix4>::OpMulAssign<float>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void opMulAssign(const Matrix4& in)", asFUNCTION(AngelScriptAPI<Matrix4>::OpMulAssign<const Matrix4&>), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void AppendScale(const Vector3& in)", asMETHOD(Matrix4, AppendScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void PrependScale(const Vector3& in)", asMETHOD(Matrix4, PrependScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void Transpose()", asMETHOD(Matrix4, Transpose), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void Invert()", asMETHOD(Matrix4, Invert), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void AffineInvert()", asMETHOD(Matrix4, AffineInvert), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "void OrthoInvert()", asMETHOD(Matrix4, OrthoInvert), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Matrix4", "float CalculateDeterminant() const", asMETHOD(Matrix4, CalculateDeterminant), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace("Matrix4"); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix4@ Identity()", asFUNCTION(AngelScriptGenericAPI<Matrix4>::StaticFunc<&Matrix4::Identity>), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix4@ CreateTranslation(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<const Vector3&, &Matrix4::CreateTranslation>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix4@ CreateRotationX(float)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<float, &Matrix4::CreateRotationX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix4@ CreateRotationY(float)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<float, &Matrix4::CreateRotationY>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix4@ CreateRotationZ(float)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<float, &Matrix4::CreateRotationZ>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix4@ CreateRotationZYX(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<const Vector3&, &Matrix4::CreateRotationZYX>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix4@ CreateRotation(float, const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<float, const Vector3&, &Matrix4::CreateRotation>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("Matrix4@ CreateScale(const Vector3& in)", asFUNCTION((AngelScriptGenericAPI<Matrix4>::StaticFunc<const Vector3&, &Matrix4::CreateScale>)), asCALL_GENERIC); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS); // Transform result = engine.RegisterObjectType("Transform", 0, asOBJ_REF | asOBJ_NOHANDLE); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "void SetLocalPosition(const Vector3& in)", asMETHOD(Transform, SetLocalPosition), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "const Vector3& GetLocalPosition() const", asMETHOD(Transform, GetLocalPosition), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "void SetLocalRotation(const Quat& in)", asMETHOD(Transform, SetLocalRotation), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "const Quat& GetLocalRotation() const", asMETHOD(Transform, GetLocalRotation), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "void SetLocalScale(const Vector3& in)", asMETHOD(Transform, SetLocalScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "const Vector3& GetLocalScale() const", asMETHOD(Transform, GetLocalScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "void SetPosition(const Vector3& in)", asMETHOD(Transform, SetPosition), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "Vector3@ GetPosition() const", asFUNCTION(Transform_GetPosition), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "void SetRotation(const Quat& in)", asMETHOD(Transform, SetRotation), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "Quat@ GetRotation() const", asFUNCTION(Transform_GetRotation), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "void SetScale(const Vector3& in)", asMETHOD(Transform, SetScale), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Transform", "Vector3@ GetScale() const", asFUNCTION(Transform_GetScale), asCALL_CDECL_OBJFIRST); ASSERT(result >= asSUCCESS); // Rand result = engine.RegisterObjectType("Rand", 0, asOBJ_REF | asOBJ_NOHANDLE); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Rand", "int GetInt32()", asMETHOD(Rand, GetInt32), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Rand", "uint GetUint32()", asMETHOD(Rand, GetUint32), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Rand", "float GetFloat()", asMETHOD(Rand, GetFloat), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Rand", "double GetDouble()", asMETHOD(Rand, GetDouble), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterObjectMethod("Rand", "bool GetBool()", asMETHOD(Rand, GetBool), asCALL_THISCALL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalProperty("Rand s_globalRand", &Rand::s_globalRand); ASSERT(result >= asSUCCESS); // Math result = engine.SetDefaultNamespace("Math"); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("int Round32(float)", asFUNCTION(Math::Round32), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("int RoundUp(float, int)", asFUNCTION(Math::RoundUp), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.SetDefaultNamespace(""); ASSERT(result >= asSUCCESS); // Trigonometric functions result = engine.RegisterGlobalFunction("float cos(float)", asFUNCTION(std::cosf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float sin(float)", asFUNCTION(std::sinf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float tan(float)", asFUNCTION(std::tanf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float acos(float)", asFUNCTION(std::acosf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float asin(float)", asFUNCTION(std::asinf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float atan(float)", asFUNCTION(std::atanf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float atan2(float, float)", asFUNCTION(std::atan2f), asCALL_CDECL); ASSERT(result >= asSUCCESS); // Hyberbolic functions result = engine.RegisterGlobalFunction("float cosh(float)", asFUNCTION(std::coshf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float sinh(float)", asFUNCTION(std::sinhf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float tanh(float)", asFUNCTION(std::tanhf), asCALL_CDECL); ASSERT(result >= asSUCCESS); // Exponential and logarithmic functions result = engine.RegisterGlobalFunction("float log(float)", asFUNCTION(std::logf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float log10(float)", asFUNCTION(std::log10f), asCALL_CDECL); ASSERT(result >= asSUCCESS); // Power functions result = engine.RegisterGlobalFunction("float pow(float, float)", asFUNCTION(std::powf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("float sqrt(float)", asFUNCTION(std::sqrtf), asCALL_CDECL); ASSERT(result >= asSUCCESS); // Absolute value functions result = engine.RegisterGlobalFunction("float fabsf(float)", asFUNCTION(std::fabsf), asCALL_CDECL); ASSERT(result >= asSUCCESS); result = engine.RegisterGlobalFunction("int64 abs(int64)", asFUNCTION(std::llabs), asCALL_CDECL); ASSERT(result >= asSUCCESS); }
163.672474
323
0.691404
nyaki-HUN
83f3f8a87d7df2fb79e11988e0fab1b152b09aa3
1,958
cpp
C++
tests/containers/btree/test_btree_insert_find.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
tests/containers/btree/test_btree_insert_find.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
tests/containers/btree/test_btree_insert_find.cpp
hthetran/stxxl
7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7
[ "BSL-1.0" ]
null
null
null
/*************************************************************************** * tests/containers/btree/test_btree_insert_find.cpp * * Part of the STXXL. See http://stxxl.org * * Copyright (C) 2006 Roman Dementiev <[email protected]> * Copyright (C) 2018 Manuel Penschuck <[email protected]> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include "test_btree_common.h" int main(int argc, char* argv[]) { size_t nins; { die_with_message_if(argc < 2, "Usage: " << argv[0] << " #log_ins"); const auto log_nins = foxxll::atoi64(argv[1]); die_with_message_if(log_nins > 31, "This test can't do more than 2^31 operations, you requested 2^" << log_nins); nins = 1ULL << log_nins; } stxxl::vector<int> Values(nins); random_fill_vector(Values); btree_type BTree(1024 * 128, 1024 * 128); { LOG1 << "Inserting " << nins << " random values into btree"; for (auto it = Values.cbegin(); it != Values.cend(); ++it) BTree.insert({ *it, static_cast<payload_type>(*it + 1) }); LOG1 << "Number of elements in btree: " << BTree.size(); } { LOG1 << "Searching " << nins << " existing elements"; for (auto it = Values.cbegin(); it != Values.cend(); ++it) { btree_type::iterator bIt = BTree.find(*it); die_unless(bIt != BTree.end()); die_unless(bIt->first == *it); } } { LOG1 << "Searching " << nins << " non-existing elements"; for (auto it = Values.cbegin(); it != Values.cend(); ++it) { btree_type::iterator bIt = BTree.find(static_cast<payload_type>(*it + 1)); die_unless(bIt == BTree.end()); } } LOG1 << "Test passed."; return 0; }
34.350877
121
0.536261
hthetran
83f43a4b2d0b4d87c5f1eda0034a95df316aa789
495
cpp
C++
src/utility/general/timer.cpp
heiseish/DawnCpp
6bcde05109bce67cc6d44c23d57e0c4348439196
[ "Apache-2.0" ]
3
2020-08-11T07:55:16.000Z
2022-01-14T16:05:39.000Z
src/utility/general/timer.cpp
heiseish/DawnCpp
6bcde05109bce67cc6d44c23d57e0c4348439196
[ "Apache-2.0" ]
null
null
null
src/utility/general/timer.cpp
heiseish/DawnCpp
6bcde05109bce67cc6d44c23d57e0c4348439196
[ "Apache-2.0" ]
null
null
null
#include "timer.hpp" #include <chrono> namespace Dawn::Utility { //--------------------------------- time_t GetCurrentEpoch() { struct timeval tv; gettimeofday(&tv, nullptr); return tv.tv_sec; } //--------------------------------- unsigned long GetCurrentEpochMs() { struct timeval tv; gettimeofday(&tv, nullptr); return tv.tv_sec * 1000 + tv.tv_usec / 1000; } void Timer::Start() { _start = std::chrono::high_resolution_clock::now(); } } // namespace Dawn::Utility
20.625
75
0.581818
heiseish
83f73dac265e4cad27c1d8a0259b17b031cb89f3
576
hpp
C++
simsync/include/simsync/reports/criticality_stack.hpp
mariobadr/simsync-pmam
c541d2bf3a52eec8579e254a0300442bc3d6f1d4
[ "Apache-2.0" ]
null
null
null
simsync/include/simsync/reports/criticality_stack.hpp
mariobadr/simsync-pmam
c541d2bf3a52eec8579e254a0300442bc3d6f1d4
[ "Apache-2.0" ]
null
null
null
simsync/include/simsync/reports/criticality_stack.hpp
mariobadr/simsync-pmam
c541d2bf3a52eec8579e254a0300442bc3d6f1d4
[ "Apache-2.0" ]
null
null
null
#ifndef SIMSYNC_CRITICALITY_STACK_HPP #define SIMSYNC_CRITICALITY_STACK_HPP #include <simsync/reports/report.hpp> #include <map> namespace simsync { class system; class criticality_stack : public report { public: explicit criticality_stack(std::string const &output_file, const system &system); ~criticality_stack() override; void update(std::chrono::nanoseconds current_time, event *e) override; private: system const &m_system; std::chrono::nanoseconds m_last_time; std::map<int32_t, int64_t> m_criticality; }; } #endif //SIMSYNC_CRITICALITY_STACK_HPP
19.862069
83
0.779514
mariobadr
83f975c550da54f756f9bb2e3551ea8bd57af189
1,206
cpp
C++
code_snippets/Chapter09/chapter.9.7.1-problematic.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
170
2015-05-02T18:08:38.000Z
2018-07-31T11:35:17.000Z
code_snippets/Chapter09/chapter.9.7.1-problematic.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
7
2018-08-29T15:43:14.000Z
2021-09-23T21:56:49.000Z
code_snippets/Chapter09/chapter.9.7.1-problematic.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
105
2015-05-28T11:52:19.000Z
2018-07-17T14:11:25.000Z
// // This is example code from Chapter 9.7.1 "Argument types" of // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // //------------------------------------------------------------------------------ // simple Date (use Month type): class Date { public: enum Month { jan=1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec }; Date(int yy, Month mm, int dd) : y(yy), m(mm), d(dd) // check for valid date and initialize { // ... } private: int y; // year Month m; int d; // day }; //------------------------------------------------------------------------------ int main() { //Date d1(4,5,2005); // oops: Year 4, day 2005 //Date d2(2005,4,5); // April 5 or May 4? //Date dx1(1998, 4, 3); // error: 2nd argument not a Month //Date dx2(1998, 4, Date::mar); // error: 2nd argument not a Month Date dx2(4, Date::mar, 1998); // oops: run-time error: day 1998 //Date dx2(Date::mar, 4, 1998); // error: 2nd argument not a Month Date dx3(1998, Date::mar, 30); // ok return 0; } //------------------------------------------------------------------------------
28.046512
95
0.43864
TingeOGinge
86049ec1359af6d5974e5f2a52f9c36b65c8410a
2,917
cpp
C++
testsrc/clause_tests.cpp
sat-clique/cnfkit
280605ef29c95df3d5b349d54b2410451a2f5564
[ "X11" ]
null
null
null
testsrc/clause_tests.cpp
sat-clique/cnfkit
280605ef29c95df3d5b349d54b2410451a2f5564
[ "X11" ]
null
null
null
testsrc/clause_tests.cpp
sat-clique/cnfkit
280605ef29c95df3d5b349d54b2410451a2f5564
[ "X11" ]
null
null
null
#include <cnfkit/clause.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <array> #include <cstdint> using ::testing::Eq; namespace cnfkit { template <typename T> class add_member { private: T dummy; }; template <typename SizeType, typename... AdditionalBases> class alignas(8) configurable_test_clause : public clause<configurable_test_clause<SizeType, AdditionalBases...>, SizeType>, public AdditionalBases... { public: using base = clause<configurable_test_clause<SizeType, AdditionalBases...>, SizeType>; using typename base::size_type; using base::begin; using base::cbegin; using base::cend; using base::empty; using base::end; using base::size; explicit configurable_test_clause(size_t size) : base(size) {} }; template <typename ClauseType> class ClauseTests : public ::testing::Test { }; // clang-format off using TestClauseTypes = ::testing::Types< configurable_test_clause<uint8_t>, configurable_test_clause<uint16_t>, configurable_test_clause<uint32_t>, configurable_test_clause<uint64_t>, configurable_test_clause<uint8_t, add_member<uint8_t>>, configurable_test_clause<uint16_t, add_member<uint8_t>>, configurable_test_clause<uint32_t, add_member<uint8_t>>, configurable_test_clause<uint64_t, add_member<uint8_t>>, configurable_test_clause<uint8_t, add_member<uint32_t>>, configurable_test_clause<uint16_t, add_member<uint32_t>>, configurable_test_clause<uint32_t, add_member<uint32_t>>, configurable_test_clause<uint64_t, add_member<uint32_t>>, configurable_test_clause<uint8_t, add_member<std::array<uint8_t, 5>>>, configurable_test_clause<uint16_t, add_member<std::array<uint8_t, 5>>>, configurable_test_clause<uint32_t, add_member<std::array<uint8_t, 5>>>, configurable_test_clause<uint64_t, add_member<std::array<uint8_t, 5>>> >; // clang-format on TYPED_TEST_SUITE(ClauseTests, TestClauseTypes); TYPED_TEST(ClauseTests, LiteralAdressing) { using test_clause = TypeParam; alignas(test_clause) unsigned char buf[1024]; test_clause* clause = test_clause::base::construct_in(buf, 10); ASSERT_THAT(static_cast<void*>(clause), Eq(static_cast<void*>(buf))); uintptr_t const lits_begin_addr = reinterpret_cast<uintptr_t>(clause->begin()); EXPECT_THAT(lits_begin_addr, Eq(reinterpret_cast<uintptr_t>(buf) + sizeof(test_clause))); EXPECT_THAT(lits_begin_addr % alignof(lit), Eq(0)); uintptr_t const lits_end_addr = reinterpret_cast<uintptr_t>(clause->end()); EXPECT_THAT(lits_end_addr - lits_begin_addr, Eq(10 * sizeof(lit))); } TYPED_TEST(ClauseTests, LiteralsAreZeroInitialized) { using namespace cnfkit_literals; using test_clause = TypeParam; alignas(test_clause) unsigned char buf[1024]; test_clause* clause = test_clause::base::construct_in(buf, 10); for (lit const& literal : *clause) { EXPECT_THAT(literal, Eq(lit{var{0}, false})); } } }
29.765306
91
0.756256
sat-clique
8605112d9c5f9bf78d3e1656a8e9847225ef665f
637
hpp
C++
nd-coursework/books/cpp/C++Templates/tuples/pushfront.hpp
crdrisko/nd-grad
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
1
2020-09-26T12:38:55.000Z
2020-09-26T12:38:55.000Z
nd-coursework/books/cpp/C++Templates/tuples/pushfront.hpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
nd-coursework/books/cpp/C++Templates/tuples/pushfront.hpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
// Copyright (c) 2017 by Addison-Wesley, David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor. All rights reserved. // See the LICENSE file in the project root for more information. // // Name: pushfront.hpp // Author: crdrisko // Date: 11/07/2020-08:04:37 // Description: A metafunction for inserting a new element at the front of a tuple #ifndef PUSHFRONT_HPP #define PUSHFRONT_HPP #include "tuple.hpp" #include "tupletypelist.hpp" template<typename... Types, typename V> PushFront<Tuple<Types...>, V> pushFront(Tuple<Types...> const& tuple, V const& value) { return PushFront<Tuple<Types...>, V>(value, tuple); } #endif
28.954545
121
0.729984
crdrisko
860754f2a0285a3740195c1a3356b69a98973e17
3,353
cpp
C++
src/stalk_response.cpp
pykel/stalk
a51a0f4b9c005c058bcc4bce237aeb6c105b2c78
[ "BSL-1.0" ]
null
null
null
src/stalk_response.cpp
pykel/stalk
a51a0f4b9c005c058bcc4bce237aeb6c105b2c78
[ "BSL-1.0" ]
null
null
null
src/stalk_response.cpp
pykel/stalk
a51a0f4b9c005c058bcc4bce237aeb6c105b2c78
[ "BSL-1.0" ]
null
null
null
#include "stalk/stalk_response.h" #include "stalk/stalk_request.h" #include "stalk_request_impl.h" #include "stalk_response_impl.h" #include "stalk_field_convert.h" namespace Stalk { Response::Response() : impl(std::make_unique<ResponseImpl>()) { } Response::Response(const Request& request) : impl(std::make_unique<ResponseImpl>(request.impl->request)) { impl->response.keep_alive(request.impl->request.keep_alive()); } Response::~Response() = default; Response::Response(Response&& other) : impl(std::move(other.impl)) { } Response::Response(const Response& other) : impl(new ResponseImpl(*other.impl)) { } Response& Response::operator=(Response&& other) { impl = std::move(other.impl); return *this; } Response& Response::operator=(const Response& other) { impl.reset(new ResponseImpl(*other.impl)); return *this; } Response Response::build(const Request& req, Status status, const std::string& contentType, const std::string& body) { return Response(req) .status(status) .set(Field::content_type, contentType) .body(body); } Response Response::build(const Request& req, Status status, std::string&& contentType, std::string&& body) { return Response(req) .status(status) .set(Field::content_type, contentType) .body(body); } Response Response::build(const Request& req, Status status) { return Response(req).status(status); } Response& Response::set(Field name, const std::string& value) { impl->response.set(fieldToBeast(name), value); return *this; } Response& Response::set(Field name, std::string&& value) { impl->response.set(fieldToBeast(name), std::move(value)); return *this; } Response& Response::set(std::string_view name, const std::string& value) { impl->response.set(boost::string_view(name.data(), name.size()), value); return *this; } Response& Response::set(std::string_view name, std::string&& value) { impl->response.set(boost::string_view(name.data(), name.size()), std::move(value)); return *this; } std::string Response::get(Field name) { auto sv = impl->response.base()[fieldToBeast(name)]; return std::string(sv.data(), sv.data() + sv.size()); } Status Response::status() const { return static_cast<Status>(impl->response.result()); } Response& Response::status(unsigned s) { impl->response.result(static_cast<boost::beast::http::status>(s)); return *this; } Response& Response::status(Status s) { impl->response.result(static_cast<boost::beast::http::status>(s)); return *this; } bool Response::keepAlive() const { return impl->response.keep_alive(); } Response& Response::keepAlive(bool v) { impl->response.keep_alive(v); return *this; } const std::string& Response::body() const { return impl->response.body(); } std::string& Response::body() { return impl->response.body(); } Response& Response::body(std::string&& b) { impl->response.body() = std::move(b); impl->response.prepare_payload(); return *this; } Response& Response::body(const std::string& b) { impl->response.body() = b; impl->response.prepare_payload(); return *this; } std::ostream& operator<<(std::ostream& os, const Response& resp) { os << resp.impl->response; return os; } } // namespace Stalk
21.49359
116
0.670743
pykel
8615c18788c5a73c020e7170a20acdce2eccdc89
13,633
cpp
C++
Source/AllProjects/CIDKernel/Win32/CIDKernel_USB_Win32.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/CIDKernel/Win32/CIDKernel_USB_Win32.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/CIDKernel/Win32/CIDKernel_USB_Win32.cpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDKernel_USB_Win32.Cpp // // AUTHOR: Dean Roddey // // CREATED: 02/08/2004 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file provides some core support for interacting with USB and HID // devices. // // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "CIDKernel_.hpp" #pragma warning(push) #include <CodeAnalysis\Warnings.h> #pragma warning(disable : ALL_CODE_ANALYSIS_WARNINGS 26812) #include <setupapi.h> #pragma warning(pop) // // Some stuff we define ourself, because otherwise we'd have to bring in a // whole raft of device driver kit stuff. // extern "C" { #pragma CIDLIB_PACK(4) typedef struct _HIDP_PREPARSED_DATA * PHIDP_PREPARSED_DATA; typedef struct _HIDP_CAPS { USHORT Usage; USHORT UsagePage; USHORT InputReportByteLength; USHORT OutputReportByteLength; USHORT FeatureReportByteLength; USHORT Reserved[17]; USHORT NumberLinkCollectionNodes; USHORT NumberInputButtonCaps; USHORT NumberInputValueCaps; USHORT NumberInputDataIndices; USHORT NumberOutputButtonCaps; USHORT NumberOutputValueCaps; USHORT NumberOutputDataIndices; USHORT NumberFeatureButtonCaps; USHORT NumberFeatureValueCaps; USHORT NumberFeatureDataIndices; } HIDP_CAPS, *PHIDP_CAPS; typedef struct _HIDD_ATTRIBUTES { ULONG Size; USHORT VendorID; USHORT ProductID; USHORT VersionNumber; } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES; #pragma CIDLIB_POPPACK // // Some APIs we will call. We don't have the header, so we have to // provide the signatures ourself. // extern BOOLEAN __stdcall HidD_GetAttributes ( HANDLE HidDeviceObject , PHIDD_ATTRIBUTES Attributes ); extern void __stdcall HidD_GetHidGuid(struct _GUID *); extern BOOLEAN __stdcall HidD_GetPreparsedData ( HANDLE HidDeviceObject , PHIDP_PREPARSED_DATA* PreparsedData ); extern void __stdcall HidP_GetCaps ( PHIDP_PREPARSED_DATA PreparsedData , HIDP_CAPS* Capabilities ); } // --------------------------------------------------------------------------- // Local helpers // --------------------------------------------------------------------------- static tCIDLib::TBoolean bStringToGUID(const tCIDLib::TCh* const pszText, GUID& guidToFill) { // // Create the GUIID from the text version. The format of the id string // must be: // // {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} // // where X is a hex digit. The first is an long value (4 2 digit values), // then three shorts (2 2 digit values), then 2 and 6 individual bytes // (8 2 digit values.) The braces are optional, so it must be either 36 or // 38 characters. // const tCIDLib::TCard4 c4Len = TRawStr::c4StrLen(pszText); if ((c4Len != 36) && (c4Len != 38)) return kCIDLib::False; // // Make a copy of the string that we can mangle, and get rid of the // braces. // tCIDLib::TCh* pszGUID = TRawStr::pszReplicate(pszText); TArrayJanitor<tCIDLib::TCh> janGUID(pszGUID); if (c4Len == 38) { *(pszGUID + 37) = kCIDLib::chNull; pszGUID++; } // There must be a dash at 8, 13, 18, and 23 if ((pszGUID[8] != kCIDLib::chHyphenMinus) || (pszGUID[13] != kCIDLib::chHyphenMinus) || (pszGUID[18] != kCIDLib::chHyphenMinus) || (pszGUID[23] != kCIDLib::chHyphenMinus)) { return kCIDLib::False; } // Make it more convenient for us by upper casing it TRawStr::pszUpperCase(pszGUID); // Ok, put nulls in those places to create separate strings pszGUID[8] = kCIDLib::chNull; pszGUID[13] = kCIDLib::chNull; pszGUID[18] = kCIDLib::chNull; pszGUID[23] = kCIDLib::chNull; // Ok, fill in the GUID now, by converting the strings to binary tCIDLib::TBoolean bOk; tCIDLib::TCard4 c4Tmp; guidToFill.Data1 = TRawStr::c4AsBinary(pszGUID, bOk, tCIDLib::ERadices::Hex); if (!bOk) return kCIDLib::False; pszGUID += 9; c4Tmp = TRawStr::c4AsBinary(pszGUID, bOk, tCIDLib::ERadices::Hex); if (!bOk) return kCIDLib::False; guidToFill.Data2 = tCIDLib::TCard2(c4Tmp); pszGUID += 5; c4Tmp = TRawStr::c4AsBinary(pszGUID, bOk, tCIDLib::ERadices::Hex); if (!bOk) return kCIDLib::False; guidToFill.Data3 = tCIDLib::TCard2(c4Tmp); // // The next one gets stored as two bytes but for convenience we convert // it as a short. // pszGUID += 5; c4Tmp = TRawStr::c4AsBinary(pszGUID, bOk, tCIDLib::ERadices::Hex); if (!bOk) return kCIDLib::False; guidToFill.Data4[0] = tCIDLib::TCard1(c4Tmp >> 8); guidToFill.Data4[1] = tCIDLib::TCard1(c4Tmp & 0xFF); // // And now we have 6 2 digit bytes left to fill in the last 6 bytes // of Data4. There are no separators, so it's a little more of a pain // than it would be otherwise. // pszGUID += 5; for (tCIDLib::TCard4 c4Index = 0; c4Index < 6; c4Index++) { const tCIDLib::TCh ch1(*pszGUID++); const tCIDLib::TCh ch2(*pszGUID++); if (!TRawStr::bIsHexDigit(ch1) || !TRawStr::bIsHexDigit(ch2)) return kCIDLib::False; tCIDLib::TCard1 c1Val; if ((ch1 >= kCIDLib::chDigit0) && (ch1 <= kCIDLib::chDigit9)) c1Val = tCIDLib::TCard1(ch1 - kCIDLib::chDigit0); else c1Val = tCIDLib::TCard1(10 + (ch1 - kCIDLib::chLatin_A)); c1Val <<= 4; if ((ch2 >= kCIDLib::chDigit0) && (ch2 <= kCIDLib::chDigit9)) c1Val |= tCIDLib::TCard1(ch2 - kCIDLib::chDigit0); else c1Val |= tCIDLib::TCard1(10 + (ch2 - kCIDLib::chLatin_A)); guidToFill.Data4[2 + c4Index] = c1Val; } return kCIDLib::True; } // --------------------------------------------------------------------------- // USBDev namespace methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TKrnlUSBDev::bCheckForDevice(const tCIDLib::TCh* const pszDevId , const tCIDLib::TCard2 c2VendorId , const tCIDLib::TCard2 c2ProductId , tCIDLib::TBoolean& bFound) { // Assume worst case bFound = kCIDLib::False; // Set up the data structures we'll need for this SP_DEVICE_INTERFACE_DATA IntfInfo = {0}; IntfInfo.cbSize = sizeof(IntfInfo); HIDD_ATTRIBUTES Attrs = {0}; Attrs.Size = sizeof(Attrs); // // Try to convert the string id to a GUID that we'll need in order to // search for devices of that type. If bad, return false now. // GUID guidDev; if (!bStringToGUID(pszDevId, guidDev)) return kCIDLib::False; // And get the enumerator handle, only for devices actually present HDEVINFO hDevList = ::SetupDiGetClassDevs ( &guidDev, 0, 0, DIGCF_INTERFACEDEVICE | DIGCF_PRESENT ); if (!hDevList) { TKrnlError::SetLastHostError(::GetLastError()); return kCIDLib::False; } // Now loop through the devices till we find our guy, or fail tCIDLib::TCard4 c4Index = 0; bFound = kCIDLib::False; HANDLE hDevFl; while (1) { // // Break out when done. It could be an error as well, but we don't // distinguish. // if (!::SetupDiEnumDeviceInterfaces(hDevList, 0, &guidDev, c4Index++, &IntfInfo)) break; // Allocate the buffer for this one tCIDLib::TCard4 c4DetailSz = 0; tCIDLib::TCard1* pc1Buf = 0; ::SetupDiGetDeviceInterfaceDetail ( hDevList, &IntfInfo, 0, 0, &c4DetailSz, 0 ); if (!c4DetailSz) continue; // Point the details stucture pointer at it and set the size info hDevFl = 0; { pc1Buf = new tCIDLib::TCard1[c4DetailSz]; SP_DEVICE_INTERFACE_DETAIL_DATA* pDetails ( (SP_DEVICE_INTERFACE_DETAIL_DATA*)pc1Buf ); pDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); TArrayJanitor<tCIDLib::TCard1> janBuf(pc1Buf); // // Get the interface details, which gets us a path that we can // use to get the device attributes. // ::SetupDiGetDeviceInterfaceDetail ( hDevList, &IntfInfo, pDetails, c4DetailSz, 0, 0 ); // Temporarly open this device hDevFl = ::CreateFile ( pDetails->DevicePath , GENERIC_READ , FILE_SHARE_READ | FILE_SHARE_WRITE , 0 , OPEN_EXISTING , 0 , 0 ); } // Get the attrs. If it's our guy, break out ::HidD_GetAttributes(hDevFl, &Attrs); // And close it now that we have the info ::CloseHandle(hDevFl); if ((Attrs.VendorID == c2VendorId) && (Attrs.ProductID == c2ProductId)) { bFound = kCIDLib::True; break; } } // And now we can dump the device list enumerator ::SetupDiDestroyDeviceInfoList(hDevList); return kCIDLib::True; } tCIDLib::TBoolean TKrnlUSBDev::bFindHIDDev(const tCIDLib::TCard2 c2VendorId , const tCIDLib::TCard2 c2ProductId , tCIDLib::TCh* const pszToFill , const tCIDLib::TCard4 c4MaxChars , tCIDLib::TBoolean& bFound) { // Set up the data structures we'll need for this SP_DEVICE_INTERFACE_DATA IntfInfo = {0}; IntfInfo.cbSize = sizeof(IntfInfo); HIDD_ATTRIBUTES Attrs = {0}; Attrs.Size = sizeof(Attrs); // // Get the GUID for HID devices that we need to iterate the devices // available. // GUID guidHID; ::HidD_GetHidGuid(&guidHID); // And get the enumerator handle, only for devices actually present HDEVINFO hDevList = ::SetupDiGetClassDevs ( &guidHID , 0 , 0 , DIGCF_INTERFACEDEVICE | DIGCF_PRESENT ); if (!hDevList) { TKrnlError::SetLastHostError(::GetLastError()); return kCIDLib::False; } // Now loop through the devices till we find our guy, or fail tCIDLib::TCard4 c4Index = 0; bFound = kCIDLib::False; HANDLE hDevFl; while (1) { // // Break out when done. It could be an error as well, but we don't // distinguish. // if (!::SetupDiEnumDeviceInterfaces(hDevList, 0, &guidHID, c4Index++, &IntfInfo)) break; // Allocate the buffer for this one tCIDLib::TCard4 c4DetailSz = 0; tCIDLib::TCard1* pc1Buf = 0; ::SetupDiGetDeviceInterfaceDetail ( hDevList, &IntfInfo, 0, 0, &c4DetailSz, 0 ); if (!c4DetailSz) continue; // Point the details stucture pointer at it and set the size info { pc1Buf = new tCIDLib::TCard1[c4DetailSz]; SP_DEVICE_INTERFACE_DETAIL_DATA* pDetails ( (SP_DEVICE_INTERFACE_DETAIL_DATA*)pc1Buf ); pDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); TArrayJanitor<tCIDLib::TCard1> janBuf(pc1Buf); // // Get the interface details, which gets us a path that we can use // to get the device attributes. // ::SetupDiGetDeviceInterfaceDetail ( hDevList, &IntfInfo, pDetails, c4DetailSz, 0, 0 ); // Temporarly open this device hDevFl = ::CreateFile ( pDetails->DevicePath , GENERIC_READ , FILE_SHARE_READ | FILE_SHARE_WRITE , 0 , OPEN_EXISTING , 0 , 0 ); // Get the attrs. If it's our guy, break out ::HidD_GetAttributes(hDevFl, &Attrs); // And close it now that we have the info ::CloseHandle(hDevFl); if ((Attrs.VendorID == c2VendorId) && (Attrs.ProductID == c2ProductId)) { // Copy the device name back if we can, else it's an error if (TRawStr::c4StrLen(pDetails->DevicePath) > c4MaxChars) { TKrnlError::SetLastError(kKrnlErrs::errcData_InsufficientBuffer); return kCIDLib::False; } // We can handle it, so store it and clean up the buffer TRawStr::CopyStr(pszToFill, pDetails->DevicePath, c4MaxChars); bFound = kCIDLib::True; break; } } } // And now we can dump the device list enumerator ::SetupDiDestroyDeviceInfoList(hDevList); return kCIDLib::True; }
29.508658
88
0.561579
MarkStega
861860e17b8af61d1b88fe742ed7868aa8915591
3,079
hpp
C++
include/audio/mapping/AudioToneSweepMapping.hpp
Tyulis/ToyGB
841507fa19c320caa98b16eae2a6df0bc996ba51
[ "MIT" ]
null
null
null
include/audio/mapping/AudioToneSweepMapping.hpp
Tyulis/ToyGB
841507fa19c320caa98b16eae2a6df0bc996ba51
[ "MIT" ]
null
null
null
include/audio/mapping/AudioToneSweepMapping.hpp
Tyulis/ToyGB
841507fa19c320caa98b16eae2a6df0bc996ba51
[ "MIT" ]
null
null
null
#ifndef _AUDIO_MAPPING_AUDIOTONESWEEPMAPPING_HPP #define _AUDIO_MAPPING_AUDIOTONESWEEPMAPPING_HPP #include "audio/timing.hpp" #include "audio/mapping/AudioChannelMapping.hpp" #include "audio/mapping/AudioControlMapping.hpp" #include "core/hardware.hpp" #include "memory/Constants.hpp" #include "util/error.hpp" namespace toygb { /** Tone (square wave) channel with frequency sweep memory mapping and operation (channel 2) */ class AudioToneSweepMapping : public AudioChannelMapping { public: AudioToneSweepMapping(int channel, AudioControlMapping* control, AudioDebugMapping* debug, HardwareStatus* hardware); uint8_t get(uint16_t address); void set(uint16_t address, uint8_t value); // NR10 : Frequency sweep control uint8_t sweepPeriod; // Number of sweep frames between every sweep update (0-7) (register NR10, bits 4-6) bool sweepDirection; // Frequency sweep direction (0 = increase frequency, 1 = decrease) (register NR10, bit 3) uint8_t sweepShift; // Frequency sweep shift (0-7) (register NR10, bits 0-2) // NR11 : Sound pattern and length control uint8_t wavePatternDuty; // Select the wave pattern duty (0-3) (register NR11, bits 6-7) uint8_t length; // Sound length counter (0-64) (register NR11, bits 0-5) // NR12 : Volume envelope control uint8_t initialEnvelopeVolume; // Initial envelope volume value (0-15) (register NR12, bits 4-7) bool envelopeDirection; // Envelope direction (0 = decrease volume, 1 = increase) uint8_t envelopePeriod; // Envelope period (envelope volume is recalculated every `envelopePeriod` frames, 0 disables envelope) (register NR12, bits 0-2) // NR13 + NR14.0-2 : Sound frequency control uint16_t frequency; // The channel state is updated every 2*(2048 - `frequency`) // NR14 : Channel control bool enableLength; // Enables length counter operation (1 = enable, channel stops when length counter reaches zero, 0 = disable) (register NR14, bit 6) protected: void reset(); // Called when a channel restart is requested via NR14.7 uint16_t calculateFrequencySweep(); // Perform a sweep frequency calculation and overflow check // AudioChannelMapping overrides float buildSample(); void onPowerOn(); void onPowerOff(); void onUpdate(); void onLengthFrame(); void onSweepFrame(); void onEnvelopeFrame(); int m_envelopeVolume; // Current volume envelope value uint16_t m_sweepFrequency; // Current sound frequency, with sweep int m_dutyPointer; // Current position in the wave duty int m_baseTimerCounter; // Counts cycles for the recalculation period int m_envelopeFrameCounter; // Counts envelope frames for the envelope update period int m_sweepFrameCounter; // Counts sweep frames for the sweep update period bool m_sweepEnabled; // Internal sweep enable frag bool m_sweepNegateCalculated; // Whether a sweep calculation in negate (decreasing frequency) mode has already been calculated since the last channel restart }; } #endif
45.955224
164
0.733355
Tyulis
861dd403d17dffa7ec09edea3f099cda24d0bee7
3,293
hpp
C++
include/paal/utils/read_rows.hpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
include/paal/utils/read_rows.hpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
include/paal/utils/read_rows.hpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
1
2021-02-24T06:23:56.000Z
2021-02-24T06:23:56.000Z
//======================================================================= // Copyright (c) 2015 // // 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 read_rows.hpp * @brief * @author Tomasz Strozak * @version 1.0 * @date 2015-07-23 */ #ifndef PAAL_READ_ROWS_HPP #define PAAL_READ_ROWS_HPP #include "paal/utils/functors.hpp" #include "paal/utils/system_message.hpp" #include <boost/range/size.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/range/istream_range.hpp> #include <cassert> #include <istream> #include <string> #include <sstream> #include <vector> #include <list> namespace paal { /** * @brief reads up to max_rows_to_read rows of size row_size * * @tparam RowType * @tparam ShouldIgnoreBadRow * @param input_stream * @param rows * @param row_size * @param max_rows_to_read * @param should_ignore_bad_row */ template <typename CoordinateType, typename RowType = std::vector<CoordinateType>, typename ShouldIgnoreBadRow = utils::always_true> void read_rows(std::istream &input_stream, std::vector<RowType> &rows, std::size_t row_size, std::size_t max_rows_to_read, ShouldIgnoreBadRow &&should_ignore_bad_row = ShouldIgnoreBadRow{}) { std::string line; RowType row; row.reserve(row_size); while ((max_rows_to_read--) && std::getline(input_stream, line)) { row.clear(); std::stringstream row_stream(line); boost::copy(boost::istream_range<CoordinateType>(row_stream), std::back_inserter(row)); if((!row_stream.bad() && row_size == boost::size(row)) || !should_ignore_bad_row(line)) { rows.emplace_back(row); } } } /** * @brief reads up to max_rows_to_read rows, size is determine by first row * * @tparam CoordinateType * @tparam RowType * @tparam ShouldIgnoreBadRow * @tparam FailureMessage * @param input_stream * @param rows * @param max_rows_to_read * @param should_ignore_bad_row * @param failure_message */ template <typename CoordinateType, typename RowType = std::vector<CoordinateType>, typename ShouldIgnoreBadRow = utils::always_true, typename FailureMessage = utils::failure_message> void read_rows_first_row_size(std::istream &input_stream, std::vector<RowType> &rows, std::size_t max_rows_to_read, ShouldIgnoreBadRow &&should_ignore_bad_row = ShouldIgnoreBadRow{}, FailureMessage &&failure_message = FailureMessage{}) { if(!input_stream.good()) { failure_message("Input stream is broken"); } read_rows<CoordinateType>(input_stream, rows, 0, 1, utils::always_false{}); if(rows.empty()) { failure_message("Empty input data"); } std::size_t const row_size = boost::size(rows.front()); if(row_size <= 0) { failure_message("Empty first row"); } read_rows<CoordinateType>(input_stream, rows, row_size, max_rows_to_read - 1, std::forward<ShouldIgnoreBadRow>(should_ignore_bad_row)); } } //! paal #endif /* PAAL_READ_ROWS_HPP */
29.401786
139
0.648952
Kommeren
861dead9180f36f69ddbb2201a2a5cb260e705d8
80
cpp
C++
Sources/LibRT/source/RTMaths.cpp
Rominitch/MouCaLab
d8c24de479b1bc11509df8456e0071d394fbeab9
[ "Unlicense" ]
null
null
null
Sources/LibRT/source/RTMaths.cpp
Rominitch/MouCaLab
d8c24de479b1bc11509df8456e0071d394fbeab9
[ "Unlicense" ]
null
null
null
Sources/LibRT/source/RTMaths.cpp
Rominitch/MouCaLab
d8c24de479b1bc11509df8456e0071d394fbeab9
[ "Unlicense" ]
null
null
null
#include "Dependencies.h" #include "LibRT/include/RTMaths.h" namespace RT { }
10
34
0.725
Rominitch
8621b0db7d2de6ad6421e1f6a860765f27e2fc13
10,582
cpp
C++
src/diffusion/DiffusionEquation.cpp
WeiqunZhang/incflo
d72eb6e3c387704d06ceee686596337e5e9711d3
[ "BSD-3-Clause" ]
null
null
null
src/diffusion/DiffusionEquation.cpp
WeiqunZhang/incflo
d72eb6e3c387704d06ceee686596337e5e9711d3
[ "BSD-3-Clause" ]
null
null
null
src/diffusion/DiffusionEquation.cpp
WeiqunZhang/incflo
d72eb6e3c387704d06ceee686596337e5e9711d3
[ "BSD-3-Clause" ]
null
null
null
#include <AMReX_EBFArrayBox.H> #include <AMReX_EBMultiFabUtil.H> #include <AMReX_MultiFabUtil.H> #include <AMReX_ParmParse.H> #include <AMReX_Vector.H> #include <DiffusionEquation.H> #include <diffusion_F.H> #include <constants.H> using namespace amrex; // // Constructor: // We set up everything which doesn't change between timesteps here // DiffusionEquation::DiffusionEquation(AmrCore* _amrcore, Vector<std::unique_ptr<EBFArrayBoxFactory>>* _ebfactory, Vector<std::unique_ptr<IArrayBox>>& bc_ilo, Vector<std::unique_ptr<IArrayBox>>& bc_ihi, Vector<std::unique_ptr<IArrayBox>>& bc_jlo, Vector<std::unique_ptr<IArrayBox>>& bc_jhi, Vector<std::unique_ptr<IArrayBox>>& bc_klo, Vector<std::unique_ptr<IArrayBox>>& bc_khi, int _nghost, Real _cyl_speed) { // Get inputs from ParmParse readParameters(); if(verbose > 0) { amrex::Print() << "Constructing DiffusionEquation class" << std::endl; } // Set AmrCore and ebfactory based on input, fetch some data needed in constructor amrcore = _amrcore; ebfactory = _ebfactory; nghost = _nghost; Vector<Geometry> geom = amrcore->Geom(); Vector<BoxArray> grids = amrcore->boxArray(); Vector<DistributionMapping> dmap = amrcore->DistributionMap(); int max_level = amrcore->maxLevel(); // Cylinder speed cyl_speed = _cyl_speed; // Whole domain Box domain(geom[0].Domain()); // The boundary conditions need only be set at level 0 set_diff_bc(bc_lo, bc_hi, domain.loVect(), domain.hiVect(), &nghost, bc_ilo[0]->dataPtr(), bc_ihi[0]->dataPtr(), bc_jlo[0]->dataPtr(), bc_jhi[0]->dataPtr(), bc_klo[0]->dataPtr(), bc_khi[0]->dataPtr()); // Resize and reset data b.resize(max_level + 1); phi.resize(max_level + 1); rhs.resize(max_level + 1); ueb.resize(max_level + 1); veb.resize(max_level + 1); for(int lev = 0; lev <= max_level; lev++) { for(int dir = 0; dir < AMREX_SPACEDIM; dir++) { BoxArray edge_ba = grids[lev]; edge_ba.surroundingNodes(dir); b[lev][dir].reset(new MultiFab(edge_ba, dmap[lev], 1, nghost, MFInfo(), *(*ebfactory)[lev])); } phi[lev].reset(new MultiFab(grids[lev], dmap[lev], 1, nghost, MFInfo(), *(*ebfactory)[lev])); rhs[lev].reset(new MultiFab(grids[lev], dmap[lev], 1, nghost, MFInfo(), *(*ebfactory)[lev])); ueb[lev].reset(new MultiFab(grids[lev], dmap[lev], 1, nghost, MFInfo(), *(*ebfactory)[lev])); veb[lev].reset(new MultiFab(grids[lev], dmap[lev], 1, nghost, MFInfo(), *(*ebfactory)[lev])); } // Fill the Dirichlet values on the EB surface for(int lev = 0; lev <= max_level; lev++) { // Get EB normal vector const amrex::MultiCutFab* bndrynormal; bndrynormal = &((*ebfactory)[lev] -> getBndryNormal()); #ifdef _OPENMP #pragma omp parallel if (Gpu::notInLaunchRegion()) #endif for(MFIter mfi(*ueb[lev], TilingIfNotGPU()); mfi.isValid(); ++mfi) { // Tilebox Box bx = mfi.tilebox(); // This is to check efficiently if this tile contains any eb stuff const EBFArrayBox& ueb_fab = static_cast<EBFArrayBox const&>((*ueb[lev])[mfi]); const EBCellFlagFab& flags = ueb_fab.getEBCellFlagFab(); if (flags.getType(bx) == FabType::covered || flags.getType(bx) == FabType::regular) { (*ueb[lev])[mfi].setVal(0.0, bx); (*veb[lev])[mfi].setVal(0.0, bx); } else { const auto& ueb_arr = ueb[lev]->array(mfi); const auto& veb_arr = veb[lev]->array(mfi); const auto& nrm_fab = bndrynormal->array(mfi); for(int i = bx.smallEnd(0); i <= bx.bigEnd(0); i++) for(int j = bx.smallEnd(1); j <= bx.bigEnd(1); j++) for(int k = bx.smallEnd(2); k <= bx.bigEnd(2); k++) { Real theta = atan2(-nrm_fab(i,j,k,1), -nrm_fab(i,j,k,0)); ueb_arr(i,j,k) = cyl_speed * sin(theta); veb_arr(i,j,k) = - cyl_speed * cos(theta); } } } } // Define the matrix. LPInfo info; info.setMaxCoarseningLevel(mg_max_coarsening_level); matrix.define(geom, grids, dmap, info, GetVecOfConstPtrs(*ebfactory)); // It is essential that we set MaxOrder to 2 if we want to use the standard // phi(i)-phi(i-1) approximation for the gradient at Dirichlet boundaries. // The solver's default order is 3 and this uses three points for the gradient. matrix.setMaxOrder(2); // LinOpBCType Definitions are in amrex/Src/Boundary/AMReX_LO_BCTYPES.H matrix.setDomainBC({(LinOpBCType) bc_lo[0], (LinOpBCType) bc_lo[1], (LinOpBCType) bc_lo[2]}, {(LinOpBCType) bc_hi[0], (LinOpBCType) bc_hi[1], (LinOpBCType) bc_hi[2]}); } DiffusionEquation::~DiffusionEquation() { } void DiffusionEquation::readParameters() { ParmParse pp("diffusion"); pp.query("verbose", verbose); pp.query("mg_verbose", mg_verbose); pp.query("mg_cg_verbose", mg_cg_verbose); pp.query("mg_max_iter", mg_max_iter); pp.query("mg_cg_maxiter", mg_cg_maxiter); pp.query("mg_max_fmg_iter", mg_max_fmg_iter); pp.query("mg_max_coarsening_level", mg_max_coarsening_level); pp.query("mg_rtol", mg_rtol); pp.query("mg_atol", mg_atol); pp.query("bottom_solver_type", bottom_solver_type); } void DiffusionEquation::updateInternals(AmrCore* amrcore_in, Vector<std::unique_ptr<EBFArrayBoxFactory>>* ebfactory_in) { // This must be implemented when we want dynamic meshing // amrex::Print() << "ERROR: DiffusionEquation::updateInternals() not yet implemented" << std::endl; amrex::Abort(); } // // Solve the matrix equation // void DiffusionEquation::solve(Vector<std::unique_ptr<MultiFab>>& vel, const Vector<std::unique_ptr<MultiFab>>& ro, const Vector<std::unique_ptr<MultiFab>>& eta, Real dt) { BL_PROFILE("DiffusionEquation::solve"); // Update the coefficients of the matrix going into the solve based on the current state of the // simulation. Recall that the relevant matrix is // // alpha a - beta div ( b grad ) <---> rho - dt div ( eta grad ) // // So the constants and variable coefficients are: // // alpha: 1 // beta: dt // a: ro // b: eta // Set alpha and beta matrix.setScalars(1.0, dt); for(int lev = 0; lev <= amrcore->finestLevel(); lev++) { // Compute the spatially varying b coefficients (on faces) to equal the apparent viscosity average_cellcenter_to_face(GetArrOfPtrs(b[lev]), *eta[lev], amrcore->Geom(lev)); for(int dir = 0; dir < AMREX_SPACEDIM; dir++) { b[lev][dir]->FillBoundary(amrcore->Geom(lev).periodicity()); } // This sets the coefficients matrix.setACoeffs(lev, (*ro[lev])); matrix.setBCoeffs(lev, GetArrOfConstPtrs(b[lev])); } if(verbose > 0) { amrex::Print() << "Diffusing velocity..." << std::endl; } // Loop over the velocity components for(int dir = 0; dir < AMREX_SPACEDIM; dir++) { for(int lev = 0; lev <= amrcore->finestLevel(); lev++) { // Set the right hand side to equal rho rhs[lev]->copy(*ro[lev], 0, 0, 1, nghost, nghost); // Multiply rhs by vel(dir) to get momentum // Note that vel holds the updated velocity: // // u_old + dt ( - u grad u + div ( eta (grad u)^T ) / rho - grad p / rho + gravity ) // MultiFab::Multiply((*rhs[lev]), (*vel[lev]), dir, 0, 1, nghost); // By this point we must have filled the Dirichlet values of phi stored in ghost cells phi[lev]->copy(*vel[lev], dir, 0, 1, nghost, nghost); phi[lev]->FillBoundary(amrcore->Geom(lev).periodicity()); matrix.setLevelBC(lev, GetVecOfConstPtrs(phi)[lev]); // This sets the coefficient on the wall and defines the wall as a Dirichlet bc if(cyl_speed > 0.0 && dir == 0) { matrix.setEBDirichlet(lev, *ueb[lev], *eta[lev]); } else if(cyl_speed > 0.0 && dir == 1) { matrix.setEBDirichlet(lev, *veb[lev], *eta[lev]); } else { matrix.setEBHomogDirichlet(lev, *eta[lev]); } } MLMG solver(matrix); setSolverSettings(solver); solver.solve(GetVecOfPtrs(phi), GetVecOfConstPtrs(rhs), mg_rtol, mg_atol); for(int lev = 0; lev <= amrcore->finestLevel(); lev++) { phi[lev]->FillBoundary(amrcore->Geom(lev).periodicity()); vel[lev]->copy(*phi[lev], 0, dir, 1, nghost, nghost); } if(verbose > 0) { amrex::Print() << " done!" << std::endl; } } } // // Set the user-supplied settings for the MLMG solver // (this must be done every time step, since MLMG is created after updating matrix // void DiffusionEquation::setSolverSettings(MLMG& solver) { // The default bottom solver is BiCG if(bottom_solver_type == "smoother") { solver.setBottomSolver(MLMG::BottomSolver::smoother); } else if(bottom_solver_type == "hypre") { solver.setBottomSolver(MLMG::BottomSolver::hypre); } // Maximum iterations for MultiGrid / ConjugateGradients solver.setMaxIter(mg_max_iter); solver.setMaxFmgIter(mg_max_fmg_iter); solver.setCGMaxIter(mg_cg_maxiter); // Verbosity for MultiGrid / ConjugateGradients solver.setVerbose(mg_verbose); solver.setCGVerbose(mg_cg_verbose); // This ensures that ghost cells of phi are correctly filled when returned from the solver solver.setFinalFillBC(true); }
35.871186
101
0.570214
WeiqunZhang
8623a3ff5ba52ff9debcee4a9db96c83d7db1876
9,490
cpp
C++
src/tree_gui.cpp
trademarks/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
8
2016-10-21T09:01:43.000Z
2021-05-31T06:32:14.000Z
src/tree_gui.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
null
null
null
src/tree_gui.cpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
4
2017-05-16T00:15:58.000Z
2020-08-06T01:46:31.000Z
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD 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. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file tree_gui.cpp GUIs for building trees. */ #include "stdafx.h" #include "window_gui.h" #include "gfx_func.h" #include "tilehighlight_func.h" #include "company_func.h" #include "company_base.h" #include "command_func.h" #include "sound_func.h" #include "tree_map.h" #include "table/sprites.h" #include "table/strings.h" #include "table/tree_land.h" void PlaceTreesRandomly(); /** Widget definitions for the build trees window. */ enum BuildTreesWidgets { BTW_TYPE_11, BTW_TYPE_12, BTW_TYPE_13, BTW_TYPE_14, BTW_TYPE_21, BTW_TYPE_22, BTW_TYPE_23, BTW_TYPE_24, BTW_TYPE_31, BTW_TYPE_32, BTW_TYPE_33, BTW_TYPE_34, BTW_TYPE_RANDOM, BTW_MANY_RANDOM, }; /** * The build trees window. */ class BuildTreesWindow : public Window { uint16 base; ///< Base tree number used for drawing the window. uint16 count; ///< Number of different trees available. TreeType tree_to_plant; ///< Tree number to plant, \c TREE_INVALID for a random tree. public: BuildTreesWindow(const WindowDesc *desc, WindowNumber window_number) : Window() { this->InitNested(desc, window_number); ResetObjectToPlace(); } virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) { if (widget != BTW_MANY_RANDOM) return; if (_game_mode != GM_EDITOR) { size->width = 0; size->height = 0; } } virtual void OnPaint() { this->OnInvalidateData(0); this->DrawWidgets(); } virtual void DrawWidget(const Rect &r, int widget) const { static const PalSpriteID tree_sprites[] = { { 0x655, PAL_NONE }, { 0x663, PAL_NONE }, { 0x678, PAL_NONE }, { 0x62B, PAL_NONE }, { 0x647, PAL_NONE }, { 0x639, PAL_NONE }, { 0x64E, PAL_NONE }, { 0x632, PAL_NONE }, { 0x67F, PAL_NONE }, { 0x68D, PAL_NONE }, { 0x69B, PAL_NONE }, { 0x6A9, PAL_NONE }, { 0x6AF, PAL_NONE }, { 0x6D2, PAL_NONE }, { 0x6D9, PAL_NONE }, { 0x6C4, PAL_NONE }, { 0x6CB, PAL_NONE }, { 0x6B6, PAL_NONE }, { 0x6BD, PAL_NONE }, { 0x6E0, PAL_NONE }, { 0x72E, PAL_NONE }, { 0x734, PAL_NONE }, { 0x74A, PAL_NONE }, { 0x74F, PAL_NONE }, { 0x76B, PAL_NONE }, { 0x78F, PAL_NONE }, { 0x788, PAL_NONE }, { 0x77B, PAL_NONE }, { 0x75F, PAL_NONE }, { 0x774, PAL_NONE }, { 0x720, PAL_NONE }, { 0x797, PAL_NONE }, { 0x79E, PAL_NONE }, { 0x7A5, PALETTE_TO_GREEN }, { 0x7AC, PALETTE_TO_RED }, { 0x7B3, PAL_NONE }, { 0x7BA, PAL_NONE }, { 0x7C1, PALETTE_TO_RED, }, { 0x7C8, PALETTE_TO_PALE_GREEN }, { 0x7CF, PALETTE_TO_YELLOW }, { 0x7D6, PALETTE_TO_RED } }; if (widget < BTW_TYPE_11 || widget > BTW_TYPE_34 || widget - BTW_TYPE_11 >= this->count) return; int i = this->base + widget - BTW_TYPE_11; DrawSprite(tree_sprites[i].sprite, tree_sprites[i].pal, (r.left + r.right) / 2, r.bottom - 7); } virtual void OnClick(Point pt, int widget, int click_count) { switch (widget) { case BTW_TYPE_11: case BTW_TYPE_12: case BTW_TYPE_13: case BTW_TYPE_14: case BTW_TYPE_21: case BTW_TYPE_22: case BTW_TYPE_23: case BTW_TYPE_24: case BTW_TYPE_31: case BTW_TYPE_32: case BTW_TYPE_33: case BTW_TYPE_34: if (widget - BTW_TYPE_11 >= this->count) break; if (HandlePlacePushButton(this, widget, SPR_CURSOR_TREE, HT_RECT)) { this->tree_to_plant = (TreeType)(this->base + widget - BTW_TYPE_11); } break; case BTW_TYPE_RANDOM: // tree of random type. if (HandlePlacePushButton(this, BTW_TYPE_RANDOM, SPR_CURSOR_TREE, HT_RECT)) { this->tree_to_plant = TREE_INVALID; } break; case BTW_MANY_RANDOM: // place trees randomly over the landscape this->LowerWidget(BTW_MANY_RANDOM); this->flags4 |= WF_TIMEOUT_BEGIN; SndPlayFx(SND_15_BEEP); PlaceTreesRandomly(); MarkWholeScreenDirty(); break; } } virtual void OnPlaceObject(Point pt, TileIndex tile) { VpStartPlaceSizing(tile, VPM_X_AND_Y_LIMITED, DDSP_PLANT_TREES); VpSetPlaceSizingLimit(20); } virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt) { VpSelectTilesWithMethod(pt.x, pt.y, select_method); } virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile) { if (pt.x != -1 && select_proc == DDSP_PLANT_TREES) { DoCommandP(end_tile, this->tree_to_plant, start_tile, CMD_PLANT_TREE | CMD_MSG(STR_ERROR_CAN_T_PLANT_TREE_HERE)); } } /** * Some data on this window has become invalid. * @param data Information about the changed data. * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details. */ virtual void OnInvalidateData(int data = 0, bool gui_scope = true) { if (!gui_scope) return; this->base = _tree_base_by_landscape[_settings_game.game_creation.landscape]; this->count = _tree_count_by_landscape[_settings_game.game_creation.landscape]; } virtual void OnTimeout() { this->RaiseWidget(BTW_MANY_RANDOM); this->SetWidgetDirty(BTW_MANY_RANDOM); } virtual void OnPlaceObjectAbort() { this->RaiseButtons(); } }; static const NWidgetPart _nested_build_trees_widgets[] = { NWidget(NWID_HORIZONTAL), NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN), NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_PLANT_TREE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS), NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN), NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN), EndContainer(), NWidget(WWT_PANEL, COLOUR_DARK_GREEN), NWidget(NWID_SPACER), SetMinimalSize(0, 2), NWidget(NWID_HORIZONTAL), NWidget(NWID_SPACER), SetMinimalSize(2, 0), NWidget(NWID_VERTICAL), NWidget(NWID_HORIZONTAL), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_11), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_12), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_13), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_14), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(0, 1), NWidget(NWID_HORIZONTAL), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_21), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_22), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_23), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_24), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(0, 1), NWidget(NWID_HORIZONTAL), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_31), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_32), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_33), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(1, 0), NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_34), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP), EndContainer(), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(0, 1), NWidget(WWT_TEXTBTN, COLOUR_GREY, BTW_TYPE_RANDOM), SetMinimalSize(139, 12), SetDataTip(STR_TREES_RANDOM_TYPE, STR_TREES_RANDOM_TYPE_TOOLTIP), NWidget(NWID_SPACER), SetMinimalSize(0, 1), NWidget(WWT_TEXTBTN, COLOUR_GREY, BTW_MANY_RANDOM), SetMinimalSize(139, 12), SetDataTip(STR_TREES_RANDOM_TREES_BUTTON, STR_TREES_RANDOM_TREES_TOOLTIP), NWidget(NWID_SPACER), SetMinimalSize(0, 2), EndContainer(), NWidget(NWID_SPACER), SetMinimalSize(2, 0), EndContainer(), EndContainer(), }; static const WindowDesc _build_trees_desc( WDP_AUTO, 0, 0, WC_BUILD_TREES, WC_NONE, WDF_CONSTRUCTION, _nested_build_trees_widgets, lengthof(_nested_build_trees_widgets) ); void ShowBuildTreesToolbar() { if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return; AllocateWindowDescFront<BuildTreesWindow>(&_build_trees_desc, 0); }
38.421053
185
0.73235
trademarks
8628075e4c6e8a0c045e8e24d135bb3e29866d3a
15,184
cpp
C++
example-pix2pix/src/example-pix2pix.cpp
marcel303/ofxMSATensorFlow
512a6e9a929e397c0bddf8bf86ea7521a22dd593
[ "Apache-2.0" ]
481
2016-01-28T22:05:07.000Z
2022-03-07T23:29:10.000Z
example-pix2pix/src/example-pix2pix.cpp
marcel303/ofxMSATensorFlow
512a6e9a929e397c0bddf8bf86ea7521a22dd593
[ "Apache-2.0" ]
37
2016-01-29T02:18:33.000Z
2020-03-24T17:36:05.000Z
example-pix2pix/src/example-pix2pix.cpp
marcel303/ofxMSATensorFlow
512a6e9a929e397c0bddf8bf86ea7521a22dd593
[ "Apache-2.0" ]
110
2016-01-29T14:00:39.000Z
2020-11-22T14:20:56.000Z
/* pix2pix (Image-to-Image Translation with Conditional Adversarial Nets). An accessible explanation can be found [here](https://phillipi.github.io/pix2pix/) and [here](https://affinelayer.com/pix2pix/). The network basically learns to map from one image to another. E.g. in the example you draw in the left viewport, and it generates the image in the right viewport. I'm supplying three pretrained models from the original paper: cityscapes, building facades, and maps. And a model I trained on [150 art collections from around the world](https://commons.wikimedia.org/wiki/Category:Google_Art_Project_works_by_collection). Models are trained and saved in python with [this code](https://github.com/memo/pix2pix-tensorflow) (which is based on [this](https://github.com/affinelayer/pix2pix-tensorflow) tensorflow implementation, which is based on the original [torch implementation](https://phillipi.github.io/pix2pix/)), and loaded in openframeworks for prediction. */ #include "ofMain.h" #include "ofxMSATensorFlow.h" //-------------------------------------------------------------- //-------------------------------------------------------------- class ofApp : public ofBaseApp { public: // a simple wrapper for a simple predictor model with variable number of inputs and outputs msa::tf::SimpleModel model; // a bunch of properties of the models // ideally should read from disk and vary with the model // but trying to keep the code minimal so hardcoding them since they're the same for all models const int input_shape[2] = {256, 256}; // dimensions {height, width} for input image const int output_shape[2] = {256, 256}; // dimensions {height, width} for output image const ofVec2f input_range = {-1, 1}; // range of values {min, max} that model expects for input const ofVec2f output_range = {-1, 1}; // range of values {min, max} that model outputs const string input_op_name = "generator/generator_inputs"; // name of op to feed input to const string output_op_name = "generator/generator_outputs"; // name of op to fetch output from // fbo for drawing into (will be fed to model) ofFbo fbo; // images in and out of model // preallocating these to save allocating them every frame ofFloatImage img_in; // input to the model (read from fbo) ofFloatImage img_out; // output from the model // model file management ofDirectory models_dir; // data/models folder which contains subfolders for each model int cur_model_index = 0; // which model (i.e. folder) we're currently using // color management for drawing vector<ofColor> colors; // contains color palette to be used for drawing (loaded from data/models/XYZ/palette.txt) const int palette_draw_size = 50; int draw_color_index = 0; ofColor draw_color; // other vars bool do_auto_run = true; // auto run every frame int draw_mode = 0; // draw vs boxes int draw_radius = 10; ofVec2f mousePressPos; //-------------------------------------------------------------- void setup() { ofSetColor(255); ofBackground(0); ofSetVerticalSync(true); ofSetLogLevel(OF_LOG_VERBOSE); ofSetFrameRate(60); // scan models dir models_dir.listDir("models"); if(models_dir.size()==0) { ofLogError() << "Couldn't find models folder." << msa::tf::missing_data_error(); assert(false); ofExit(1); } models_dir.sort(); load_model_index(0); // load first model } //-------------------------------------------------------------- // Load graph (model trained in and exported from python) by folder NAME, and initialise session void load_model(string model_dir) { ofLogVerbose() << "loading model " << model_dir; // init the model // note that it expects arrays for input op names and output op names, so just use {} model.setup(ofFilePath::join(model_dir, "graph_frz.pb"), {input_op_name}, {output_op_name}); if(! model.is_loaded()) { ofLogError() << "Model init error." << msa::tf::missing_data_error(); assert(false); ofExit(1); } // init tensor for input. shape should be: {batch size, image height, image width, number of channels} // (ideally the SimpleModel graph loader would read this info from the graph_def and call this internally) model.init_inputs(tensorflow::DT_FLOAT, {1, input_shape[0], input_shape[1], 3}); // allocate fbo and images with correct dimensions, and no alpha channel ofLogVerbose() << "allocating fbo and images " << input_shape; fbo.allocate(input_shape[1], input_shape[0], GL_RGB); img_in.allocate(input_shape[1], input_shape[0], OF_IMAGE_COLOR); img_out.allocate(output_shape[1], output_shape[0], OF_IMAGE_COLOR); // load test image ofLogVerbose() << "loading test image"; ofImage img; img.load(ofFilePath::join(model_dir, "test_image.png")); if(img.isAllocated()) { fbo.begin(); ofSetColor(255); img.draw(0, 0, fbo.getWidth(), fbo.getHeight()); fbo.end(); } else { ofLogError() << "Test image not found"; } // load color palette for drawing ofLogVerbose() << "loading color palette"; colors.clear(); ofBuffer buf; buf = ofBufferFromFile(ofFilePath::join(model_dir, "/palette.txt")); if(buf.size()>0) { for(const auto& line : buf.getLines()) { ofLogVerbose() << line; if(line.size() == 6) // if valid hex code colors.push_back(ofColor::fromHex(ofHexToInt(line))); } draw_color_index = 0; if(colors.size() > 0) draw_color = colors[0]; } else { ofLogError() << "Palette info not found"; } // load default brush info ofLogVerbose() << "loading default brush info"; buf = ofBufferFromFile(ofFilePath::join(model_dir, "/default_brush.txt")); if(buf.size()>0) { auto str_info = buf.getFirstLine(); ofLogVerbose() << str_info; auto str_infos = ofSplitString(str_info, " ", true, true); if(str_infos[0]=="draw") draw_mode = 0; else if(str_infos[0]=="box") draw_mode = 1; else ofLogError() << "Unknown draw mode: " << str_infos[0]; draw_radius = ofToInt(str_infos[1]); } else { ofLogError() << "Default brush info not found"; } } //-------------------------------------------------------------- // Load model by folder INDEX void load_model_index(int index) { cur_model_index = ofClamp(index, 0, models_dir.size()-1); load_model(models_dir.getPath(cur_model_index)); } //-------------------------------------------------------------- // draw image or fbo etc with border and label // typename T must have draw(x,y), isAllocated(), getWidth(), getHeight() template <typename T> bool drawImage(const T& img, string label) { if(img.isAllocated()) { ofSetColor(255); ofFill(); img.draw(0, 0); // draw border ofNoFill(); ofSetColor(200); ofSetLineWidth(1); ofDrawRectangle(0, 0, img.getWidth(), img.getHeight()); // draw label ofDrawBitmapString(label, 10, img.getHeight()+15); ofTranslate(img.getWidth(), 0); return true; } return false; } //-------------------------------------------------------------- void draw() { // read from fbo into img_in fbo.readToPixels(img_in.getPixels()); // img_in.update(); // update so we can draw if need be (useful for debuging) // run model on it if(do_auto_run) model.run_image_to_image(img_in, img_out, input_range, output_range); // DISPLAY STUFF stringstream str; str << ofGetFrameRate() << endl; str << endl; str << "ENTER : toggle auto run " << (do_auto_run ? "(X)" : "( )") << endl; str << "DEL : clear drawing " << endl; str << "d : toggle draw mode " << (draw_mode==0 ? "(draw)" : "(boxes)") << endl; str << "[/] : change draw radius (" << draw_radius << ")" << endl; str << "z/x : change draw color " << endl; str << "i : get color from mouse" << endl; str << endl; str << "draw in the box on the left" << endl; str << "or drag an image (PNG) into it" << endl; str << endl; str << "Press number key to load model: " << endl; for(int i=0; i<models_dir.size(); i++) { auto marker = (i==cur_model_index) ? ">" : " "; str << " " << (i+1) << " : " << marker << " " << models_dir.getName(i) << endl; } ofPushMatrix(); { if(!drawImage(fbo, "fbo (draw in here)") ) str << "fbo not allocated !!" << endl; // if(!drawImage(img_in, "img_in") ) str << "img_in not allocated !!" << endl; // just to check fbo is reading correctly if(!drawImage(img_out, "img_out") ) str << "img_out not allocated !!" << endl; ofTranslate(20, 0); // draw texts ofSetColor(150); ofDrawBitmapString(str.str(), 0, 20); } ofPopMatrix(); // draw colors ofFill(); int x=0; int y=fbo.getHeight() + 30; // draw current color ofSetColor(draw_color); ofDrawCircle(x+palette_draw_size/2, y+palette_draw_size/2, palette_draw_size/2); ofSetColor(200); ofDrawBitmapString("current draw color (change with z/x keys)", x+palette_draw_size+10, y+palette_draw_size/2); y += palette_draw_size + 10; // draw color palette for(int i=0; i<colors.size(); i++) { ofSetColor(colors[i]); ofDrawCircle(x + palette_draw_size/2, y + palette_draw_size/2, palette_draw_size/2); // draw outline if selected color if(colors[i] == draw_color) { ofPushStyle(); ofNoFill(); ofSetColor(255); ofSetLineWidth(3); ofDrawRectangle(x, y, palette_draw_size, palette_draw_size); ofPopStyle(); } x += palette_draw_size; // wrap around if doesn't fit on screen if(x > ofGetWidth() - palette_draw_size) { x = 0; y += palette_draw_size; } } // display drawing helpers ofNoFill(); switch(draw_mode) { case 0: ofSetLineWidth(3); ofSetColor(ofColor::black); ofDrawCircle(ofGetMouseX(), ofGetMouseY(), draw_radius+1); ofSetLineWidth(3); ofSetColor(draw_color); ofDrawCircle(ofGetMouseX(), ofGetMouseY(), draw_radius); break; case 1: if(ofGetMousePressed(0)) { ofSetLineWidth(3); ofSetColor(ofColor::black); ofDrawRectangle(mousePressPos.x-1, mousePressPos.y-1, ofGetMouseX()-mousePressPos.x+3, ofGetMouseY()-mousePressPos.y+3); ofSetLineWidth(3); ofSetColor(draw_color); ofDrawRectangle(mousePressPos.x, mousePressPos.y, ofGetMouseX()-mousePressPos.x, ofGetMouseY()-mousePressPos.y); } } } //-------------------------------------------------------------- void keyPressed(int key) { switch(key) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': load_model_index(key-'1'); break; case 'd': case 'D': draw_mode = 1 - draw_mode; break; case '[': if(draw_radius > 0) draw_radius--; break; case ']': draw_radius++; break; case 'z': draw_color_index--; if(draw_color_index < 0) draw_color_index += colors.size(); // wrap around draw_color = colors[draw_color_index]; break; case 'x': draw_color_index++; if(draw_color_index >= colors.size()) draw_color_index -= colors.size(); // wrap around draw_color = colors[draw_color_index]; break; case 'i': case 'I': if(ofGetMouseX() < fbo.getWidth() && ofGetMouseY() < fbo.getHeight()) { draw_color = img_in.getColor(ofGetMouseX(), ofGetMouseY()); } break; case OF_KEY_DEL: case OF_KEY_BACKSPACE: fbo.begin(); ofClear(0); fbo.end(); break; case OF_KEY_RETURN: do_auto_run ^= true; break; } } //-------------------------------------------------------------- void mouseDragged( int x, int y, int button) { switch(draw_mode) { case 0: // draw fbo.begin(); ofSetColor(draw_color); ofFill(); if(draw_radius>0) { ofDrawCircle(x, y, draw_radius); ofSetLineWidth(draw_radius*2); } else { ofSetLineWidth(0.1f); } ofDrawLine(x, y, ofGetPreviousMouseX(), ofGetPreviousMouseY()); fbo.end(); break; case 1: // draw boxes break; } } //-------------------------------------------------------------- void mousePressed( int x, int y, int button) { mousePressPos = ofVec2f(x, y); mouseDragged(x, y, button); } //-------------------------------------------------------------- virtual void mouseReleased(int x, int y, int button) { switch(draw_mode) { case 0: // draw break; case 1: // boxes fbo.begin(); ofSetColor(draw_color); ofFill(); ofDrawRectangle(mousePressPos.x, mousePressPos.y, x-mousePressPos.x, y-mousePressPos.y); fbo.end(); break; } } //-------------------------------------------------------------- void dragEvent(ofDragInfo dragInfo) { if(dragInfo.files.empty()) return; string file_path = dragInfo.files[0]; // only PNGs work for some reason when Tensorflow is linked in ofImage img; img.load(file_path); if(img.isAllocated()) { fbo.begin(); ofSetColor(255); img.draw(0, 0, fbo.getWidth(), fbo.getHeight()); fbo.end(); } } }; //======================================================================== int main() { ofSetupOpenGL(800, 450, OF_WINDOW); ofRunApp(new ofApp()); }
33.892857
153
0.532205
marcel303
862cc233b4dd498bdace193c9ae8429601c0efc4
3,425
cpp
C++
src/driver/denoiser/cublas.cpp
Skel0t/rodent
adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12
[ "MIT" ]
1
2021-08-19T15:21:32.000Z
2021-08-19T15:21:32.000Z
src/driver/denoiser/cublas.cpp
Skel0t/rodent
adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12
[ "MIT" ]
null
null
null
src/driver/denoiser/cublas.cpp
Skel0t/rodent
adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12
[ "MIT" ]
null
null
null
#include <cublas_v2.h> #include <cublasLt.h> #include <cuda_runtime.h> extern "C" { /* cublaslt supports row-major matrix multiplication. */ void cublaslt_S_gemm(const float* d_A, const float* d_B, float* d_C, int a_width, int a_height, int b_width, int device) { cudaSetDevice(device); cublasHandle_t handle; cublasCreate(&handle); cublasLtHandle_t handlelt = (cublasLtHandle_t) handle; cublasLtMatmulDesc_t descriptor; cublasLtMatrixLayout_t a_layout; cublasLtMatrixLayout_t b_layout; cublasLtMatrixLayout_t c_layout; cublasLtMatrixLayoutCreate(&a_layout, CUDA_R_32F, a_height, a_width, a_width); cublasLtMatrixLayoutCreate(&b_layout, CUDA_R_32F, a_width, b_width, b_width); cublasLtMatrixLayoutCreate(&c_layout, CUDA_R_32F, a_height, b_width, b_width); cublasLtMatmulDescCreate(&descriptor, CUBLAS_COMPUTE_32F, CUDA_R_32F); // Matrices are row-major cublasLtOrder_t rowOrder = CUBLASLT_ORDER_ROW; cublasLtMatrixLayoutSetAttribute( a_layout, CUBLASLT_MATRIX_LAYOUT_ORDER, &rowOrder, sizeof( rowOrder ) ); cublasLtMatrixLayoutSetAttribute( b_layout, CUBLASLT_MATRIX_LAYOUT_ORDER, &rowOrder, sizeof( rowOrder ) ); cublasLtMatrixLayoutSetAttribute( c_layout, CUBLASLT_MATRIX_LAYOUT_ORDER, &rowOrder, sizeof( rowOrder ) ); float a = 1.f, b = 0.f; cublasLtMatmul(handlelt, descriptor, // description &a, // alpha d_A, // pointer to a a_layout, // a description d_B, // pointer to b b_layout, // b description &b, // beta d_C, // C pointer c_layout, // C layout d_C, // D pointer c_layout, // D layout NULL, // matmul algorithm, NULL = take one heuristically nullptr, // workspace* 0, // workspaceSize nullptr); // stream cublasDestroy(handle); } /* Use identity (AB)^t = B^t A^t = C^t and that transposing only changes interpretation from row-major to column-major and vice versa. Necessary since cublas expects column-major while we use row-major. */ void cublas_S_gemm(float* d_A, float* d_B, float* d_C, int a_width, int a_height, int b_width, int device) { cudaSetDevice(device); cublasHandle_t handle; cublasCreate(&handle); float a = 1.f, b = 0.f; cublasSgemm(handle, CUBLAS_OP_N, // no transpose CUBLAS_OP_N, // no transpose b_width, // rows of b' a_height, // cols of a' a_width, // cols of b' &a, // alpha d_B, // B^T left matrix b_width, // b col first d_A, // A^T right matrix a_width, // a col first &b, // beta d_C, // C b_width); // c col first cublasDestroy(handle); } }
42.283951
126
0.531095
Skel0t
862e02da65b63560136d7e691285e103424e7879
441
cpp
C++
Cpp-Snippets-09-sharedptr/main.cpp
LU-JIANGZHOU/Cpp-Snippets
0b2e1ca26a0ffd79e25922c9d92104882cd415bd
[ "MIT" ]
null
null
null
Cpp-Snippets-09-sharedptr/main.cpp
LU-JIANGZHOU/Cpp-Snippets
0b2e1ca26a0ffd79e25922c9d92104882cd415bd
[ "MIT" ]
null
null
null
Cpp-Snippets-09-sharedptr/main.cpp
LU-JIANGZHOU/Cpp-Snippets
0b2e1ca26a0ffd79e25922c9d92104882cd415bd
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> using namespace std; struct myBase { myBase() { cout << " myBase::myBase()\n"; } ~myBase() { cout << " myBase::~myBase()\n"; } }; struct myDerived: public myBase { myDerived() { cout << " myDerived::myDerived()\n"; } ~myDerived() { cout << " myDerived::~myDerived()\n"; } }; int main() { shared_ptr<myBase> sharedPtr = make_shared<myDerived>(); return EXIT_SUCCESS; };
20.045455
60
0.598639
LU-JIANGZHOU
8630b6c29bba3b682a3e450b591bdbe302c909be
5,230
hpp
C++
include/mckl/algorithm/pmcmc.hpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
12
2016-08-02T17:01:13.000Z
2021-03-04T12:11:33.000Z
include/mckl/algorithm/pmcmc.hpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
5
2017-05-09T12:05:06.000Z
2021-03-16T10:39:23.000Z
include/mckl/algorithm/pmcmc.hpp
zhouyan/MCKL
1d03eb5a879e47e268efc73b1d433611e64307b3
[ "BSD-2-Clause" ]
2
2016-08-25T13:10:29.000Z
2019-05-01T01:54:29.000Z
//============================================================================ // MCKL/include/mckl/algorithm/pmcmc.hpp //---------------------------------------------------------------------------- // MCKL: Monte Carlo Kernel Library //---------------------------------------------------------------------------- // Copyright (c) 2013-2018, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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. //============================================================================ #ifndef MCKL_ALGORITHM_PMCMC_HPP #define MCKL_ALGORITHM_PMCMC_HPP #include <mckl/internal/common.hpp> #include <mckl/algorithm/mcmc.hpp> #include <mckl/algorithm/smc.hpp> #include <mckl/core/state_matrix.hpp> #include <mckl/random/rng.hpp> MCKL_PUSH_CLANG_WARNING("-Wpadded") namespace mckl { template <typename Param, MatrixLayout Layout, typename T, std::size_t Dim = 0> class PMCMCStateMatrix : public StateMatrix<Layout, T, Dim> { public: using param_type = Param; using StateMatrix<Layout, T, Dim>::StateMatrix; double log_nc() const { return log_nc_; } void add_log_nc(double nc) { log_nc_ += nc; } const param_type &param() { return param_; } void reset(const param_type &p, double nc = 0) { param_ = p; log_nc_ = nc; } private: param_type param_; double log_nc_; }; // class PMCMCStateMatrix /// \brief Particle Markov chain Monte Carlo mutation /// \ingroup PMCMC template <typename Param, typename T, typename U = double> class PMCMCMutation { public: using param_type = Param; using state_type = T; using size_type = typename Particle<T>::size_type; using eval_type = std::function<double(typename Particle<T>::rng_type &, param_type &)>; using prior_type = std::function<double(const param_type &)>; using pf_type = SMCSampler<T, U>; template <typename Prior, typename... Args> PMCMCMutation(std::size_t N, std::size_t M, Prior &&prior, Args &&... args) : M_(M), prior_(prior), pf_(N, std::forward<Args>(args)...) { } void reset() { eval_.clear(); pf_.reset(); } pf_type &pf() { return pf_; } pf_type &pf() const { return pf_; } PMCMCMutation<Param, T, U> clone() const { PMCMCMutation<Param, T, U> mutation(*this); mutation.pf_.particle().rng_set().reset(); mutation.pf_.particle().rng().seed( Seed<typename Particle<T>::rng_type>::instance().get()); return mutation; } template <typename Prior> void prior(Prior &&prior) { prior_ = std::forward<Prior>(prior); } /// \brief Add a new evaluation object for the update step template <typename Eval> std::size_t update(Eval &&eval) { eval_.push_back(std::forward<Eval>(eval)); return eval_.size() - 1; } std::size_t operator()(std::size_t iter, param_type &param) { if (iter == 0) { pf_.clear(); pf_.particle().state().reset(param, 0); pf_.iterate(M_); return 0; } const double lnc = pf_.particle().state().log_nc(); double prob = -prior_(param) - lnc; param_type p(param); for (auto &eval : eval_) { prob += eval(pf_.particle().rng(), p); } prob += prior_(p); pf_.clear(); pf_.particle().state().reset(p, 0); pf_.iterate(M_); prob += pf_.particle().state().log_nc(); mckl::U01Distribution<double> u01; double u = std::log(u01(pf_.particle().rng())); if (u < prob) { param = std::move(p); } else { pf_.particle().state().reset(param, lnc); } return u < prob ? 1 : 0; } private: std::size_t M_; prior_type prior_; pf_type pf_; Vector<eval_type> eval_; }; // class PMCMCMutation } // namespace mckl MCKL_POP_CLANG_WARNING #endif // MCKL_ALGORITHM_PMCMC_HPP
30.406977
79
0.609751
zhouyan
8632fce14439b4ec0bc65b9e066f77f71f17bd95
8,012
cpp
C++
sugus/detail/Conversion.cpp
tiropp/sugus
21b25bd74abdae0b421613ad5ecae57d8c5869a1
[ "MIT" ]
1
2018-03-23T08:51:11.000Z
2018-03-23T08:51:11.000Z
sugus/detail/Conversion.cpp
tiropp/sugus
21b25bd74abdae0b421613ad5ecae57d8c5869a1
[ "MIT" ]
null
null
null
sugus/detail/Conversion.cpp
tiropp/sugus
21b25bd74abdae0b421613ad5ecae57d8c5869a1
[ "MIT" ]
null
null
null
#include "Conversion.h" // BOOST includes #include <boost/foreach.hpp> // OpcUa includes #include <opcua_guid.h> // Sugus includes #include <sugus/Exceptions.h> #include <sugus/EndpointContainer.h> #include <sugus/Value.h> #include <sugus/detail/EndpointContainer.h> namespace Sugus { namespace detail { String ToString(SecurityPolicy secPolicy) { switch( secPolicy ) { case SecurityPolicy::None: return OpcUa_SecurityPolicy_None; case SecurityPolicy::Basic128Rsa15: return OpcUa_SecurityPolicy_Basic128Rsa15; case SecurityPolicy::Basic256: return OpcUa_SecurityPolicy_Basic256; case SecurityPolicy::Basic256Sha256: return OpcUa_SecurityPolicy_Basic256Sha256; default: throw InvalidSecurityPolicy(); } } std::string ToString(const OpcUa_String& string) { std::string result; const char* p = OpcUa_String_GetRawString( &string ); if( p ) result.assign( p ); return result; } MessageSecurityMode ToSecurityMode(OpcUa_MessageSecurityMode mode) { switch( mode ) { case OpcUa_MessageSecurityMode_Invalid: return MessageSecurityMode::Invalid; case OpcUa_MessageSecurityMode_None: return MessageSecurityMode::None; case OpcUa_MessageSecurityMode_Sign: return MessageSecurityMode::Sign; case OpcUa_MessageSecurityMode_SignAndEncrypt: return MessageSecurityMode::SignAndEncrypt; default: throw InvalidMessageSecurityMode(); } } OpcUa_MessageSecurityMode ToSecurityMode(MessageSecurityMode mode) { switch( mode ) { case MessageSecurityMode::Invalid: return OpcUa_MessageSecurityMode_Invalid; case MessageSecurityMode::None: return OpcUa_MessageSecurityMode_None; case MessageSecurityMode::Sign: return OpcUa_MessageSecurityMode_Sign; case MessageSecurityMode::SignAndEncrypt: return OpcUa_MessageSecurityMode_SignAndEncrypt; default: throw InvalidMessageSecurityMode(); } } Sugus::EndpointContainer ToEndpointContainer(const Sugus::detail::EndpointContainer& in) { Sugus::EndpointContainer out; BOOST_FOREACH(const Endpoint& ep, in) out.Add( ep ); return out; } ApplicationType ToApplicationType(OpcUa_ApplicationType type) { switch( type ) { case OpcUa_ApplicationType_Server: return ApplicationType::Server; case OpcUa_ApplicationType_Client: return ApplicationType::Client; case OpcUa_ApplicationType_ClientAndServer: return ApplicationType::ClientAndServer; case OpcUa_ApplicationType_DiscoveryServer: return ApplicationType::DiscoveryServer; default: throw InvalidApplicationType(); } } ApplicationDescription ToApplicationDescription(const OpcUa_ApplicationDescription& in) { Sugus::ApplicationDescription out; out.applicationUri = ToString (in.ApplicationUri); out.productUri = ToString (in.ProductUri); out.applicationName = ToString (in.ApplicationName.Text); out.applicationType = ToApplicationType(in.ApplicationType); out.gatewayServerUri = ToString (in.GatewayServerUri); out.discoveryProfileUri = ToString (in.DiscoveryProfileUri); for(int i=0; i<in.NoOfDiscoveryUrls; ++i) out.discoveryUrls.push_back( ToString(in.DiscoveryUrls[i]) ); return out; } Data ToData(const OpcUa_ByteString& data) { Data result; if( !data.Length || (data.Length==-1) ) return result; result.resize( data.Length ); std::copy(data.Data, data.Data+data.Length, result.begin()); return result; } UserTokenPolicyContainer ToUserTokenPolicyContainer(OpcUa_UserTokenPolicy* policies, int size) { UserTokenPolicyContainer result; for(int i=0; i<size; ++i) result.push_back( ToUserTokenPolicy(policies[i]) ); return result; } UserTokenPolicy ToUserTokenPolicy(const OpcUa_UserTokenPolicy& policy) { UserTokenPolicy result; result.policyId = ToString (policy.PolicyId); result.tokenType = ToUserTokenType(policy.TokenType); result.issuedTokenType = ToString (policy.IssuedTokenType); result.issuerEndpointUrl = ToString (policy.IssuerEndpointUrl); result.securityPolicyUri = ToString (policy.SecurityPolicyUri); return result; } UserTokenType ToUserTokenType(OpcUa_UserTokenType type) { switch( type ) { case OpcUa_UserTokenType_Anonymous: return UserTokenType::Anonymous; case OpcUa_UserTokenType_UserName: return UserTokenType::UserName; case OpcUa_UserTokenType_Certificate: return UserTokenType::Certificate; case OpcUa_UserTokenType_IssuedToken: return UserTokenType::IssuedToken; default: throw InvalidUserTokenType(); } } uint64_t ToUint64(const OpcUa_DateTime& dt) { uint64_t result = dt.dwHighDateTime; result <<=32; result += dt.dwLowDateTime; return result; } Data ToData(const OpcUa_Guid& guid) { char g[OPCUA_GUID_LEXICAL_LENGTH]; OpcUa_Guid_ToStringA(const_cast<OpcUa_Guid*>(&guid), g); Data data; data.assign(g, g+OPCUA_GUID_LEXICAL_LENGTH); return data; } namespace { template <typename T> Data ToData(T& value) { Data data; data.assign((uint8_t*)&value, (uint8_t*)(&value+1)); return data; } } // End unnamed namespace Value ToValue(const OpcUa_DataValue& value) { Value result; result.statusCode = value.StatusCode; result.sourceTimestamp = ToUint64(value.SourceTimestamp); result.serverTimestamp = ToUint64(value.ServerTimestamp); result.sourcePicoseconds = value.SourcePicoseconds; result.serverPicoseconds = value.ServerPicoseconds; const OpcUa_VariantUnion& v = value.Value.Value; switch( value.Value.Datatype ) { case OpcUaType_Null: break; case OpcUaType_Boolean: result.data.push_back(v.Boolean); break; case OpcUaType_SByte: result.data.push_back(v.SByte); break; case OpcUaType_Byte: result.data.push_back(v.Byte); break; case OpcUaType_Int16: result.data = ToData(v.Int16); break; case OpcUaType_UInt16: result.data = ToData(v.UInt16); break; case OpcUaType_Int32: result.data = ToData(v.Int32); break; case OpcUaType_UInt32: result.data = ToData(v.UInt32); break; case OpcUaType_Int64: result.data = ToData(v.Int64); break; case OpcUaType_UInt64: result.data = ToData(v.UInt64); break; case OpcUaType_Float: result.data = ToData(v.Float); break; case OpcUaType_Double: result.data = ToData(v.Double); break; case OpcUaType_String: { String s(v.String); const std::string& ss = s.Str(); result.data.assign(ss.begin(), ss.end()); break; } case OpcUaType_DateTime: { uint64_t dt = ToUint64(v.DateTime); result.data = ToData( dt ); break; } case OpcUaType_Guid: result.data = ToData(v.Guid); break; case OpcUaType_ByteString: result.data = ToData( v.ByteString ); break; case OpcUaType_XmlElement: result.data = ToData( v.XmlElement ); break; case OpcUaType_NodeId: // not supported break; case OpcUaType_ExpandedNodeId: // not supported break; case OpcUaType_StatusCode: result.data = ToData(v.StatusCode); break; case OpcUaType_QualifiedName: // not supported break; case OpcUaType_LocalizedText: // not supported break; case OpcUaType_ExtensionObject: // not supported break; case OpcUaType_DataValue: // not supported break; case OpcUaType_Variant: // not supported break; case OpcUaType_DiagnosticInfo: // not supported break; } return result; } } // End namespace detail } // End namespace Sugus
28.310954
94
0.68647
tiropp
8636bb9734559286a9631f649a9eef8dbbc07f16
262
cpp
C++
17/if_switch_init/if_init.cpp
odiubankov/cpp_examples
4107315778aebfc9c397fea0524a1ab6565abfde
[ "MIT" ]
null
null
null
17/if_switch_init/if_init.cpp
odiubankov/cpp_examples
4107315778aebfc9c397fea0524a1ab6565abfde
[ "MIT" ]
null
null
null
17/if_switch_init/if_init.cpp
odiubankov/cpp_examples
4107315778aebfc9c397fea0524a1ab6565abfde
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" bool true_case() { return true; } TEST(if_init, test) { bool bar = true; if (const auto foo = true_case(); foo) { bar = false; } else { bar = foo; } const auto foo = false; ASSERT_FALSE(bar); ASSERT_FALSE(foo); }
16.375
42
0.603053
odiubankov
863979125d319560e2587911ed9ba15e982c97d7
2,308
cpp
C++
HookDll/Hook/HookLog.cpp
211847750/iagd
051635e3bf1b26d27315f19ae3a63e33a6f67f37
[ "MIT" ]
null
null
null
HookDll/Hook/HookLog.cpp
211847750/iagd
051635e3bf1b26d27315f19ae3a63e33a6f67f37
[ "MIT" ]
null
null
null
HookDll/Hook/HookLog.cpp
211847750/iagd
051635e3bf1b26d27315f19ae3a63e33a6f67f37
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "HookLog.h" #include <filesystem> #include <iostream> #include <windows.h> #include <shlobj.h> std::wstring GetIagdFolder() { PWSTR path_tmp; auto get_folder_path_ret = SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path_tmp); if (get_folder_path_ret != S_OK) { CoTaskMemFree(path_tmp); return std::wstring(); } std::wstring path = path_tmp; CoTaskMemFree(path_tmp); return path + L"\\..\\local\\evilsoft\\iagd\\"; } HookLog::HookLog() : m_lastMessageCount(0) { std::wstring iagdFolder = GetIagdFolder(); // %appdata%\..\local\evilsoft\iagd wchar_t tmpfolder[MAX_PATH]; // %appdata%\..\local\temp\ GetTempPath(MAX_PATH, tmpfolder); std::wstring logFile(!iagdFolder.empty() ? iagdFolder : tmpfolder); logFile += L"iagd_hook.log"; m_out.open(logFile); if (m_out.is_open()) { m_out << L"****************************" << std::endl << L" Hook Logging Started" << std::endl << L"****************************" << std::endl; TCHAR buffer[MAX_PATH]; DWORD size = GetCurrentDirectory(MAX_PATH, buffer); buffer[size] = '\0'; m_out << L"Current Directory: " << buffer << std::endl; } } HookLog::~HookLog() { if (m_out.is_open()) { m_out << L"****************************" << std::endl << L" Hook Logging Terminated " << std::endl << L"****************************" << std::endl; m_out.close(); } } void HookLog::out( std::wstring const& output ) { if (m_out.is_open()) { if (!m_lastMessage.empty()) { if (m_lastMessage.compare(output) == 0) { ++m_lastMessageCount; } else { if (m_lastMessageCount > 1) { m_out << L"Last message was repeated " << m_lastMessageCount << L" times." << std::endl; } m_lastMessage = output; m_lastMessageCount = 1; m_out << output.c_str() << std::endl; } } else { m_lastMessage = output; m_lastMessageCount = 1; m_out << output.c_str() << std::endl; } } }
25.086957
100
0.506066
211847750
864386c9c52d25ed7e9ea5295551c429957210f0
1,817
cpp
C++
src/lib/problem.cpp
bunsanorg/bacs_archive
2909b82e84259cc1441c5bc7f4bf87c2ec31548b
[ "Apache-2.0" ]
null
null
null
src/lib/problem.cpp
bunsanorg/bacs_archive
2909b82e84259cc1441c5bc7f4bf87c2ec31548b
[ "Apache-2.0" ]
null
null
null
src/lib/problem.cpp
bunsanorg/bacs_archive
2909b82e84259cc1441c5bc7f4bf87c2ec31548b
[ "Apache-2.0" ]
null
null
null
#include <bacs/archive/problem.hpp> #include <bacs/archive/error.hpp> #include <bunsan/pm/entry.hpp> namespace bacs { namespace archive { namespace problem { const std::string &flag_cast(const problem::Flag &flag) { switch (flag.flag_case()) { case Flag::kReserved: return flag_cast(flag.reserved()); case Flag::kCustom: return flag.custom(); default: BOOST_ASSERT(false); } } const std::string &flag_cast(const problem::Flag::Reserved flag) { return Flag::Reserved_Name(flag); } Flag flag_cast(const std::string &flag) { Flag result; problem::Flag::Reserved reserved; if (Flag::Reserved_Parse(flag, &reserved)) { result.set_reserved(reserved); } else { result.set_custom(flag); } return result; } const std::string &flag_to_string(const problem::Flag &flag) { return flag_cast(flag); } const std::string &flag_to_string(const problem::Flag::Reserved flag) { return flag_cast(flag); } const std::string &flag_to_string(const std::string &flag) { return flag; } bool is_allowed_flag(const flag &flag_) { return bunsan::pm::entry::is_allowed_subpath(flag_); } bool is_allowed_flag(const Flag &flag) { return is_allowed_flag(flag_cast(flag)); } bool is_allowed_flag_set(const FlagSet &flags) { for (const Flag &flag : flags.flag()) { if (!is_allowed_flag(flag)) return false; } return true; } void validate_flag(const flag &flag_) { if (!is_allowed_flag(flag_)) BOOST_THROW_EXCEPTION(invalid_flag_error() << invalid_flag_error::flag(flag_)); } void validate_flag(const Flag &flag) { validate_flag(flag_cast(flag)); } void validate_flag_set(const FlagSet &flags) { for (const Flag &flag : flags.flag()) validate_flag(flag); } } // namespace problem } // namespace archive } // namespace bacs
23
75
0.698404
bunsanorg
8643f1dc9391398c5cb0d61cc5726fa78ef3c89c
386
hpp
C++
FootSoldier.hpp
Dolev/WarGame
0c51c62432e059483275ec916c16c411f40e9116
[ "MIT" ]
null
null
null
FootSoldier.hpp
Dolev/WarGame
0c51c62432e059483275ec916c16c411f40e9116
[ "MIT" ]
null
null
null
FootSoldier.hpp
Dolev/WarGame
0c51c62432e059483275ec916c16c411f40e9116
[ "MIT" ]
null
null
null
#include "Soldier.hpp" class FootSoldier: public Soldier{ protected: //char letter=FS; /* Direction Options: Up, Down, Right, Left FootSoldier Up(); FootSoldier Down(); FootSoldier Left(); FootSoldier Right(); */ public: FootSoldier(); ~FootSoldier(); explicit FootSoldier(int player); };
19.3
41
0.551813
Dolev
8645c70f3190470a98aaefd07c76e2a1070df7db
2,946
cpp
C++
lib/src/tinytmxUtil.cpp
KaseyJenkins/tinytmx
b7ab2927dfe2e70459c55af991b3c1013d335fd5
[ "BSD-2-Clause" ]
2
2022-01-10T07:53:48.000Z
2022-03-22T11:25:50.000Z
lib/src/tinytmxUtil.cpp
KaseyJenkins/tinytmx
b7ab2927dfe2e70459c55af991b3c1013d335fd5
[ "BSD-2-Clause" ]
null
null
null
lib/src/tinytmxUtil.cpp
KaseyJenkins/tinytmx
b7ab2927dfe2e70459c55af991b3c1013d335fd5
[ "BSD-2-Clause" ]
null
null
null
#include <cstdlib> #include <algorithm> #include <cctype> #ifdef USE_MINIZ #include "miniz.h" #else #include "zlib.h" #endif #include "tinytmxUtil.hpp" #include "base64.h" namespace tinytmx { // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } void Util::Trim(std::string &str) { trim(str); } // // trim from start (copying) // static inline std::string ltrim_copy(std::string s) { // ltrim(s); // return s; // } // // trim from end (copying) // static inline std::string rtrim_copy(std::string s) { // rtrim(s); // return s; // } // // trim from both ends (copying) // static inline std::string trim_copy(std::string s) { // trim(s); // return s; // } std::string Util::DecodeBase64(std::string const &str) { return base64_decode(str); } char *Util::DecompressGZIP(char const *data, uint32_t dataSize, uint32_t expectedSize) { uint32_t bufferSize = expectedSize; int ret; z_stream strm; char *out = (char *) malloc(bufferSize); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = (Bytef *) data; strm.avail_in = dataSize; strm.next_out = (Bytef *) out; strm.avail_out = bufferSize; ret = inflateInit2(&strm, 15 + 32); if (ret != Z_OK) { free(out); return NULL; } do { ret = inflate(&strm, Z_SYNC_FLUSH); switch (ret) { case Z_NEED_DICT: case Z_STREAM_ERROR: ret = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&strm); free(out); return NULL; } if (ret != Z_STREAM_END) { out = (char *) realloc(out, bufferSize * 2); if (!out) { inflateEnd(&strm); free(out); return NULL; } strm.next_out = (Bytef *) (out + bufferSize); strm.avail_out = bufferSize; bufferSize *= 2; } } while (ret != Z_STREAM_END); if (strm.avail_in != 0) { free(out); return NULL; } inflateEnd(&strm); return out; } }
22.837209
92
0.491174
KaseyJenkins
86467b46799ce180ecaf4aeb72290b54e5e1e952
912
cpp
C++
source/jz19.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
source/jz19.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
source/jz19.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
#include "jz19.h" using namespace std; bool Jz19::isMatch(string s, string p) { vector<vector<bool>> dp(s.size() + 1, vector<bool>(p.size() + 1, false)); // 二维动态规划数组 // 初始状态 dp[0][0] = true; for (int i = 2; i < dp[0].size(); i += 2) { dp[0][i] = dp[0][i - 2] && p[i - 1] == '*'; } // 状态转移 for (int i = 1; i < dp.size(); i++) { for (int j = 1; j < dp[0].size(); j++) { if (p[j - 1] == '*') { if (dp[i][j - 2] || (dp[i - 1][j] && (p[j - 2] == '.' || p[j - 2] == s[i - 1]))) { dp[i][j] = true; } } else { if (dp[i - 1][j - 1] && (p[j - 1] == '.' || p[j - 1] == s[i - 1])) { dp[i][j] = true; } } } } return dp.back().back(); }
22.8
96
0.294956
loganautomata
8646b4006ece47b569d999da6f3239cadf24a9aa
163
cc
C++
build/x86/python/m5/internal/param_L1Cache_Controller.i_init.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/python/m5/internal/param_L1Cache_Controller.i_init.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
1
2020-08-20T05:53:30.000Z
2020-08-20T05:53:30.000Z
build/X86_MESI_Two_Level/python/m5/internal/param_L1Cache_Controller.i_init.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" extern "C" { void init_param_L1Cache_Controller(); } EmbeddedSwig embed_swig_param_L1Cache_Controller(init_param_L1Cache_Controller);
20.375
80
0.809816
billionshang
864a3d443cf0689dbcbaefe0576b602c539826ae
15,993
cpp
C++
qt-4.8.4/src/opengl/qgl_egl.cpp
easion/qt_for_gix
f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8
[ "Apache-2.0" ]
null
null
null
qt-4.8.4/src/opengl/qgl_egl.cpp
easion/qt_for_gix
f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8
[ "Apache-2.0" ]
null
null
null
qt-4.8.4/src/opengl/qgl_egl.cpp
easion/qt_for_gix
f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtOpenGL module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qdebug.h> #include <QtOpenGL/qgl.h> #include <QtOpenGL/qglpixelbuffer.h> #include "qgl_p.h" #include "qgl_egl_p.h" #include "qglpixelbuffer_p.h" #ifdef Q_WS_X11 #include <QtGui/private/qpixmap_x11_p.h> #endif #if defined(Q_OS_SYMBIAN) #include <QtGui/private/qgraphicssystemex_symbian_p.h> #endif QT_BEGIN_NAMESPACE QEglProperties *QGLContextPrivate::extraWindowSurfaceCreationProps = NULL; void qt_eglproperties_set_glformat(QEglProperties& eglProperties, const QGLFormat& glFormat) { int redSize = glFormat.redBufferSize(); int greenSize = glFormat.greenBufferSize(); int blueSize = glFormat.blueBufferSize(); int alphaSize = glFormat.alphaBufferSize(); int depthSize = glFormat.depthBufferSize(); int stencilSize = glFormat.stencilBufferSize(); int sampleCount = glFormat.samples(); bool prefer32Bit = false; #ifdef Q_OS_SYMBIAN // on Symbian we prefer 32-bit configs, unless we're using the low memory GPU prefer32Bit = !QSymbianGraphicsSystemEx::hasBCM2727(); #endif if (prefer32Bit) { if (glFormat.alpha() && alphaSize <= 0) alphaSize = 8; if (glFormat.depth() && depthSize <= 0) depthSize = 24; if (glFormat.stencil() && stencilSize <= 0) stencilSize = 8; if (glFormat.sampleBuffers() && sampleCount <= 0) sampleCount = 1; redSize = redSize > 0 ? redSize : 8; greenSize = greenSize > 0 ? greenSize : 8; blueSize = blueSize > 0 ? blueSize : 8; alphaSize = alphaSize > 0 ? alphaSize : 8; depthSize = depthSize > 0 ? depthSize : 24; stencilSize = stencilSize > 0 ? stencilSize : 8; sampleCount = sampleCount >= 0 ? sampleCount : 4; } else { // QGLFormat uses a magic value of -1 to indicate "don't care", even when a buffer of that // type has been requested. So we must check QGLFormat's booleans too if size is -1: if (glFormat.alpha() && alphaSize <= 0) alphaSize = 1; if (glFormat.depth() && depthSize <= 0) depthSize = 1; if (glFormat.stencil() && stencilSize <= 0) stencilSize = 1; if (glFormat.sampleBuffers() && sampleCount <= 0) sampleCount = 1; // We want to make sure 16-bit configs are chosen over 32-bit configs as they will provide // the best performance. The EGL config selection algorithm is a bit stange in this regard: // The selection criteria for EGL_BUFFER_SIZE is "AtLeast", so we can't use it to discard // 32-bit configs completely from the selection. So it then comes to the sorting algorithm. // The red/green/blue sizes have a sort priority of 3, so they are sorted by first. The sort // order is special and described as "by larger _total_ number of color bits.". So EGL will // put 32-bit configs in the list before the 16-bit configs. However, the spec also goes on // to say "If the requested number of bits in attrib_list for a particular component is 0, // then the number of bits for that component is not considered". This part of the spec also // seems to imply that setting the red/green/blue bits to zero means none of the components // are considered and EGL disregards the entire sorting rule. It then looks to the next // highest priority rule, which is EGL_BUFFER_SIZE. Despite the selection criteria being // "AtLeast" for EGL_BUFFER_SIZE, it's sort order is "smaller" meaning 16-bit configs are // put in the list before 32-bit configs. So, to make sure 16-bit is preffered over 32-bit, // we must set the red/green/blue sizes to zero. This has an unfortunate consequence that // if the application sets the red/green/blue size to 5/6/5 on the QGLFormat, they will // probably get a 32-bit config, even when there's an RGB565 config available. Oh well. // Now normalize the values so -1 becomes 0 redSize = redSize > 0 ? redSize : 0; greenSize = greenSize > 0 ? greenSize : 0; blueSize = blueSize > 0 ? blueSize : 0; alphaSize = alphaSize > 0 ? alphaSize : 0; depthSize = depthSize > 0 ? depthSize : 0; stencilSize = stencilSize > 0 ? stencilSize : 0; sampleCount = sampleCount > 0 ? sampleCount : 0; } eglProperties.setValue(EGL_RED_SIZE, redSize); eglProperties.setValue(EGL_GREEN_SIZE, greenSize); eglProperties.setValue(EGL_BLUE_SIZE, blueSize); eglProperties.setValue(EGL_ALPHA_SIZE, alphaSize); eglProperties.setValue(EGL_DEPTH_SIZE, depthSize); eglProperties.setValue(EGL_STENCIL_SIZE, stencilSize); eglProperties.setValue(EGL_SAMPLES, sampleCount); eglProperties.setValue(EGL_SAMPLE_BUFFERS, sampleCount ? 1 : 0); } // Updates "format" with the parameters of the selected configuration. void qt_glformat_from_eglconfig(QGLFormat& format, const EGLConfig config) { EGLint redSize = 0; EGLint greenSize = 0; EGLint blueSize = 0; EGLint alphaSize = 0; EGLint depthSize = 0; EGLint stencilSize = 0; EGLint sampleCount = 0; EGLint level = 0; EGLDisplay display = QEgl::display(); eglGetConfigAttrib(display, config, EGL_RED_SIZE, &redSize); eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &greenSize); eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &blueSize); eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &alphaSize); eglGetConfigAttrib(display, config, EGL_DEPTH_SIZE, &depthSize); eglGetConfigAttrib(display, config, EGL_STENCIL_SIZE, &stencilSize); eglGetConfigAttrib(display, config, EGL_SAMPLES, &sampleCount); eglGetConfigAttrib(display, config, EGL_LEVEL, &level); format.setRedBufferSize(redSize); format.setGreenBufferSize(greenSize); format.setBlueBufferSize(blueSize); format.setAlphaBufferSize(alphaSize); format.setDepthBufferSize(depthSize); format.setStencilBufferSize(stencilSize); format.setSamples(sampleCount); format.setPlane(level); format.setDirectRendering(true); // All EGL contexts are direct-rendered format.setRgba(true); // EGL doesn't support colour index rendering format.setStereo(false); // EGL doesn't support stereo buffers format.setAccumBufferSize(0); // EGL doesn't support accululation buffers format.setDoubleBuffer(true); // We don't support single buffered EGL contexts // Clear the EGL error state because some of the above may // have errored out because the attribute is not applicable // to the surface type. Such errors don't matter. eglGetError(); } bool QGLFormat::hasOpenGL() { return true; } void QGLContext::reset() { Q_D(QGLContext); if (!d->valid) return; d->cleanup(); doneCurrent(); if (d->eglContext && d->ownsEglContext) { d->destroyEglSurfaceForDevice(); delete d->eglContext; } d->ownsEglContext = false; d->eglContext = 0; d->eglSurface = EGL_NO_SURFACE; d->crWin = false; d->sharing = false; d->valid = false; d->transpColor = QColor(); d->initDone = false; QGLContextGroup::removeShare(this); } void QGLContext::makeCurrent() { Q_D(QGLContext); if (!d->valid || !d->eglContext || d->eglSurfaceForDevice() == EGL_NO_SURFACE) { qWarning("QGLContext::makeCurrent(): Cannot make invalid context current"); return; } if (d->eglContext->makeCurrent(d->eglSurfaceForDevice())) { QGLContextPrivate::setCurrentContext(this); if (!d->workaroundsCached) { d->workaroundsCached = true; const char *renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER)); if (!renderer) return; if ((strstr(renderer, "SGX") || strstr(renderer, "MBX"))) { // PowerVR MBX/SGX chips needs to clear all buffers when starting to render // a new frame, otherwise there will be a performance penalty to pay for // each frame. qDebug() << "Found SGX/MBX driver, enabling FullClearOnEveryFrame"; d->workaround_needsFullClearOnEveryFrame = true; // Older PowerVR SGX drivers (like the one in the N900) have a // bug which prevents glCopyTexSubImage2D() to work with a POT // or GL_ALPHA texture bound to an FBO. The only way to // identify that driver is to check the EGL version number for it. const char *egl_version = eglQueryString(d->eglContext->display(), EGL_VERSION); if (egl_version && strstr(egl_version, "1.3")) { qDebug() << "Found v1.3 driver, enabling brokenFBOReadBack"; d->workaround_brokenFBOReadBack = true; } else if (egl_version && strstr(egl_version, "1.4")) { qDebug() << "Found v1.4 driver, enabling brokenTexSubImage"; d->workaround_brokenTexSubImage = true; // this is a bit complicated; 1.4 version SGX drivers from // Nokia have fixed the brokenFBOReadBack problem, but // official drivers from TI haven't, meaning that things // like the beagleboard are broken unless we hack around it // - but at the same time, we want to not reduce performance // by not enabling this elsewhere. // // so, let's check for a Nokia-specific addon, and only // enable if it isn't present. // (see MeeGo bug #5616) if (!QEgl::hasExtension("EGL_NOK_image_shared")) { // no Nokia extension, this is probably a standard SGX // driver, so enable the workaround qDebug() << "Found non-Nokia v1.4 driver, enabling brokenFBOReadBack"; d->workaround_brokenFBOReadBack = true; } } } else if (strstr(renderer, "VideoCore III")) { // Some versions of VideoCore III drivers seem to pollute and use // stencil buffer when using glScissors even if stencil test is disabled. // Workaround is to clear stencil buffer before disabling scissoring. // qDebug() << "Found VideoCore III driver, enabling brokenDisableScissorTest"; d->workaround_brokenScissor = true; } } } } void QGLContext::doneCurrent() { Q_D(QGLContext); if (d->eglContext) d->eglContext->doneCurrent(); QGLContextPrivate::setCurrentContext(0); } void QGLContext::swapBuffers() const { Q_D(const QGLContext); if (!d->valid || !d->eglContext) return; d->eglContext->swapBuffers(d->eglSurfaceForDevice()); } extern void remove_gles_window(gi_window_id_t wid); void QGLContextPrivate::destroyEglSurfaceForDevice() { unsigned long xid = 0; if (eglSurface != EGL_NO_SURFACE) { #if defined(Q_WS_X11) || defined(Q_OS_SYMBIAN) || defined(Q_WS_GIX) // Make sure we don't call eglDestroySurface on a surface which // was created for a different winId. This applies only to QGLWidget // paint device, so make sure this is the one we're operating on // (as opposed to a QGLWindowSurface use case). if (paintDevice && paintDevice->devType() == QInternal::Widget) { QWidget *w = static_cast<QWidget *>(paintDevice); if (QGLWidget *wgl = qobject_cast<QGLWidget *>(w)) { if (wgl->d_func()->eglSurfaceWindowId != wgl->winId()) { qWarning("WARNING: Potential EGL surface leak! Not destroying surface."); eglSurface = EGL_NO_SURFACE; return; } else{ xid = wgl->d_func()->eglSurfaceWindowId; } } } #endif #if defined(Q_WS_GIX) releaseNativeWindow(); //remove_gles_window(xid); #endif eglDestroySurface(eglContext->display(), eglSurface); eglSurface = EGL_NO_SURFACE; } } EGLSurface QGLContextPrivate::eglSurfaceForDevice() const { // If a QPixmapData had to create the QGLContext, we don't have a paintDevice if (!paintDevice) return eglSurface; #ifdef Q_WS_X11 if (paintDevice->devType() == QInternal::Pixmap) { QPixmapData *pmd = static_cast<QPixmap*>(paintDevice)->data_ptr().data(); if (pmd->classId() == QPixmapData::X11Class) { QX11PixmapData* x11PixmapData = static_cast<QX11PixmapData*>(pmd); return (EGLSurface)x11PixmapData->gl_surface; } } #endif if (paintDevice->devType() == QInternal::Pbuffer) { QGLPixelBuffer* pbuf = static_cast<QGLPixelBuffer*>(paintDevice); return pbuf->d_func()->pbuf; } return eglSurface; } void QGLContextPrivate::swapRegion(const QRegion &region) { if (!valid || !eglContext) return; eglContext->swapBuffersRegion2NOK(eglSurfaceForDevice(), &region); } void QGLContextPrivate::setExtraWindowSurfaceCreationProps(QEglProperties *props) { extraWindowSurfaceCreationProps = props; } void QGLWidget::setMouseTracking(bool enable) { QWidget::setMouseTracking(enable); } QColor QGLContext::overlayTransparentColor() const { return d_func()->transpColor; } uint QGLContext::colorIndex(const QColor &c) const { Q_UNUSED(c); return 0; } void QGLContext::generateFontDisplayLists(const QFont & fnt, int listBase) { Q_UNUSED(fnt); Q_UNUSED(listBase); } void *QGLContext::getProcAddress(const QString &proc) const { return (void*)eglGetProcAddress(reinterpret_cast<const char *>(proc.toLatin1().data())); } bool QGLWidgetPrivate::renderCxPm(QPixmap*) { return false; } QT_END_NAMESPACE
39.9825
100
0.650847
easion
864d6aa4f31ca97ea85e61123781207a80fbb786
1,903
hpp
C++
caffe/include/caffe/layers/point_transformer_layer.hpp
shaoxiaohu/Face-Alignment-with-Two-Stage-Re-initialization-
ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b
[ "MIT" ]
92
2017-07-19T05:12:05.000Z
2021-11-09T07:59:07.000Z
caffe/include/caffe/layers/point_transformer_layer.hpp
mornydew/Face_Alignment_Two_Stage_Re-initialization
ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b
[ "MIT" ]
11
2017-10-18T05:11:20.000Z
2020-04-03T21:28:20.000Z
caffe/include/caffe/layers/point_transformer_layer.hpp
mornydew/Face_Alignment_Two_Stage_Re-initialization
ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b
[ "MIT" ]
31
2017-07-20T11:37:39.000Z
2021-03-08T09:01:26.000Z
#ifndef CAFFE_POINT_TRANSFORMER_LAYERHPP_ #define CAFFE_POINT_TRANSFORMER_LAYERHPP_ #include <string> #include <utility> #include <vector> #include "caffe/blob.hpp" #include "caffe/data_transformer.hpp" #include "caffe/internal_thread.hpp" #include "caffe/layer.hpp" #include "caffe/layers/base_data_layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /* PointTransformerLayer - Points Trasnformation layer Transform points/landmarks for input points/landmarks based input spatial transformation parameters input: [x1, y1, ..., xn, yn] output: [x1', y1', ..., xn', yn'] 20160705 */ template <typename Dtype> class PointTransformerLayer : public Layer<Dtype> { public: explicit PointTransformerLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "PointTransformer Layer"; } virtual inline int MinBottomBlobs() const { return 2; } virtual inline int MaxBottomBlobs() const { return 2; } virtual inline int MinTopBlobs() const { return 1; } virtual inline int MaxTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); // virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, // const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); // virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, // const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); bool inv_trans; int point_num_; }; } // namespace caffe #endif //CAFFE_POINT_TRANSFORMER_LAYERHPP_
32.810345
102
0.728849
shaoxiaohu
865a37e14172e95004d5af18c4348c90bea0b192
3,703
cpp
C++
Source/Projects/GoddamnGraphics/GoddamnGraphicsVulkan/Source/GoddamnEngine/GraphicsVulkan/GraphicsVulkanWindows.cpp
GoddamnIndustries/GoddamnEngine
018c6582f6a2ebcba2c59693c677744434d66b20
[ "MIT" ]
4
2015-07-05T16:46:12.000Z
2021-02-04T09:32:47.000Z
Source/Projects/GoddamnGraphics/GoddamnGraphicsVulkan/Source/GoddamnEngine/GraphicsVulkan/GraphicsVulkanWindows.cpp
GoddamnIndustries/GoddamnEngine
018c6582f6a2ebcba2c59693c677744434d66b20
[ "MIT" ]
null
null
null
Source/Projects/GoddamnGraphics/GoddamnGraphicsVulkan/Source/GoddamnEngine/GraphicsVulkan/GraphicsVulkanWindows.cpp
GoddamnIndustries/GoddamnEngine
018c6582f6a2ebcba2c59693c677744434d66b20
[ "MIT" ]
1
2017-01-27T22:49:12.000Z
2017-01-27T22:49:12.000Z
// ========================================================================================== // Copyright (C) Goddamn Industries 2015. All Rights Reserved. // // This software or any its part is distributed under terms of Goddamn Industries End User // License Agreement. By downloading or using this software or any its part you agree with // terms of Goddamn Industries End User License Agreement. // ========================================================================================== /*! * @file GoddamnEngine/GraphicsVulkan/GraphicsVulkanWindows.cpp * File contains Implementations for Windows-specific code of the Vulkan Implementation * of the graphics interface. */ #include <GoddamnEngine/GraphicsVulkan/GraphicsVulkan.h> #if GD_PLATFORM_WINDOWS //#include <GoddamnEngine/Core/OutputDevice/OutputDevice.h> #define GD_DLOG_CAT "GFX device (Windows@Vulkan)" //! @todo Move this as a dependency. #pragma comment (lib, "opengl32.lib") #include <Windows.h> GD_NAMESPACE_BEGIN // ------------------------------------------------------------------------------------------ //! Function would be called on the global initialization step, before all other interfaces //! are initialized. //! @returns Non-negative value if the operation succeeded. GDAPI IResult IGraphicsVulkanWindows::OnRuntimePreInitialize() { IResult const _BaseResult = IGraphicsPlatform::OnRuntimePreInitialize(); if (IFailed(_BaseResult)) return _BaseResult; // Retrieving information about the list of supported screen resolutions. { DEVMODE HGLRCTestCanvasMode; HGLRCTestCanvasMode.dmSize = sizeof(HGLRCTestCanvasMode); for (DWORD _Cnt = 0; EnumDisplaySettings(nullptr, _Cnt, &HGLRCTestCanvasMode) != GD_FALSE; ++_Cnt) { // Testing current resolution.. if (ChangeDisplaySettings(&HGLRCTestCanvasMode, CDS_TEST) == DISP_CHANGE_SUCCESSFUL) { m_GfxResolutionsList.InsertAt(0, { static_cast<UInt32>(HGLRCTestCanvasMode.dmPelsWidth), static_cast<UInt32>(HGLRCTestCanvasMode.dmPelsHeight), 30, 1 }); m_GfxResolutionsList.InsertAt(0, { static_cast<UInt32>(HGLRCTestCanvasMode.dmPelsWidth), static_cast<UInt32>(HGLRCTestCanvasMode.dmPelsHeight), 60, 1 }); } } } //! @todo Load default parameters. m_GfxCanvasMode = IGRAPHICS_OUTPUT_MODE_WINDOWED; // Easier for debugging purposes. m_GfxResolutionSelected = &m_GfxResolutionsList.GetData()[8]; return IResult::Ok; } // ------------------------------------------------------------------------------------------ //! Function would be called on the global initialization step. //! @returns Non-negative value if the operation succeeded. GDAPI IResult IGraphicsVulkanWindows::OnRuntimeInitialize() { // _CheckNotInitialized(); // ConsoleDevice->Log(GD_DLOG_CAT ": going to initialize graphics devices..."); IResult const _BaseResult = IGraphicsPlatform::OnRuntimeInitialize(); if (IFailed(_BaseResult)) return _BaseResult; return IResult::Ok; } // ------------------------------------------------------------------------------------------ //! Function would be called on the global deinitialization step. //! @returns Non-negative value if the operation succeeded. GDAPI IResult IGraphicsVulkanWindows::OnRuntimeDeinitialize() { return IGraphicsPlatform::OnRuntimeDeinitialize(); } // ------------------------------------------------------------------------------------------ //! Function would be called once per frame, after all other runtime //! interfaces are deinitialized. GDAPI void IGraphicsVulkanWindows::OnRuntimePostUpdate() { //! @todo Uncomment this. IGraphicsPlatform::OnRuntimePostUpdate(); } GD_NAMESPACE_END #endif // if GD_PLATFORM_WINDOWS
39.817204
158
0.649743
GoddamnIndustries
865ced23c38df56f37d80cd8673372031c1aaaad
916
cpp
C++
pellets/harold/harold_server_request_api.cpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
pellets/harold/harold_server_request_api.cpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
pellets/harold/harold_server_request_api.cpp
sinmx/ZPublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
#include "harold_server_request_api.h" int HaroldServerRequestApi::OnRequest(struct mg_connection *conn) { if (conn->uri) { std::string sUri(conn->uri); std::map<std::string, HaroldServerRequestApiFunc>::iterator it = m_mapApiList.find(sUri); if (it != m_mapApiList.end()) { return it->second(conn); } } return 0; } bool HaroldServerRequestApi::InsertApi(const std::string& uri, HaroldServerRequestApiFunc func) { if (uri.size() == 0 || !func) { return false; } m_mapApiList[uri] = func; return true; } bool HaroldServerRequestApi::RemoveApi(const std::string& uri) { if (uri.size() == 0) { return false; } std::map<std::string, HaroldServerRequestApiFunc>::iterator it = m_mapApiList.find(uri); if (it != m_mapApiList.end()) { m_mapApiList.erase(it); } return true; }
22.9
97
0.612445
wohaaitinciu
8661628444d42bad716d097bf25835e95407d4d9
3,167
cpp
C++
utils.cpp
superblocks/superblocks
920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc
[ "Unlicense" ]
3
2018-09-09T10:05:38.000Z
2020-11-06T02:11:46.000Z
utils.cpp
superblocks/superblocks
920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc
[ "Unlicense" ]
null
null
null
utils.cpp
superblocks/superblocks
920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc
[ "Unlicense" ]
null
null
null
// utils.cpp // Superblocks - Version 0.4.3 #include "superblocks.hpp" void Superblocks::timer_start() { cstart = clock(); } float Superblocks::timer_end() { cend = clock() - cstart; return (double)cend / ((double)CLOCKS_PER_SEC); } long Superblocks::gethashcutout( int step, const char* hash ) { if( debug ) { cout << "gethashcutout: step: " << step << endl; cout << "gethashcutout: cutout_start: " << cutout_start[step] << endl; cout << "gethashcutout: cutout_length: " << cutout_length[step] << endl; } int hlen = strlen(hash); if( debug ) { cout << "gethashcutout: srlen(hash): " << hlen << endl; } if( hlen != hash_length ) { cout << "gethashcutout: error: hash length not " << hash_length << endl; return 0; } if( debug ) { cout << "gethashcutout: hash: " << hash << endl; } string hash_string(hash); if( debug ) { cout << "gethashcutout: hash_string: " << hash_string << endl; } std::string cseed_str = hash_string.substr( cutout_start[step], cutout_length[step]); const char* cseed = cseed_str.c_str(); if( debug ) { cout << "gethashcutout: cseed: " << cseed << endl; } long seed = hex2long(cseed); if( debug ) { cout << "gethashcutout: return: seed: " << seed << endl; } return seed; } int /*static*/ Superblocks::generateMTRandom(unsigned int s, int range_low, int range_high) { if( debug ) { cout << "generateMTRandom: seed: " << s << endl; cout << "generateMTRandom: range_low: " << range_low << endl; cout << "generateMTRandom: range_high: " << range_high << endl; } random::mt19937 gen(s); random::uniform_int_distribution<> dist(range_low, range_high); int result = dist(gen); if( debug ) { cout << "generateMTRandom: result: " << result << endl; } return result; } long Superblocks::hex2long(const char* hexString) { static const long hextable[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-19 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 30-39 -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, // 50-59 -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 70-79 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, // 90-99 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 110-109 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 130-139 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 150-159 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 170-179 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 190-199 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 210-219 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 230-239 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; long ret = 0; while (*hexString && ret >= 0) { ret = (ret << 4) | hextable[*hexString++]; } return ret; }
33.336842
92
0.499526
superblocks
866de3a8c64dc4d79bdfe21bc61a547ba9b7638f
4,820
cpp
C++
src/util/Segmentation.cpp
je310/Card1
736671104e46aaf89ddf41cd825d6be24297a464
[ "BSD-3-Clause" ]
141
2015-02-20T18:44:53.000Z
2022-01-06T09:33:05.000Z
src/util/Segmentation.cpp
je310/Card1
736671104e46aaf89ddf41cd825d6be24297a464
[ "BSD-3-Clause" ]
29
2015-02-23T10:05:10.000Z
2019-04-25T03:55:09.000Z
src/util/Segmentation.cpp
je310/Card1
736671104e46aaf89ddf41cd825d6be24297a464
[ "BSD-3-Clause" ]
54
2015-02-23T00:22:53.000Z
2022-01-06T09:33:07.000Z
/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ #include <cstring> #include <cmath> #include "Segmentation.h" #include <cstdlib> namespace Conv { void Segmentation::ExtractPatches (const int patchsize_x, const int patchsize_y, Tensor& target, Tensor& helper, const Tensor& source, const int source_sample, bool substract_mean) { int image_width = source.width(); int image_height = source.height(); unsigned int image_maps = source.maps(); // new version unsigned int npatches = image_width * image_height; int offsetx = (patchsize_x / 2); int offsety = (patchsize_y / 2); target.Resize (npatches, patchsize_x, patchsize_y, image_maps); helper.Resize (npatches, 2); for (int px = 0; px < image_width; px++) { for (int py = 0; py < image_height; py++) { unsigned int element = image_width * py + px; for (int ipy = 0; ipy < patchsize_y; ipy++) { int image_y = py + ipy - offsety; if (image_y < 0) image_y = -image_y; if (image_y >= image_height) image_y = -1 + image_height + image_height - image_y; for (int ipx = 0; ipx < patchsize_x; ipx++) { int image_x = px + ipx - offsetx; if (image_x < 0) image_x = -image_x; if (image_x >= image_width) image_x = -1 + image_width + image_width - image_x; // Copy pixel for (unsigned int map = 0; map < image_maps; map++) { const datum pixel = *source.data_ptr_const (image_x, image_y, map, source_sample); *target.data_ptr (ipx, ipy, map, element) = pixel; } } } // Copy helper data helper[2 * element] = fmax (0.0, fmin (image_height - (patchsize_y - 1), py - offsety)) / image_height; helper[2 * element + 1] = fmax (0.0, fmin (image_width - (patchsize_x - 1), px - offsetx)) / image_width; } } // FIXME make this configurable: KITTI needs it, LMF does not /* for (unsigned int e = 0; e < target.elements(); e++) { target[e] -= 0.5; target[e] *= 2.0; }*/ if (substract_mean) { const unsigned int elements_per_sample = patchsize_x * patchsize_y * image_maps; // substract mean for (unsigned int sample = 0; sample < target.samples(); sample++) { // Add up elements datum sum = 0; for (unsigned int e = 0; e < elements_per_sample; e++) { sum += target[sample * elements_per_sample + e]; } // Calculate mean const datum mean = sum / (datum) elements_per_sample; // Substract mean for (unsigned int e = 0; e < elements_per_sample; e++) { target[sample * elements_per_sample + e] -= mean; } } } } void Segmentation::ExtractLabels (const int patchsize_x, const int patchsize_y, Tensor& labels, Tensor& weight, const Tensor& source, const int source_sample, const int ignore_class) { int image_width = source.width(); int image_height = source.height(); // new version unsigned int npatches = image_width * image_height; int offsetx = (patchsize_x / 2); int offsety = (patchsize_y / 2); labels.Resize (npatches, 1, 1, 1); weight.Resize (npatches); for (int px = 0; px < image_width; px++) { for (int py = 0; py < image_height; py++) { unsigned int element = image_width * py + px; const int ipy = (patchsize_y / 2) + 1; int image_y = py + ipy - offsety; if (image_y < 0) image_y = -image_y; if (image_y >= image_height) image_y = -1 + image_height + image_height - image_y; int ipx = (patchsize_x / 2) + 1; int image_x = px + ipx - offsetx; if (image_x < 0) image_x = -image_x; if (image_x >= image_width) image_x = -1 + image_width + image_width - image_x; // Copy pixel const duint nlabel = * ( (duint*) source.data_ptr_const (image_x, image_y, 0, source_sample)); *labels.data_ptr (0, 0, 0, element) = *source.data_ptr_const (image_x, image_y, 0, source_sample); // Assign weight if (nlabel != ignore_class) *weight.data_ptr (0, 0, 0, element) = 1.0; else *weight.data_ptr (0, 0, 0, element) = 0.0; } } } }
32.348993
89
0.553734
je310
866f9328f465d7491bea0d176dfd120ff44f12c5
1,508
cpp
C++
clove/source/Rendering/Camera.cpp
AGarlicMonkey/Garlic
4f439b789b7db9fc7b2c104705f259c318be62fd
[ "MIT" ]
33
2020-01-09T04:57:29.000Z
2021-08-14T08:02:43.000Z
clove/source/Rendering/Camera.cpp
AGarlicMonkey/Garlic
4f439b789b7db9fc7b2c104705f259c318be62fd
[ "MIT" ]
234
2019-10-25T06:04:35.000Z
2021-08-18T05:47:41.000Z
clove/source/Rendering/Camera.cpp
AGarlicMonkey/Garlic
4f439b789b7db9fc7b2c104705f259c318be62fd
[ "MIT" ]
4
2020-02-11T15:28:42.000Z
2020-09-07T16:22:58.000Z
#include "Clove/Rendering/Camera.hpp" #include "Clove/Rendering/RenderingLog.hpp" #include <Clove/Maths/MathsHelpers.hpp> namespace clove { Camera::Camera(Viewport viewport, ProjectionMode const projection) : viewport{ viewport } , currentProjectionMode{ projection } { setProjectionMode(projection); } Camera::Camera(ProjectionMode const projection) : currentProjectionMode{ projection } { viewport = { 0.0f, 0.0f, 1.0f, 1.0f }; setProjectionMode(projection); } mat4f Camera::getProjection(vec2ui const screenSize) const { float constexpr orthographicSize{ 15.0f }; float constexpr fov{ 45.0f }; float const othoZoom{ orthographicSize * zoomLevel }; float const width{ static_cast<float>(screenSize.x) * viewport.width }; float const height{ static_cast<float>(screenSize.y) * viewport.height }; float const aspect{ height > 0.0f ? width / height : 0.0f }; switch(currentProjectionMode) { case ProjectionMode::Orthographic: return createOrthographicMatrix(-othoZoom * aspect, othoZoom * aspect, -othoZoom, othoZoom, nearPlane, farPlane); case ProjectionMode::Perspective: return createPerspectiveMatrix(fov * zoomLevel, aspect, nearPlane, farPlane); default: CLOVE_ASSERT_MSG(false, "{0}: Case not handled", CLOVE_FUNCTION_NAME_PRETTY); return mat4f{ 1.0f }; } } }
38.666667
129
0.653183
AGarlicMonkey
8671f5b698a2ed5a315728d966df1a15bb486d40
35,579
cpp
C++
src/ListViewDelegate.cpp
BlueDragon28/GameSorting
aef3604038b3084c26c0d4430f81c05a83c0f5de
[ "MIT" ]
null
null
null
src/ListViewDelegate.cpp
BlueDragon28/GameSorting
aef3604038b3084c26c0d4430f81c05a83c0f5de
[ "MIT" ]
null
null
null
src/ListViewDelegate.cpp
BlueDragon28/GameSorting
aef3604038b3084c26c0d4430f81c05a83c0f5de
[ "MIT" ]
null
null
null
/* * MIT Licence * * This file is part of the GameSorting * * Copyright © 2022 Erwan Saclier de la Bâtie (BlueDragon28) * * 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 "ListViewDelegate.h" #include "TableModel_UtilityInterface.h" #include "UtilityInterfaceEditor.h" #include "UtilitySensitiveContentEditor.h" #include "Common.h" #include "TableModel.h" #include "StarEditor.h" #include "UtilityLineEdit.h" #include "Settings.h" #include <iostream> #include <QPainter> #include <QBrush> #include <QColor> #include <QSpinBox> #include <QSqlQuery> #include <QStringList> #include <QSqlError> ListViewDelegate::ListViewDelegate( TableModel* tableModel, SqlUtilityTable& utilityTable, QSqlDatabase& db, QObject* parent) : QStyledItemDelegate(parent), m_tableModel(tableModel), m_utilityTable(utilityTable), m_utilityInterface(m_tableModel->utilityInterface()), m_db(db) {} ListViewDelegate::~ListViewDelegate() {} void ListViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { // Painting the delegate. if (m_tableModel->listType() == ListType::GAMELIST) { if (index.column() == Game::RATE) { // Painting the stars. paintRateStars(painter, option, index); return; } else if (index.column() == Game::SENSITIVE_CONTENT) { paintSensitiveStars(painter, option, index); return; } } else if (m_tableModel->listType() == ListType::MOVIESLIST) { if (index.column() == Movie::RATE) { // Painting the stars. paintRateStars(painter, option, index); return; } else if (index.column() == Movie::SENSITIVE_CONTENT) { paintSensitiveStars(painter, option, index); return; } } else if (m_tableModel->listType() == ListType::COMMONLIST) { if (index.column() == Common::RATE) { // Painting the stars. paintRateStars(painter, option, index); return; } else if (index.column() == Common::SENSITIVE_CONTENT) { paintSensitiveStars(painter, option, index); return; } } else if (m_tableModel->listType() == ListType::BOOKSLIST) { if (index.column() == Books::RATE) { // Painting the starts. paintRateStars(painter, option, index); return; } else if (index.column() == Books::SENSITIVE_CONTENT) { paintSensitiveStars(painter, option, index); return; } } else if (m_tableModel->listType() == ListType::SERIESLIST) { if (index.column() == Series::RATE) { // Painting the stars. paintRateStars(painter, option, index); return; } else if (index.column() == Series::SENSITIVE_CONTENT) { paintSensitiveStars(painter, option, index); return; } } QStyledItemDelegate::paint(painter, option, index); } QSize ListViewDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { // Returning the recommanded size of the field. if (m_tableModel->listType() == ListType::GAMELIST) { if (index.column() == Game::RATE) { return StarEditor::sizeHint(5); } else if (index.column() == Game::SENSITIVE_CONTENT) { return QSize((int)StarEditor::paintFactor() * 15, 1); } } else if (m_tableModel->listType() == ListType::MOVIESLIST) { if (index.column() == Movie::RATE) { return StarEditor::sizeHint(5); } else if (index.column() == Movie::SENSITIVE_CONTENT) { return QSize((int)StarEditor::paintFactor() * 15, 1); } } else if (m_tableModel->listType() == ListType::COMMONLIST) { if (index.column() == Common::RATE) { return StarEditor::sizeHint(5); } else if (index.column() == Common::SENSITIVE_CONTENT) { return QSize((int)StarEditor::paintFactor() * 15, 1); } } else if (m_tableModel->listType() == ListType::BOOKSLIST) { if (index.column() == Books::RATE) { return StarEditor::sizeHint(5); } else if (index.column() == Books::SENSITIVE_CONTENT) { return QSize((int)StarEditor::paintFactor() * 15, 1); } } else if (m_tableModel->listType() == ListType::SERIESLIST) { if (index.column() == Series::RATE) { return StarEditor::sizeHint(5); } else if (index.column() == Series::SENSITIVE_CONTENT) { return QSize((int)StarEditor::paintFactor() * 15, 1); } } return QStyledItemDelegate::sizeHint(option, index); } QWidget* ListViewDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const { // Creating the editor if (m_tableModel->listType() == ListType::GAMELIST) { if (index.column() == Game::RATE) { // Creating the editor for the edition of the rate column. if (option.rect.width() >= 5 * StarEditor::paintFactor()) { StarEditor* editor = new StarEditor(parent); connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor); return editor; } else { QSpinBox* editor = new QSpinBox(parent); editor->setRange(0, 5); editor->setSingleStep(1); return editor; } } else if (index.column() == Game::SERIES || index.column() == Game::CATEGORIES || index.column() == Game::DEVELOPPERS || index.column() == Game::PUBLISHERS || index.column() == Game::PLATFORMS || index.column() == Game::SERVICES) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilityTableName tableName; if (index.column() == Game::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Game::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Game::DEVELOPPERS) tableName = UtilityTableName::DEVELOPPERS; else if (index.column() == Game::PUBLISHERS) tableName = UtilityTableName::PUBLISHERS; else if (index.column() == Game::PLATFORMS) tableName = UtilityTableName::PLATFORM; else if (index.column() == Game::SERVICES) tableName = UtilityTableName::SERVICES; if (!Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = new UtilityLineEdit( tableName, m_utilityTable, m_db, parent); return editor; } else { UtilityInterfaceEditor* editor = new UtilityInterfaceEditor( tableName, itemID, m_tableModel, m_utilityInterface, m_utilityTable, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (index.column() == Game::SENSITIVE_CONTENT) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilitySensitiveContentEditor* editor = new UtilitySensitiveContentEditor( itemID, m_utilityInterface, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (m_tableModel->listType() == ListType::MOVIESLIST) { if (index.column() == Movie::RATE) { // Creating the editor for the edition of the rate column. if (option.rect.width() >= 5 * StarEditor::paintFactor()) { StarEditor* editor = new StarEditor(parent); connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor); return editor; } else { QSpinBox* editor = new QSpinBox(parent); editor->setRange(0, 5); editor->setSingleStep(1); return editor; } } else if (index.column() >= Movie::SERIES && index.column() <= Movie::SERVICES) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilityTableName tableName; if (index.column() == Movie::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Movie::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Movie::DIRECTORS) tableName = UtilityTableName::DIRECTOR; else if (index.column() == Movie::ACTORS) tableName = UtilityTableName::ACTORS; else if (index.column() == Movie::PRODUCTIONS) tableName = UtilityTableName::PRODUCTION; else if (index.column() == Movie::MUSIC) tableName = UtilityTableName::MUSIC; else if (index.column() == Movie::SERVICES) tableName = UtilityTableName::SERVICES; if (!Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = new UtilityLineEdit( tableName, m_utilityTable, m_db, parent); return editor; } else { UtilityInterfaceEditor* editor = new UtilityInterfaceEditor( tableName, itemID, m_tableModel, m_utilityInterface, m_utilityTable, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (index.column() == Movie::SENSITIVE_CONTENT) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilitySensitiveContentEditor* editor = new UtilitySensitiveContentEditor( itemID, m_utilityInterface, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (m_tableModel->listType() == ListType::COMMONLIST) { if (index.column() == Common::RATE) { // Creating the editor for the edition of the rate column. if (option.rect.width() >= 5 * StarEditor::paintFactor()) { StarEditor* editor = new StarEditor(parent); connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor); return editor; } else { QSpinBox* editor = new QSpinBox(parent); editor->setRange(0, 5); editor->setSingleStep(1); return editor; } } else if (index.column() == Common::SERIES || index.column() == Common::CATEGORIES || index.column() == Common::AUTHORS) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilityTableName tableName; if (index.column() == Common::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Common::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Common::AUTHORS) tableName = UtilityTableName::AUTHORS; if (!Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = new UtilityLineEdit( tableName, m_utilityTable, m_db, parent); return editor; } else { UtilityInterfaceEditor* editor = new UtilityInterfaceEditor( tableName, itemID, m_tableModel, m_utilityInterface, m_utilityTable, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (index.column() == Common::SENSITIVE_CONTENT) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilitySensitiveContentEditor* editor = new UtilitySensitiveContentEditor( itemID, m_utilityInterface, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (m_tableModel->listType() == ListType::BOOKSLIST) { if (index.column() == Books::RATE) { // Creating the editor for the edition of the rate column. if (option.rect.width() >= 5 * StarEditor::paintFactor()) { StarEditor* editor = new StarEditor(parent); connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor); return editor; } else { QSpinBox* editor = new QSpinBox(parent); editor->setRange(0, 5); editor->setSingleStep(1); return editor; } } else if (index.column() == Books::SERIES || index.column() == Books::CATEGORIES || index.column() == Books::AUTHORS || index.column() == Books::PUBLISHERS || index.column() == Books::SERVICES) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilityTableName tableName; if (index.column() == Books::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Books::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Books::AUTHORS) tableName = UtilityTableName::AUTHORS; else if (index.column() == Books::PUBLISHERS) tableName = UtilityTableName::PUBLISHERS; else if (index.column() == Books::SERVICES) tableName = UtilityTableName::SERVICES; if (!Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = new UtilityLineEdit( tableName, m_utilityTable, m_db, parent); return editor; } else { UtilityInterfaceEditor* editor = new UtilityInterfaceEditor( tableName, itemID, m_tableModel, m_utilityInterface, m_utilityTable, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (index.column() == Books::SENSITIVE_CONTENT) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilitySensitiveContentEditor* editor = new UtilitySensitiveContentEditor( itemID, m_utilityInterface, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (m_tableModel->listType() == ListType::SERIESLIST) { if (index.column() == Series::RATE) { // Creating the editor for the edition of the rate column. if (option.rect.width() >= 5 * StarEditor::paintFactor()) { StarEditor* editor = new StarEditor(parent); connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor); return editor; } else { QSpinBox* editor = new QSpinBox(parent); editor->setRange(0, 5); editor->setSingleStep(1); return editor; } } else if (index.column() == Series::EPISODE || index.column() == Series::SEASON) { // Creating the editor for the episode column. QSpinBox* editor = new QSpinBox(parent); editor->setRange(0, 0x7FFFFFFF); editor->setSingleStep(1); return editor; } else if (index.column() == Series::CATEGORIES || index.column() == Series::DIRECTORS || index.column() == Series::ACTORS || index.column() == Series::PRODUCTION || index.column() == Series::MUSIC || index.column() == Series::SERVICES) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilityTableName tableName; if (index.column() == Series::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Series::DIRECTORS) tableName = UtilityTableName::DIRECTOR; else if (index.column() == Series::ACTORS) tableName = UtilityTableName::ACTORS; else if (index.column() == Series::PRODUCTION) tableName = UtilityTableName::PRODUCTION; else if (index.column() == Series::MUSIC) tableName = UtilityTableName::MUSIC; else if (index.column() == Series::SERVICES) tableName = UtilityTableName::SERVICES; if (!Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = new UtilityLineEdit( tableName, m_utilityTable, m_db, parent); return editor; } else { UtilityInterfaceEditor* editor = new UtilityInterfaceEditor( tableName, itemID, m_tableModel, m_utilityInterface, m_utilityTable, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } else if (index.column() == Series::SENSITIVE_CONTENT) { long long int itemID = m_tableModel->itemID(index); if (itemID <= 0) return nullptr; UtilitySensitiveContentEditor* editor = new UtilitySensitiveContentEditor( itemID, m_utilityInterface, m_db, parent); editor->raise(); editor->activateWindow(); editor->show(); return nullptr; } } return QStyledItemDelegate::createEditor(parent, option, index); } void ListViewDelegate::setEditorData(QWidget* e, const QModelIndex& index) const { // Setting the fild data to the editor. const TableModel* model = reinterpret_cast<const TableModel*>(index.model()); if (model->listType() == ListType::GAMELIST) { if (index.column() == Game::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { starEditor->setStars(index.data().toInt()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { spinEditor->setValue(index.data().toInt()); return; } } else if (index.column() >= Game::SERIES && index.column() <= Game::SERVICES && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Game::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Game::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Game::DEVELOPPERS) tableName = UtilityTableName::DEVELOPPERS; else if (index.column() == Game::PUBLISHERS) tableName = UtilityTableName::PUBLISHERS; else if (index.column() == Game::PLATFORMS) tableName = UtilityTableName::PLATFORM; else if (index.column() == Game::SERVICES) tableName = UtilityTableName::SERVICES; editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName)); return; } } } else if (model->listType() == ListType::MOVIESLIST) { if (index.column() == Movie::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { starEditor->setStars(index.data().toInt()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { spinEditor->setValue(index.data().toInt()); return; } } else if (index.column() >= Movie::SERIES && index.column() <= Movie::SERVICES && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Movie::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Movie::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Movie::DIRECTORS) tableName = UtilityTableName::DIRECTOR; else if (index.column() == Movie::ACTORS) tableName = UtilityTableName::ACTORS; else if (index.column() == Movie::PRODUCTIONS) tableName = UtilityTableName::PRODUCTION; else if (index.column() == Movie::MUSIC) tableName = UtilityTableName::MUSIC; else if (index.column() == Movie::SERVICES) tableName = UtilityTableName::SERVICES; editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName)); return; } } } else if (model->listType() == ListType::COMMONLIST) { if (index.column() == Common::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { starEditor->setStars(index.data().toInt()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { spinEditor->setValue(index.data().toInt()); return; } } else if (index.column() >= Common::SERIES && index.column() <= Common::AUTHORS && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Common::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Common::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Common::AUTHORS) tableName = UtilityTableName::AUTHORS; editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName)); return; } } } else if (model->listType() == ListType::BOOKSLIST) { if (index.column() == Books::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { starEditor->setStars(index.data().toInt()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { spinEditor->setValue(index.data().toInt()); return; } } else if (index.column() >= Books::SERIES && index.column() <= Books::SERVICES && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Books::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Books::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Books::AUTHORS) tableName = UtilityTableName::AUTHORS; else if (index.column() == Books::PUBLISHERS) tableName = UtilityTableName::PUBLISHERS; else if (index.column() == Books::SERVICES) tableName = UtilityTableName::SERVICES; editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName)); return; } } } else if (model->listType() == ListType::SERIESLIST) { if (index.column() == Series::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { starEditor->setStars(index.data().toInt()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { spinEditor->setValue(index.data().toInt()); return; } } else if (index.column() >= Series::CATEGORIES && index.column() <= Series::SERVICES && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Series::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Series::DIRECTORS) tableName = UtilityTableName::DIRECTOR; else if (index.column() == Series::ACTORS) tableName = UtilityTableName::ACTORS; else if (index.column() == Series::PRODUCTION) tableName = UtilityTableName::PRODUCTION; else if (index.column() == Series::MUSIC) tableName = UtilityTableName::MUSIC; else if (index.column() == Series::SERVICES) tableName = UtilityTableName::SERVICES; editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName)); return; } } } return QStyledItemDelegate::setEditorData(e, index); } void ListViewDelegate::setModelData(QWidget* e, QAbstractItemModel* m, const QModelIndex& index) const { // When the edit is finished, apply the editor data to the field. TableModel* model = reinterpret_cast<TableModel*>(m); if (model->listType() == ListType::GAMELIST) { if (index.column() == Game::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { model->setData(index, starEditor->stars()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { model->setData(index, spinEditor->value()); return; } } else if (index.column() >= Game::SERIES && index.column() <= Game::SERVICES && !Settings::instance().isLegacyUtilEditor()) { // Retrieve data from the UtilityLineEdit and appending it into the utilityInterface. UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Game::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Game::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Game::DEVELOPPERS) tableName = UtilityTableName::DEVELOPPERS; else if (index.column() == Game::PUBLISHERS) tableName = UtilityTableName::PUBLISHERS; else if (index.column() == Game::PLATFORMS) tableName = UtilityTableName::PLATFORM; else if (index.column() == Game::SERVICES) tableName = UtilityTableName::SERVICES; applyUtilityLineEditData(itemID, tableName, editor->text()); return; } } } else if (model->listType() == ListType::MOVIESLIST) { if (index.column() == Movie::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { model->setData(index, starEditor->stars()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { model->setData(index, spinEditor->value()); return; } } else if (index.column() >= Movie::SERIES && index.column() <= Movie::SERVICES && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Movie::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Movie::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Movie::DIRECTORS) tableName = UtilityTableName::DIRECTOR; else if (index.column() == Movie::ACTORS) tableName = UtilityTableName::ACTORS; else if (index.column() == Movie::PRODUCTIONS) tableName = UtilityTableName::PRODUCTION; else if (index.column() == Movie::MUSIC) tableName = UtilityTableName::MUSIC; else if (index.column() == Movie::SERVICES) tableName = UtilityTableName::SERVICES; applyUtilityLineEditData(itemID, tableName, editor->text()); return; } } } else if (model->listType() == ListType::COMMONLIST) { if (index.column() == Common::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { model->setData(index, starEditor->stars()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { model->setData(index, spinEditor->value()); return; } } else if (index.column() >= Common::SERIES && index.column() <= Common::AUTHORS && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Common::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Common::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Common::AUTHORS) tableName = UtilityTableName::AUTHORS; applyUtilityLineEditData(itemID, tableName, editor->text()); return; } } } else if (model->listType() == ListType::BOOKSLIST) { if (index.column() == Books::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { model->setData(index, starEditor->stars()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { model->setData(index, spinEditor->value()); return; } } else if (index.column() >= Books::SERIES && index.column() <= Books::SERVICES && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Books::SERIES) tableName = UtilityTableName::SERIES; else if (index.column() == Books::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Books::AUTHORS) tableName = UtilityTableName::AUTHORS; else if (index.column() == Books::PUBLISHERS) tableName = UtilityTableName::PUBLISHERS; else if (index.column() == Books::SERVICES) tableName = UtilityTableName::SERVICES; applyUtilityLineEditData(itemID, tableName, editor->text()); return; } } } else if (model->listType() == ListType::SERIESLIST) { if (index.column() == Series::RATE) { StarEditor* starEditor = dynamic_cast<StarEditor*>(e); if (starEditor) { model->setData(index, starEditor->stars()); return; } QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e); if (spinEditor) { model->setData(index, spinEditor->value()); return; } } else if (index.column() >= Series::CATEGORIES && index.column() <= Series::SERVICES && !Settings::instance().isLegacyUtilEditor()) { UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e); if (editor) { long long int itemID = m_tableModel->itemID(index); UtilityTableName tableName; if (index.column() == Series::CATEGORIES) tableName = UtilityTableName::CATEGORIES; else if (index.column() == Series::DIRECTORS) tableName = UtilityTableName::DIRECTOR; else if (index.column() == Series::ACTORS) tableName = UtilityTableName::ACTORS; else if (index.column() == Series::PRODUCTION) tableName = UtilityTableName::PRODUCTION; else if (index.column() == Series::MUSIC) tableName = UtilityTableName::MUSIC; else if (index.column() == Series::SERVICES) tableName = UtilityTableName::SERVICES; applyUtilityLineEditData(itemID, tableName, editor->text()); return; } } } return QStyledItemDelegate::setModelData(e, m, index); } void ListViewDelegate::commitAndCloseEditor(QWidget* editor) { // Commit the data of the editor and close it. if (editor) { emit commitData(editor); emit closeEditor(editor); } } void ListViewDelegate::paintSensitiveStars(QPainter* painter, const QStyleOptionViewItem& options, const QModelIndex& index) const { // Paint the stars of the three categories of sensitive content items. painter->setRenderHint(QPainter::Antialiasing, true); painter->save(); if (options.rect.width() >= 15 * StarEditor::paintFactor()) { QPolygonF starPolygons = StarEditor::polygonData(); // Sensitive Content painter->setPen(Qt::NoPen); painter->setBrush(QBrush(QColor(255, 0, 0))); QRect rect = options.rect; painter->translate(rect.x() + StarEditor::paintFactor() * 0.55, rect.y() + (rect.height() / 2.)); painter->scale(StarEditor::paintFactor(), StarEditor::paintFactor()); for (int i = 0; i < 3; i++) { QColor color; if (i == 0) color = QColor(255, 0, 0); else if (i == 1) color = QColor(0, 255, 0); else color = QColor(0, 0, 255); painter->setBrush(QBrush(color)); int numStars; if (i == 0) numStars = qvariant_cast<SensitiveContent>(index.data()).explicitContent; else if (i == 1) numStars = qvariant_cast<SensitiveContent>(index.data()).violenceContent; else if (i == 2) numStars = qvariant_cast<SensitiveContent>(index.data()).badLanguageContent; for (int j = 0; j < 5; j++) { if (j < numStars) painter->drawPolygon(starPolygons, Qt::WindingFill); painter->translate(1, 0); } } } else { QString sensText = QString("%1 %2 %3") .arg(qvariant_cast<SensitiveContent>(index.data()).explicitContent) .arg(qvariant_cast<SensitiveContent>(index.data()).violenceContent) .arg(qvariant_cast<SensitiveContent>(index.data()).badLanguageContent); QFont font = painter->font(); font.setPixelSize(20); painter->setFont(font); painter->setPen(Qt::SolidLine); painter->drawText(options.rect, sensText); } painter->restore(); } void ListViewDelegate::paintRateStars(QPainter* painter, const QStyleOptionViewItem& options, const QModelIndex& index) const { if (options.rect.width() >= 5 * StarEditor::paintFactor()) StarEditor::paintStars(index.data().toInt(), painter, options.rect, options.palette); else { QString starNB = QString::number(index.data().toInt()); QFont font = painter->font(); font.setPixelSize(20); painter->setFont(font); painter->setPen(Qt::SolidLine); painter->drawText(options.rect, starNB); } } void ListViewDelegate::applyUtilityLineEditData(long long int itemID, UtilityTableName tableName, const QString& utilityText) const { if (itemID <= 0) return; QStringList utilityList = utilityText.split(',', Qt::SkipEmptyParts); QList<long long int> utilityIDs; foreach(const QString& item, utilityList) { if (!item.trimmed().isEmpty()) utilityIDs.append(m_utilityTable.addItem(tableName, item.trimmed())); } m_utilityInterface->updateItemUtility(itemID, tableName, QVariant::fromValue(utilityIDs)); } QString ListViewDelegate::retrieveDataForUtilityLineEdit(long long int itemID, UtilityTableName tableName) const { if (itemID <= 0) return ""; QString statement = QString( "SELECT\n" " UtilityID\n" "FROM\n" " \"%1\"" "WHERE\n" " ItemID = %2;") .arg(m_utilityInterface->tableName(tableName)).arg(itemID); #ifndef NDEBUG std::cout << statement.toLocal8Bit().constData() << '\n' << std::endl; #endif QSqlQuery query(m_db); QList<long long int> utilityIDs; if (query.exec(statement)) { while (query.next()) utilityIDs.append(query.value(0).toLongLong()); } else { #ifndef NDEBUG std::cerr << QString("Failed to retrieve utility id from utility interface table %1 of itemID %2.\n\t%3") .arg(m_utilityInterface->tableName(tableName)).arg(itemID) .arg(query.lastError().text()) .toLocal8Bit().constData() << '\n' << std::endl; #endif return ""; } query.clear(); if (utilityIDs.isEmpty()) return ""; statement = QString( "SELECT\n" " Name\n" "FROM\n" " \"%1\"\n" "WHERE\n" " \"%1ID\" = %2;") .arg(SqlUtilityTable::tableName(tableName)); #ifndef NDEBUG std::cout << statement.toLocal8Bit().constData() << '\n' << std::endl; #endif QStringList strUtilityList; foreach(long long int id, utilityIDs) { if (query.exec(statement.arg(id))) { if (query.next()) strUtilityList.append(query.value(0).toString()); } else { #ifndef NDEBUG std::cerr << QString("Failed to retrieve utility name list from table %1\n\t%2") .arg(SqlUtilityTable::tableName(tableName), query.lastError().text()) .toLocal8Bit().constData() << '\n' << std::endl; #endif return ""; } } if (strUtilityList.isEmpty()) return ""; QString strUtilityName; for (int i = 0; i < strUtilityList.size(); i++) { if (i > 0) strUtilityName += ", "; strUtilityName += strUtilityList.at(i); } return strUtilityName; }
27.644911
159
0.6632
BlueDragon28
8672fb62615b4a3e3f2502d37e8c9d25348d19ca
561
cpp
C++
Shape Class/rectangle.cpp
tj-dunham/CS1C_Project
2c8f329a67a142c2ee2f7426047f0c3f51656169
[ "MIT" ]
1
2021-09-22T20:38:14.000Z
2021-09-22T20:38:14.000Z
Shape Class/rectangle.cpp
korieliaz/2D-Graphics-Modeler
2c8f329a67a142c2ee2f7426047f0c3f51656169
[ "MIT" ]
null
null
null
Shape Class/rectangle.cpp
korieliaz/2D-Graphics-Modeler
2c8f329a67a142c2ee2f7426047f0c3f51656169
[ "MIT" ]
null
null
null
#include "rectangle.h" void Rectangle::draw() { painter.setPen(pen); painter.setBrush(brush); painter.drawRect(position.x(), position.y(), shapeDimensions[int(Specifications::W)], shapeDimensions[int(Specifications::H)]); painter.drawText(position.x(), position.y(), 20, 20, Qt::AlignLeft, QString::number(shapeId)); } void Rectangle::move(const QPoint &shift) { position += shift; } void Rectangle::setPosition() { position = {shapeDimensions[int(Specifications::X1)], shapeDimensions[int(Specifications::Y1)]}; }
28.05
132
0.682709
tj-dunham
86738ebc0b81dd3072f5753cd79f650e556d3b2a
4,259
cpp
C++
code/scripting/api/objs/event.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
307
2015-04-10T13:27:32.000Z
2022-03-21T03:30:38.000Z
code/scripting/api/objs/event.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
2,231
2015-04-27T10:47:35.000Z
2022-03-31T19:22:37.000Z
code/scripting/api/objs/event.cpp
trgswe/fs2open.github.com
a159eba0cebca911ad14a118412fddfe5be8e9f8
[ "Unlicense" ]
282
2015-01-05T12:16:57.000Z
2022-03-28T04:45:11.000Z
#include "event.h" #include "scripting/ade_args.h" #include "scripting/ade.h" #include "mission/missiongoals.h" namespace scripting { namespace api { //**********HANDLE: event ADE_OBJ(l_Event, int, "event", "Mission event handle"); ADE_VIRTVAR(Name, l_Event, "string", "Mission event name", "string", NULL) { int idx; const char* s = nullptr; if (!ade_get_args(L, "o|s", l_Event.Get(&idx), &s)) return ade_set_error(L, "s", ""); if (idx < 0 || idx >= Num_mission_events) return ade_set_error(L, "s", ""); mission_event *mep = &Mission_events[idx]; if (ADE_SETTING_VAR) { auto len = sizeof(mep->name); strncpy(mep->name, s, len); mep->name[len - 1] = 0; } return ade_set_args(L, "s", mep->name); } ADE_VIRTVAR(DirectiveText, l_Event, "string", "Directive text", "string", NULL) { int idx; const char* s = nullptr; if (!ade_get_args(L, "o|s", l_Event.Get(&idx), &s)) return ade_set_error(L, "s", ""); if (idx < 0 || idx >= Num_mission_events) return ade_set_error(L, "s", ""); mission_event *mep = &Mission_events[idx]; if (ADE_SETTING_VAR && s != NULL) { if (mep->objective_text != NULL) vm_free(mep->objective_text); mep->objective_text = vm_strdup(s); } if (mep->objective_text != NULL) return ade_set_args(L, "s", mep->objective_text); else return ade_set_args(L, "s", ""); } ADE_VIRTVAR(DirectiveKeypressText, l_Event, "string", "Raw directive keypress text, as seen in FRED.", "string", NULL) { int idx; const char* s = nullptr; if (!ade_get_args(L, "o|s", l_Event.Get(&idx), &s)) return ade_set_error(L, "s", ""); if (idx < 0 || idx >= Num_mission_events) return ade_set_error(L, "s", ""); mission_event *mep = &Mission_events[idx]; if (ADE_SETTING_VAR && s != NULL) { if (mep->objective_text != NULL) vm_free(mep->objective_key_text); mep->objective_key_text = vm_strdup(s); } if (mep->objective_key_text != NULL) return ade_set_args(L, "s", mep->objective_key_text); else return ade_set_args(L, "s", ""); } ADE_VIRTVAR(Interval, l_Event, "number", "Time for event to repeat (in seconds)", "number", "Repeat time, or 0 if invalid handle") { int idx; int newinterval = 0; if (!ade_get_args(L, "o|i", l_Event.Get(&idx), &newinterval)) return ade_set_error(L, "i", 0); if (idx < 0 || idx >= Num_mission_events) return ade_set_error(L, "i", 0); mission_event *mep = &Mission_events[idx]; if (ADE_SETTING_VAR) { mep->interval = newinterval; } return ade_set_args(L, "i", mep->interval); } ADE_VIRTVAR(ObjectCount, l_Event, "number", "Number of objects left for event", "number", "Repeat count, or 0 if invalid handle") { int idx; int newobject = 0; if (!ade_get_args(L, "o|i", l_Event.Get(&idx), &newobject)) return ade_set_error(L, "i", 0); if (idx < 0 || idx >= Num_mission_events) return ade_set_error(L, "i", 0); mission_event *mep = &Mission_events[idx]; if (ADE_SETTING_VAR) { mep->count = newobject; } return ade_set_args(L, "i", mep->count); } ADE_VIRTVAR(RepeatCount, l_Event, "number", "Event repeat count", "number", "Repeat count, or 0 if invalid handle") { int idx; int newrepeat = 0; if (!ade_get_args(L, "o|i", l_Event.Get(&idx), &newrepeat)) return ade_set_error(L, "i", 0); if (idx < 0 || idx >= Num_mission_events) return ade_set_error(L, "i", 0); mission_event *mep = &Mission_events[idx]; if (ADE_SETTING_VAR) { mep->repeat_count = newrepeat; } return ade_set_args(L, "i", mep->repeat_count); } ADE_VIRTVAR(Score, l_Event, "number", "Event score", "number", "Event score, or 0 if invalid handle") { int idx; int newscore = 0; if (!ade_get_args(L, "o|i", l_Event.Get(&idx), &newscore)) return ade_set_error(L, "i", 0); if (idx < 0 || idx >= Num_mission_events) return ade_set_error(L, "i", 0); mission_event *mep = &Mission_events[idx]; if (ADE_SETTING_VAR) { mep->score = newscore; } return ade_set_args(L, "i", mep->score); } ADE_FUNC(isValid, l_Event, NULL, "Detects whether handle is valid", "boolean", "true if valid, false if handle is invalid, nil if a syntax/type error occurs") { int idx; if (!ade_get_args(L, "o", l_Event.Get(&idx))) return ADE_RETURN_NIL; if (idx < 0 || idx >= Num_mission_events) return ADE_RETURN_FALSE; return ADE_RETURN_TRUE; } } }
24.337143
158
0.663066
trgswe
8674954e5e0660fe3628659d0f7adf8ebac6c008
7,110
cpp
C++
ROF_Engine/ModuleResourceManager.cpp
RogerOlasz/ROF_Engine
5c379ab51da85148a135863c8e01c4aa9f06701b
[ "MIT" ]
null
null
null
ROF_Engine/ModuleResourceManager.cpp
RogerOlasz/ROF_Engine
5c379ab51da85148a135863c8e01c4aa9f06701b
[ "MIT" ]
null
null
null
ROF_Engine/ModuleResourceManager.cpp
RogerOlasz/ROF_Engine
5c379ab51da85148a135863c8e01c4aa9f06701b
[ "MIT" ]
null
null
null
#include "ModuleResourceManager.h" #include "Application.h" #include "ModuleFileSystem.h" #include "ModuleSceneImporter.h" #include "Globals.h" #include "XMLUtilities.h" #include "ResourceMesh.h" #include "ResourceTexture.h" #include "ResourceMaterial.h" #include "MeshLoader.h" #include "TextureLoader.h" #include "MaterialLoader.h" ModuleResourceManager::ModuleResourceManager(Application* app, bool start_enabled) : Module(app, start_enabled) { name.assign("ResourceManager"); } ModuleResourceManager::~ModuleResourceManager() { } bool ModuleResourceManager::Init() { LoadResourcesData(); return true; } bool ModuleResourceManager::CleanUp() { SaveResourcesData(); std::map<Uint32, Resource*>::iterator it = resources.begin(); while(it != resources.end()) { if (it->second->IsOnMemory()) { it->second->UnloadFromMemory(); } RELEASE(it->second); it = resources.erase(it); } return true; } Resource* ModuleResourceManager::LoadResource(Uint32 ID, Resource::ResType type) { Resource* ret = nullptr; std::map<Uint32, Resource*>::iterator it = resources.find(ID); if (it != resources.end()) { ret = it->second; if (!it->second->IsOnMemory()) { ret->LoadOnMemory(); } it->second->on_use++; if (type == Resource::ResType::Material) { if (((ResourceMaterial*)it->second)->resource_texture_id != 0) { ((ResourceMaterial*)it->second)->texture = (ResourceTexture*)GetResource(((ResourceMaterial*)it->second)->resource_texture_id); ((ResourceMaterial*)it->second)->texture->on_use++; if (!((ResourceMaterial*)it->second)->texture->IsOnMemory()) { ((ResourceMaterial*)it->second)->texture->LoadOnMemory(); } } } } else { LOG("Resource must have been imported before load on memory."); } return ret; } Resource* ModuleResourceManager::CreateAndLoad(Uint32 ID, Resource::ResType type) { Resource* ret = nullptr; std::map<Uint32, Resource*>::iterator it = resources.find(ID); if (it != resources.end()) { LOG("Resource is already imported."); ret = it->second; } else { switch (type) { case (Resource::ResType::Mesh) : { ret = App->importer->mesh_loader->MeshLoad(ID); break; } case (Resource::ResType::Texture) : { ret = App->importer->tex_loader->TextureLoad(ID); break; } case (Resource::ResType::Material) : { ret = App->importer->mat_loader->MaterialLoad(ID); break; } } if (ret != nullptr) { resources[ID] = ret; } } return ret; } void ModuleResourceManager::SaveResourcesData() { pugi::xml_document data; pugi::xml_node root; root = data.append_child("Resources"); std::map<Uint32, Resource*>::iterator it = resources.begin(); while (it != resources.end()) { root = root.append_child("Resource"); root.append_child("ID").append_attribute("Value") = it->second->ID; root.append_child("Name").text().set(it->second->name.c_str()); root.append_child("Type").append_attribute("Value") = it->second->GetType(); root.append_child("OriginalFile").text().set(it->second->origin_file.c_str()); root.append_child("ResourceFile").text().set(it->second->resource_file.c_str()); root = root.parent(); it++; } root.append_child("NextID").append_attribute("Value") = next_id; std::stringstream stream; data.save(stream); App->physfs->Save("Library/Resources.xml", stream.str().c_str(), stream.str().length()); } void ModuleResourceManager::LoadResourcesData() { char* buffer; uint size = App->physfs->Load("Library/Resources.xml", &buffer); if (size > 0) { pugi::xml_document data; pugi::xml_node root; pugi::xml_parse_result result = data.load_buffer(buffer, size); RELEASE_ARRAY(buffer); if (result != 0) { root = data.child("Resources"); for (pugi::xml_node node = root.child("Resource"); node != nullptr; node = node.next_sibling("Resource")) { //Create resources with recived data Resource* tmp = CreateAndLoad(node.child("ID").attribute("Value").as_ullong(), (Resource::ResType)node.child("Type").attribute("Value").as_int()); tmp->name = node.child("Name").text().get(); tmp->origin_file = node.child("OriginalFile").text().get(); } next_id = root.child("NextID").attribute("Value").as_ullong(); } } } ResourceMesh* ModuleResourceManager::ImportMeshResource(const aiMesh* ai_mesh, const char* origin_file, const char* resource_name) { ResourceMesh* r_mesh = nullptr; r_mesh = (ResourceMesh*)SearchResource(origin_file, resource_name, Resource::ResType::Mesh); if (r_mesh != nullptr) { return r_mesh; } //If doesn't exist, import it -> it should be a method from scene importer r_mesh = App->importer->mesh_loader->MeshImport(ai_mesh, next_id++, origin_file, resource_name); if (r_mesh) { resources[r_mesh->ID] = r_mesh; } return r_mesh; } ResourceMaterial* ModuleResourceManager::ImportMaterialResource(const aiMaterial* ai_material, const char* origin_file, const char* resource_name) { ResourceMaterial* r_mat = nullptr; r_mat = (ResourceMaterial*)SearchResource(origin_file, resource_name, Resource::ResType::Material); if (r_mat != nullptr) { return r_mat; } //If doesn't exist, import it -> it should be a method from scene importer r_mat = App->importer->mat_loader->MaterialImport(ai_material, next_id++, origin_file, resource_name); if (r_mat) { resources[r_mat->ID] = r_mat; } return r_mat; } ResourceTexture* ModuleResourceManager::ImportTextureResource(const aiMaterial* ai_material, const char* origin_file, const char* resource_name) { ResourceTexture* r_tex = nullptr; r_tex = (ResourceTexture*)SearchResource(origin_file, resource_name, Resource::ResType::Texture); if (r_tex != nullptr) { return r_tex; } //If doesn't exist, import it -> it should be a method from scene importer r_tex = App->importer->tex_loader->TextureImport(ai_material, next_id++, resource_name); if (r_tex) { resources[r_tex->ID] = r_tex; } return r_tex; } bool ModuleResourceManager::CompareResource(Resource* res, const char* o_file, const char* r_name) { return (res->origin_file == o_file && res->name == r_name); } bool ModuleResourceManager::CompareResource(Resource* res, Resource::ResType type) { return (res->GetType() == type); } Resource* ModuleResourceManager::GetResource(Uint32 ID) { std::map<Uint32, Resource*>::iterator tmp = resources.find(ID); if (tmp != resources.end()) { return tmp->second; } return nullptr; } bool ModuleResourceManager::SearchForOriginFile(const char* origin_file) { for (std::map<Uint32, Resource*>::iterator tmp = resources.begin(); tmp != resources.end(); tmp++) { if (tmp->second->origin_file == origin_file) { return true; } } return false; } Resource* ModuleResourceManager::SearchResource(const char* origin_file, const char* resource_name, Resource::ResType type) { for (std::map<Uint32, Resource*>::iterator tmp = resources.begin(); tmp != resources.end(); tmp++) { if (CompareResource(tmp->second, origin_file, resource_name) && CompareResource(tmp->second, type)) { return tmp->second; } } return nullptr; }
24.773519
150
0.697468
RogerOlasz
86751774ee16587ad9db173108fa1bb19ec90bde
2,653
hpp
C++
integration/vertex/VertexBuffer.hpp
DomRe/3DRenderer
a43230704889e03206638f6bb74509541a610677
[ "MIT" ]
19
2020-02-02T16:36:46.000Z
2021-12-25T07:02:28.000Z
integration/vertex/VertexBuffer.hpp
DomRe/3DRenderer
a43230704889e03206638f6bb74509541a610677
[ "MIT" ]
103
2020-10-13T09:03:42.000Z
2022-03-26T03:41:50.000Z
integration/vertex/VertexBuffer.hpp
DomRe/3DRenderer
a43230704889e03206638f6bb74509541a610677
[ "MIT" ]
5
2020-03-13T06:14:37.000Z
2021-12-12T02:13:46.000Z
/// /// VertexBuffer.hpp /// galaxy /// /// Refer to LICENSE.txt for more details. /// #ifndef GALAXY_GRAPHICS_VERTEX_VERTEXBUFFER_HPP_ #define GALAXY_GRAPHICS_VERTEX_VERTEXBUFFER_HPP_ #include <vector> #include "galaxy/graphics/vertex/Layout.hpp" namespace galaxy { namespace graphics { /// /// Abstraction for OpenGL vertex buffer objects. /// class VertexBuffer final { public: /// /// Constructor. /// VertexBuffer() noexcept; /// /// Move constructor. /// VertexBuffer(VertexBuffer&&) noexcept; /// /// Move assignment operator. /// VertexBuffer& operator=(VertexBuffer&&) noexcept; /// /// Create vertex buffer object. /// /// \param vertices Vertices to use. /// template<meta::is_vertex VertexType> void create(std::vector<VertexType>& vertices); /// /// Destroys buffer. /// ~VertexBuffer() noexcept; /// /// Bind the current vertex buffer to current GL context. /// void bind() noexcept; /// /// Unbind the current vertex buffer to current GL context. /// void unbind() noexcept; /// /// Get vertex storage. /// /// \return Vertex storage. /// template<meta::is_vertex VertexType> [[nodiscard]] std::vector<VertexType> get(); /// /// Get OpenGL handle. /// /// \return Const unsigned integer. /// [[nodiscard]] const unsigned int id() const noexcept; private: /// /// Copy constructor. /// VertexBuffer(const VertexBuffer&) = delete; /// /// Copy assignment operator. /// VertexBuffer& operator=(const VertexBuffer&) = delete; private: /// /// ID returned by OpenGL when generating buffer. /// unsigned int m_id; /// /// Size of vertex buffer. /// unsigned int m_size; }; template<meta::is_vertex VertexType> inline void VertexBuffer::create(std::vector<VertexType>& vertices) { glBindBuffer(GL_ARRAY_BUFFER, m_id); if (!vertices.empty()) { m_size = static_cast<unsigned int>(vertices.size()); glBufferData(GL_ARRAY_BUFFER, m_size * sizeof(VertexType), vertices.data(), GL_DYNAMIC_DRAW); } else { m_size = static_cast<unsigned int>(vertices.capacity()); glBufferData(GL_ARRAY_BUFFER, m_size * sizeof(VertexType), nullptr, GL_DYNAMIC_DRAW); } glBindBuffer(GL_ARRAY_BUFFER, 0); } template<meta::is_vertex VertexType> inline std::vector<VertexType> VertexBuffer::get() { std::vector<VertexType> vs; vs.reserve(m_size); glGetNamedBufferSubData(m_id, 0, m_size * sizeof(VertexType), &vs[0]); return vs; } } // namespace graphics } // namespace galaxy #endif
20.098485
97
0.641915
DomRe
867fbf8e30dc2ac9b25fae3022edd56315525db1
528
cpp
C++
src/Delta.cpp
mironec/yoshiko
5fe02c9f0be3462959b334e1197ca9e6ea27345d
[ "MIT" ]
4
2017-04-13T02:11:15.000Z
2021-11-29T18:04:16.000Z
src/Delta.cpp
mironec/yoshiko
5fe02c9f0be3462959b334e1197ca9e6ea27345d
[ "MIT" ]
27
2018-01-15T08:37:38.000Z
2018-04-26T13:01:58.000Z
src/Delta.cpp
mironec/yoshiko
5fe02c9f0be3462959b334e1197ca9e6ea27345d
[ "MIT" ]
3
2017-07-24T13:13:28.000Z
2019-04-10T19:09:56.000Z
#include "Delta.h" using namespace std; namespace ysk { double Delta::getValue(const WorkingCopyGraph::Node &node) { if(node == _u) return _deltaU; else if(node == _v) return _deltaV; else { cerr << "Fatal error: class Delta: trying to get value of non-end-node!"<<endl; exit(-1); } } void Delta::setDeltaU(WorkingCopyGraph::Node u, double deltaU) { _u = u; _deltaU = deltaU; } void Delta::setDeltaV(WorkingCopyGraph::Node v, double deltaV) { _v = v; _deltaV = deltaV; } } // namespace ysk
18.206897
83
0.657197
mironec
8680a24b748fb40ccdceb5e5421d7e62170e6a98
12,823
cc
C++
gui/factory_edit.cc
makkrnic/simutrans-extended
8afbbce5b88c79bfea1760cf6c7662d020757b6a
[ "Artistic-1.0" ]
null
null
null
gui/factory_edit.cc
makkrnic/simutrans-extended
8afbbce5b88c79bfea1760cf6c7662d020757b6a
[ "Artistic-1.0" ]
null
null
null
gui/factory_edit.cc
makkrnic/simutrans-extended
8afbbce5b88c79bfea1760cf6c7662d020757b6a
[ "Artistic-1.0" ]
null
null
null
/* * This file is part of the Simutrans-Extended project under the Artistic License. * (see LICENSE.txt) */ #include <stdio.h> #include "../simworld.h" #include "../simtool.h" #include "../bauer/fabrikbauer.h" #include "../descriptor/ground_desc.h" #include "../descriptor/intro_dates.h" #include "../descriptor/factory_desc.h" #include "../dataobj/translator.h" #include "../utils/simrandom.h" #include "../utils/simstring.h" #include "../utils/cbuffer_t.h" #include "factory_edit.h" // new tool definition tool_build_land_chain_t factory_edit_frame_t::land_chain_tool = tool_build_land_chain_t(); tool_city_chain_t factory_edit_frame_t::city_chain_tool = tool_city_chain_t(); tool_build_factory_t factory_edit_frame_t::fab_tool = tool_build_factory_t(); char factory_edit_frame_t::param_str[256]; static bool compare_fabrik_desc(const factory_desc_t* a, const factory_desc_t* b) { int diff = strcmp(a->get_name(), b->get_name()); return diff < 0; } static bool compare_fabrik_desc_trans(const factory_desc_t* a, const factory_desc_t* b) { int diff = strcmp( translator::translate(a->get_name()), translator::translate(b->get_name()) ); return diff < 0; } factory_edit_frame_t::factory_edit_frame_t(player_t* player_) : extend_edit_gui_t(translator::translate("factorybuilder"), player_), factory_list(16), lb_rotation( rot_str, SYSCOL_TEXT_HIGHLIGHT, gui_label_t::right ), lb_rotation_info( translator::translate("Rotation"), SYSCOL_TEXT, gui_label_t::left ), lb_production_info( translator::translate("Produktion"), SYSCOL_TEXT, gui_label_t::left ) { rot_str[0] = 0; prod_str[0] = 0; land_chain_tool.set_default_param(param_str); city_chain_tool.set_default_param(param_str); fab_tool.set_default_param(param_str); land_chain_tool.cursor = city_chain_tool.cursor = fab_tool.cursor = tool_t::general_tool[TOOL_BUILD_FACTORY]->cursor; fac_desc = NULL; bt_city_chain.init( button_t::square_state, "Only city chains", scr_coord(get_tab_panel_width()+2*MARGIN, offset_of_comp-4 ) ); bt_city_chain.add_listener(this); add_component(&bt_city_chain); offset_of_comp += D_BUTTON_HEIGHT; bt_land_chain.init( button_t::square_state, "Only land chains", scr_coord(get_tab_panel_width()+2*MARGIN, offset_of_comp-4 ) ); bt_land_chain.add_listener(this); add_component(&bt_land_chain); offset_of_comp += D_BUTTON_HEIGHT; lb_rotation_info.set_pos( scr_coord( get_tab_panel_width()+2*MARGIN, offset_of_comp-4 ) ); add_component(&lb_rotation_info); bt_left_rotate.init( button_t::repeatarrowleft, NULL, scr_coord(get_tab_panel_width()+2*MARGIN+COLUMN_WIDTH/2-16, offset_of_comp-4 ) ); bt_left_rotate.add_listener(this); add_component(&bt_left_rotate); bt_right_rotate.init( button_t::repeatarrowright, NULL, scr_coord(get_tab_panel_width()+2*MARGIN+COLUMN_WIDTH/2+50-2, offset_of_comp-4 ) ); bt_right_rotate.add_listener(this); add_component(&bt_right_rotate); //lb_rotation.set_pos( scr_coord( get_tab_panel_width()+2*MARGIN+COLUMN_WIDTH/2+44, offset_of_comp-4 ) ); lb_rotation.set_width( bt_right_rotate.get_pos().x - bt_left_rotate.get_pos().x - bt_left_rotate.get_size().w ); lb_rotation.align_to(&bt_left_rotate,ALIGN_EXTERIOR_H | ALIGN_LEFT | ALIGN_CENTER_V); add_component(&lb_rotation); offset_of_comp += D_BUTTON_HEIGHT; lb_production_info.set_pos( scr_coord( get_tab_panel_width()+2*MARGIN, offset_of_comp-4 ) ); add_component(&lb_production_info); inp_production.set_pos(scr_coord(get_tab_panel_width()+2*MARGIN+COLUMN_WIDTH/2-16, offset_of_comp-4-2 )); inp_production.set_size(scr_size( 76, 12 )); inp_production.set_limits(0,9999); inp_production.add_listener( this ); add_component(&inp_production); offset_of_comp += D_BUTTON_HEIGHT; fill_list( is_show_trans_name ); resize(scr_coord(0,0)); } // fill the current factory_list void factory_edit_frame_t::fill_list( bool translate ) { const bool allow_obsolete = bt_obsolete.pressed; const bool use_timeline = bt_timeline.pressed; const bool city_chain = bt_city_chain.pressed; const bool land_chain = bt_land_chain.pressed; const sint32 month_now = bt_timeline.pressed ? welt->get_current_month() : 0; factory_list.clear(); // timeline will be obeyed; however, we may show obsolete ones ... FOR(stringhashtable_tpl<factory_desc_t const*>, const& i, factory_builder_t::get_factory_table()) { factory_desc_t const* const desc = i.value; if(desc->get_distribution_weight()>0) { // DistributionWeight=0 is obsoleted item, only for backward compatibility if(!use_timeline || (!desc->get_building()->is_future(month_now) && (!desc->get_building()->is_retired(month_now) || allow_obsolete)) ) { // timeline allows for this if(city_chain) { if (desc->get_placement() == factory_desc_t::City && desc->is_consumer_only()) { factory_list.insert_ordered(desc, translate ? compare_fabrik_desc_trans : compare_fabrik_desc); } } if(land_chain) { if (desc->get_placement() == factory_desc_t::Land && desc->is_consumer_only()) { factory_list.insert_ordered(desc, translate ? compare_fabrik_desc_trans : compare_fabrik_desc); } } if(!city_chain && !land_chain) { factory_list.insert_ordered(desc, translate ? compare_fabrik_desc_trans : compare_fabrik_desc); } } } } // now build scrolled list scl.clear_elements(); scl.set_selection(-1); FOR(vector_tpl<factory_desc_t const*>, const i, factory_list) { COLOR_VAL const color = i->is_consumer_only() ? COL_BLUE : i->is_producer_only() ? COL_DARK_GREEN : SYSCOL_TEXT; char const* const name = translate ? translator::translate(i->get_name()) : i->get_name(); scl.append_element(new gui_scrolled_list_t::const_text_scrollitem_t(name, color)); if (i == fac_desc) { scl.set_selection(scl.get_count()-1); } } // always update current selection (since the tool may depend on it) change_item_info( scl.get_selection() ); } bool factory_edit_frame_t::action_triggered( gui_action_creator_t *comp,value_t e) { // only one chain can be shown if( comp==&bt_city_chain ) { bt_city_chain.pressed ^= 1; if(bt_city_chain.pressed) { bt_land_chain.pressed = 0; } fill_list( is_show_trans_name ); } else if( comp==&bt_land_chain ) { bt_land_chain.pressed ^= 1; if(bt_land_chain.pressed) { bt_city_chain.pressed = 0; } fill_list( is_show_trans_name ); } else if(fac_desc) { if (comp==&inp_production) { production = inp_production.get_value(); } else if( comp==&bt_left_rotate && rotation!=255) { if(rotation==0) { rotation = 255; } else { rotation --; } } else if( comp==&bt_right_rotate && rotation!=fac_desc->get_building()->get_all_layouts()-1) { rotation ++; } // update info ... change_item_info( scl.get_selection() ); } return extend_edit_gui_t::action_triggered(comp,e); } void factory_edit_frame_t::change_item_info(sint32 entry) { if(entry>=0 && entry<(sint32)factory_list.get_count()) { const factory_desc_t *new_fac_desc = factory_list[entry]; if(new_fac_desc!=fac_desc) { fac_desc = new_fac_desc; production = fac_desc->get_productivity() + sim_async_rand( fac_desc->get_range() ); // Knightly : should also consider the effects of the minimum number of fields const field_group_desc_t *const field_group_desc = fac_desc->get_field_group(); if( field_group_desc && field_group_desc->get_field_class_count()>0 ) { const weighted_vector_tpl<uint16> &field_class_indices = field_group_desc->get_field_class_indices(); sint32 min_fields = field_group_desc->get_min_fields(); while( min_fields-- > 0 ) { const uint16 field_class_index = field_class_indices.at_weight( sim_async_rand( field_class_indices.get_sum_weight() ) ); production += field_group_desc->get_field_class(field_class_index)->get_field_production(); } } production = (uint32)welt->calc_adjusted_monthly_figure(production); inp_production.set_value(production); // show produced goods buf.clear(); if (!fac_desc->is_consumer_only()) { buf.append( translator::translate("Produktion") ); buf.append("\n"); for (uint i = 0; i < fac_desc->get_product_count(); i++) { buf.append(" - "); buf.append( translator::translate(fac_desc->get_product(i)->get_output_type()->get_name()) ); if (fac_desc->get_product(i)->get_output_type()->get_catg() != 0) { buf.append(" ("); buf.append(translator::translate(fac_desc->get_product(i)->get_output_type()->get_catg_name())); buf.append(")"); } buf.append( "\n"); } buf.append("\n"); } // show consumed goods if (!fac_desc->is_producer_only()) { buf.append( translator::translate("Verbrauch") ); buf.append("\n"); for( int i=0; i<fac_desc->get_supplier_count(); i++ ) { buf.append(" - "); buf.append(translator::translate(fac_desc->get_supplier(i)->get_input_type()->get_name())); if (fac_desc->get_supplier(i)->get_input_type()->get_catg() != 0) { buf.append(" ("); buf.append(translator::translate(fac_desc->get_supplier(i)->get_input_type()->get_catg_name())); buf.append(")"); } buf.append("\n"); } buf.append("\n"); } if(fac_desc->is_electricity_producer()) { buf.append( translator::translate( "Electricity producer\n\n" ) ); } // now the house stuff const building_desc_t *desc = fac_desc->get_building(); // climates buf.append( translator::translate("allowed climates:\n") ); uint16 cl = desc->get_allowed_climate_bits(); if(cl==0) { buf.append( translator::translate("none") ); buf.append("\n"); } else { for(uint16 i=0; i<=arctic_climate; i++ ) { if(cl & (1<<i)) { buf.append(" - "); buf.append(translator::translate(ground_desc_t::get_climate_name_from_bit((climate)i))); buf.append("\n"); } } } buf.append("\n"); factory_desc_t const& f = *factory_list[entry]; buf.printf( translator::translate("Passenger Demand %d\n"), f.get_pax_demand() != 65535 ? f.get_pax_demand() : f.get_pax_level()); buf.printf( translator::translate("Mail Demand %d\n"), f.get_mail_demand() != 65535 ? f.get_mail_demand() : f.get_pax_level() >> 2); buf.printf("%s%u", translator::translate("\nBauzeit von"), desc->get_intro_year_month() / 12); if(desc->get_retire_year_month()!=DEFAULT_RETIRE_DATE*12) { buf.printf("%s%u", translator::translate("\nBauzeit bis"), desc->get_retire_year_month() / 12); } if (char const* const maker = desc->get_copyright()) { buf.append("\n"); buf.printf(translator::translate("Constructed by %s"), maker); } buf.append("\n"); info_text.recalc_size(); cont.set_size( info_text.get_size() + scr_size(0, 20) ); // orientation (255=random) if(desc->get_all_layouts()>1) { rotation = 255; // no definition yet } else { rotation = 0; } // now for the tool fac_desc = factory_list[entry]; } // change label numbers if(rotation == 255) { tstrncpy(rot_str, translator::translate("random"), lengthof(rot_str)); } else { sprintf( rot_str, "%i", rotation ); } // now the images (maximum is 2x2 size) // since these may be affected by rotation, we do this every time ... for(int i=0; i<4; i++ ) { img[i].set_image( IMG_EMPTY ); } const building_desc_t *desc = fac_desc->get_building(); uint8 rot = (rotation==255) ? 0 : rotation; if(desc->get_x(rot)==1) { if(desc->get_y(rot)==1) { img[3].set_image( desc->get_tile(rot,0,0)->get_background(0,0,0) ); } else { img[2].set_image( desc->get_tile(rot,0,0)->get_background(0,0,0) ); img[3].set_image( desc->get_tile(rot,0,1)->get_background(0,0,0) ); } } else { if(desc->get_y(rot)==1) { img[1].set_image( desc->get_tile(rot,0,0)->get_background(0,0,0) ); img[3].set_image( desc->get_tile(rot,1,0)->get_background(0,0,0) ); } else { // maximum 2x2 image for(int i=0; i<4; i++ ) { img[i].set_image( desc->get_tile(rot,i/2,i&1)->get_background(0,0,0) ); } } } // the tools will be always updated, even though the data up there might be still current sprintf( param_str, "%i%c%i,%s", bt_climates.pressed, rotation==255 ? '#' : '0'+rotation, production, fac_desc->get_name() ); if(bt_land_chain.pressed) { welt->set_tool( &land_chain_tool, player ); } else if(bt_city_chain.pressed) { welt->set_tool( &city_chain_tool, player ); } else { welt->set_tool( &fab_tool, player ); } } else if(fac_desc!=NULL) { for(int i=0; i<4; i++ ) { img[i].set_image( IMG_EMPTY ); } buf.clear(); prod_str[0] = 0; tstrncpy(rot_str, translator::translate("random"), lengthof(rot_str)); fac_desc = NULL; welt->set_tool( tool_t::general_tool[TOOL_QUERY], player ); } }
34.194667
147
0.697575
makkrnic
8683f710f55766b44e37fff71e3d0d8089765303
283
cpp
C++
Libs/Core/CMake/TestBFD/TestBFD.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
515
2015-01-13T05:42:10.000Z
2022-03-29T03:10:01.000Z
Libs/Core/CMake/TestBFD/TestBFD.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
425
2015-01-06T05:28:38.000Z
2022-03-08T19:42:18.000Z
Libs/Core/CMake/TestBFD/TestBFD.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
341
2015-01-08T06:18:17.000Z
2022-03-29T21:47:49.000Z
#include <bfd.h> // STD includes #include <cstdlib> int main(int /*argc*/, char * /*argv*/[]) { bfd *abfd = 0; asymbol *symbol = 0; asection *p = 0; bfd_init(); abfd = bfd_openr("/path/to/library", 0); if (!abfd) { return false; } return EXIT_SUCCESS; }
14.15
42
0.565371
kraehlit
8694d733b93aa352a8a836b80008497ff13ef2a4
1,363
cpp
C++
src/133.clone_graph/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/133.clone_graph/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/133.clone_graph/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { if (node == NULL) return NULL; unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mapped; queue<UndirectedGraphNode*> q; q.push(node); UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label); mapped[node] = newNode; while (!q.empty()) { UndirectedGraphNode *curNode = q.front(); q.pop(); UndirectedGraphNode *newCurNode = mapped[curNode]; for (int i = 0; i < curNode->neighbors.size(); i++) { UndirectedGraphNode *nextNode = curNode->neighbors[i]; if(mapped.find(nextNode) != mapped.end()) { newCurNode->neighbors.push_back(mapped[nextNode]); } else { q.push(nextNode); UndirectedGraphNode *newNextNode = new UndirectedGraphNode(nextNode->label); mapped[nextNode] = newNextNode; newCurNode->neighbors.push_back(newNextNode); } } } return mapped[node]; } };
36.837838
96
0.569332
cloudzfy
8698075905e16ce9032f346143058775d0abbc5a
82
hpp
C++
include/dg/platform/window_events.hpp
epicodic/diligent-graph
64325a17498fa6b913bffadfc1a43108c81dd7b0
[ "Apache-2.0" ]
3
2020-08-25T07:54:43.000Z
2021-01-14T20:05:06.000Z
include/dg/platform/window_events.hpp
epicodic/diligent-graph
64325a17498fa6b913bffadfc1a43108c81dd7b0
[ "Apache-2.0" ]
null
null
null
include/dg/platform/window_events.hpp
epicodic/diligent-graph
64325a17498fa6b913bffadfc1a43108c81dd7b0
[ "Apache-2.0" ]
null
null
null
#pragma once namespace dg { struct ResizeEvent { int width, height; }; }
6.307692
22
0.634146
epicodic
869930b9054607fde2483fb0972e79cd6c46567e
6,179
hpp
C++
lib/serialize/include/pajlada/serialize/deserialize.hpp
Functioneel/chatterino7
81a52498b6850626223f96fa81c3e847c23ee25d
[ "MIT" ]
1
2022-01-08T17:59:48.000Z
2022-01-08T17:59:48.000Z
include/pajlada/serialize/deserialize.hpp
brucelevis/serialize
7d37cbfd5ac3bfbe046118e1cec3d32ba4696469
[ "MIT" ]
4
2022-03-07T14:40:30.000Z
2022-03-31T10:26:28.000Z
lib/serialize/include/pajlada/serialize/deserialize.hpp
Functioneel/chatterino7
81a52498b6850626223f96fa81c3e847c23ee25d
[ "MIT" ]
2
2020-06-04T09:52:24.000Z
2021-12-25T13:58:30.000Z
#pragma once #include <rapidjson/document.h> #include <pajlada/serialize/common.hpp> #ifdef PAJLADA_BOOST_ANY_SUPPORT #include <boost/any.hpp> #endif #include <cassert> #include <cmath> #include <map> #include <stdexcept> #include <string> #include <typeinfo> #include <vector> namespace pajlada { // Deserialize is called when we load a json file into our library template <typename Type, typename RJValue = rapidjson::Value, typename Enable = void> struct Deserialize { static Type get(const RJValue & /*value*/, bool *error = nullptr) { // static_assert(false, "Unimplemented deserialize type"); PAJLADA_REPORT_ERROR(error) return Type{}; } }; template <typename Type, typename RJValue> struct Deserialize< Type, RJValue, typename std::enable_if<std::is_integral<Type>::value>::type> { static Type get(const RJValue &value, bool *error = nullptr) { if (!value.IsNumber()) { PAJLADA_REPORT_ERROR(error) return Type{}; } return detail::GetNumber<Type>(value); } }; template <typename RJValue> struct Deserialize<bool, RJValue> { static bool get(const RJValue &value, bool *error = nullptr) { if (value.IsBool()) { // No conversion needed return value.GetBool(); } if (value.IsInt()) { // Conversion from Int: // 1 == true // Anything else = false return value.GetInt() == 1; } PAJLADA_REPORT_ERROR(error) return false; } }; template <typename RJValue> struct Deserialize<double, RJValue> { static double get(const RJValue &value, bool *error = nullptr) { if (value.IsNull()) { return std::numeric_limits<double>::quiet_NaN(); } if (!value.IsNumber()) { PAJLADA_REPORT_ERROR(error) return double{}; } return value.GetDouble(); } }; template <typename RJValue> struct Deserialize<float, RJValue> { static float get(const RJValue &value, bool *error = nullptr) { if (value.IsNull()) { return std::numeric_limits<float>::quiet_NaN(); } if (!value.IsNumber()) { PAJLADA_REPORT_ERROR(error) return float{}; } return value.GetFloat(); } }; template <typename RJValue> struct Deserialize<std::string, RJValue> { static std::string get(const RJValue &value, bool *error = nullptr) { if (!value.IsString()) { PAJLADA_REPORT_ERROR(error) return std::string{}; } return value.GetString(); } }; template <typename ValueType, typename RJValue> struct Deserialize<std::map<std::string, ValueType>, RJValue> { static std::map<std::string, ValueType> get(const RJValue &value, bool *error = nullptr) { std::map<std::string, ValueType> ret; if (!value.IsObject()) { PAJLADA_REPORT_ERROR(error) return ret; } for (typename RJValue::ConstMemberIterator it = value.MemberBegin(); it != value.MemberEnd(); ++it) { ret.emplace(it->name.GetString(), Deserialize<ValueType, RJValue>::get(it->value, error)); } return ret; } }; template <typename ValueType, typename RJValue> struct Deserialize<std::vector<ValueType>, RJValue> { static std::vector<ValueType> get(const RJValue &value, bool *error = nullptr) { std::vector<ValueType> ret; if (!value.IsArray()) { PAJLADA_REPORT_ERROR(error) return ret; } for (const RJValue &innerValue : value.GetArray()) { ret.emplace_back( Deserialize<ValueType, RJValue>::get(innerValue, error)); } return ret; } }; template <typename ValueType, size_t Size, typename RJValue> struct Deserialize<std::array<ValueType, Size>, RJValue> { static std::array<ValueType, Size> get(const RJValue &value, bool *error = nullptr) { std::array<ValueType, Size> ret; if (!value.IsArray()) { PAJLADA_REPORT_ERROR(error) return ret; } if (value.GetArray().Size() != Size) { PAJLADA_REPORT_ERROR(error) return ret; } for (size_t i = 0; i < Size; ++i) { ret[i] = Deserialize<ValueType, RJValue>::get(value[i], error); } return ret; } }; template <typename Arg1, typename Arg2, typename RJValue> struct Deserialize<std::pair<Arg1, Arg2>, RJValue> { static std::pair<Arg1, Arg2> get(const RJValue &value, bool *error = nullptr) { if (!value.IsArray()) { PAJLADA_REPORT_ERROR(error) return std::make_pair(Arg1(), Arg2()); } if (value.Size() != 2) { PAJLADA_REPORT_ERROR(error) return std::make_pair(Arg1(), Arg2()); } return std::make_pair(Deserialize<Arg1, RJValue>::get(value[0], error), Deserialize<Arg2, RJValue>::get(value[1], error)); } }; #ifdef PAJLADA_BOOST_ANY_SUPPORT template <typename RJValue> struct Deserialize<boost::any, RJValue> { static boost::any get(const RJValue &value, bool *error = nullptr) { if (value.IsInt()) { return value.GetInt(); } else if (value.IsFloat() || value.IsDouble()) { return value.GetDouble(); } else if (value.IsString()) { return std::string(value.GetString()); } else if (value.IsBool()) { return value.GetBool(); } else if (value.IsObject()) { return Deserialize<std::map<std::string, boost::any>, RJValue>::get( value, error); } else if (value.IsArray()) { return Deserialize<std::vector<boost::any>, RJValue>::get(value, error); } PAJLADA_REPORT_ERROR(error) return boost::any(); } }; #endif } // namespace pajlada
25.533058
80
0.571128
Functioneel
869961fc338987f7240f1d3cd05a792122c1a918
8,067
cpp
C++
src/internal.cpp
chenlijun99/FuzzGen
0f6ad947b3d573407b573cc54833263e03a6af73
[ "Apache-2.0" ]
233
2019-11-01T19:05:17.000Z
2022-03-19T07:00:11.000Z
src/internal.cpp
chenlijun99/FuzzGen
0f6ad947b3d573407b573cc54833263e03a6af73
[ "Apache-2.0" ]
21
2020-03-21T16:26:55.000Z
2022-03-07T11:14:27.000Z
src/internal.cpp
chenlijun99/FuzzGen
0f6ad947b3d573407b573cc54833263e03a6af73
[ "Apache-2.0" ]
54
2020-05-28T00:12:38.000Z
2022-03-19T07:00:13.000Z
// ------------------------------------------------------------------------------------------------ /* * Copyright (C) 2018 The Android Open Source Project * * 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. * * * ___ ___ ___ ___ ___ ___ ___ * /\__\ /\ \ /\__\ /\__\ /\__\ /\__\ /\ \ * /:/ _/_ \:\ \ /::| | /::| | /:/ _/_ /:/ _/_ \:\ \ * /:/ /\__\ \:\ \ /:/:| | /:/:| | /:/ /\ \ /:/ /\__\ \:\ \ * /:/ /:/ / ___ \:\ \ /:/|:| |__ /:/|:| |__ /:/ /::\ \ /:/ /:/ _/_ _____\:\ \ * /:/_/:/ / /\ \ \:\__\ /:/ |:| /\__\ /:/ |:| /\__\ /:/__\/\:\__\ /:/_/:/ /\__\ /::::::::\__\ * \:\/:/ / \:\ \ /:/ / \/__|:|/:/ / \/__|:|/:/ / \:\ \ /:/ / \:\/:/ /:/ / \:\~~\~~\/__/ * \::/__/ \:\ /:/ / |:/:/ / |:/:/ / \:\ /:/ / \::/_/:/ / \:\ \ * \:\ \ \:\/:/ / |::/ / |::/ / \:\/:/ / \:\/:/ / \:\ \ * \:\__\ \::/ / |:/ / |:/ / \::/ / \::/ / \:\__\ * \/__/ \/__/ |/__/ |/__/ \/__/ \/__/ \/__/ * * FuzzGen - Automatic Fuzzer Generation * * * * internal.cpp * * TODO: Write a small description. * * TODO: I want to deprecate this module. * */ // ------------------------------------------------------------------------------------------------ #include "internal.h" // ------------------------------------------------------------------------------------------------ // Globals // char Internal::ID = 1; // ------------------------------------------------------------------------------------------------ // Class constructor for analyzing all API functions. Simply initialize class members. // Internal::Internal(set <string> *libAPI, vector<interwork::APICall*> *calls, Context *ctx) : ModulePass(ID), ctx(ctx), libAPI(libAPI), calls(calls) { string F; if (libAPI->size() < 1) { // is there any to analyze? warning() << "There are no functions to analyze!\n"; throw FuzzGenException("Empty API"); // abort } for (auto ii=libAPI->begin(); ii!=libAPI->end(); F+=*ii++ + "(), ") { } F.pop_back(); // drop last comma F.pop_back(); info(v0) << "Internal analysis started.\n"; info(v1) << "Functions to analyze: " << F << "\n"; mode = ANALYZE_ALL; } // ------------------------------------------------------------------------------------------------ // Class constructor for analyzing a single API function. Simply initialize class members. // Internal::Internal(string libcall, interwork::APICall *call, Context *ctx) : ModulePass(ID), ctx(ctx), libcall(libcall), call(call) { info(v0) << "Internal analysis started.\n"; info(v1) << "Function to analyze: " << libcall << "\n"; mode = ANALYZE_SINGLE; } // ------------------------------------------------------------------------------------------------ // Class destructor. // Internal::~Internal(void) { // TODO: release allocated objects } // ------------------------------------------------------------------------------------------------ // Overload this function to specify the required analyses. // void Internal::getAnalysisUsage(AnalysisUsage &au) const { au.setPreservesAll(); // we might need these in future // // au.addRequired<ScalarEvolutionWrapperPass>(); // au.addRequired<AAResultsWrapperPass>(); // au.addRequired<AliasAnalysis>(); } // ------------------------------------------------------------------------------------------------ // Analysis starts from here. Analyze all arguments for each API function. // bool Internal::runOnModule(Module &M) { module = &M; // store module as a private member /* iterate over each functions */ for(Module::reverse_iterator ii=M.rbegin(); ii!=M.rend(); ++ii) { Function &func = *ii; bool discard = false; // function is not discarded (yet) /* check whether function is in API */ switch (mode) { case ANALYZE_ALL: // analyze all API functions if (!libAPI->count(func.getName())) { continue; // count is zero => function isn't in the set } break; case ANALYZE_SINGLE: // analyze a specific function if (libcall != func.getName()) { continue; } } info(v0) << "================================ Analyzing '" << func.getName() << "' ================================\n"; interwork::APICall *call = new interwork::APICall(); call->name = func.getName(); /* get number of arguments */ call->nargs = func.arg_size(); /* what about variadic functions? External analysis will reveal the variadic arguments */ if (func.isVarArg()) { warning() << "Variadic functions can be problematic but FuzzGen will do its best :)\n"; call->isVariadic = true; // mark function as variadic } Dig *dig = new Dig(module, ctx); /* return values are handled exactly as arguments */ call->retVal = dig->digRetValType(func.getReturnType()); /* iterate through each argument and analyze it */ for (Function::arg_iterator jj=func.arg_begin(); jj!=func.arg_end(); ++jj) { interwork::Argument *arg = dig->digType(*jj, nullptr, true); if (arg == nullptr) { Type *argTy = jj->getType(); /* create the issue and report it */ string type_str; raw_string_ostream raw(type_str); // create an llvm stream raw << "Argument analysis on " << jj->getParent()->getName() << "(... "; argTy->print(raw); // get type as string raw << " " << jj->getName() << " ...) failed. Function is discarded."; ctx->reportIssue(raw.str()); discard = true; // discard function break; } call->args.push_back(arg); // store argument's information that /* print the internal interwork argument/elements (DEBUG) */ info(v1) << "Interwork Argument: " << arg->dump() << "\n"; for (auto ii=arg->subElements.begin(); ii!=arg->subElements.end(); ++ii) { info(v2) << " Element: " << (*ii)->dump() << "\n"; } } if (!discard) { /* push function to the pool (if it's not discarded) */ switch (mode) { case ANALYZE_ALL: calls->push_back(call); // add call to the vector break; case ANALYZE_SINGLE: this->call = call; // we have a unique call return false; // our job is over now } } } /* we didn't modify the module, so return false */ return false; } // ------------------------------------------------------------------------------------------------
34.622318
99
0.418247
chenlijun99
86a159ca4d06f77ee3c07be51eab4c865a4f7e5c
2,890
cpp
C++
src/Geometry.cpp
eestrada/raytracer
f1a80db1c2ec05e5b39a9dce9af6a56604755a0b
[ "MIT" ]
1
2018-04-25T08:43:36.000Z
2018-04-25T08:43:36.000Z
src/Geometry.cpp
eestrada/raytracer
f1a80db1c2ec05e5b39a9dce9af6a56604755a0b
[ "MIT" ]
null
null
null
src/Geometry.cpp
eestrada/raytracer
f1a80db1c2ec05e5b39a9dce9af6a56604755a0b
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <cmath> #include "cg/Geometry.hpp" #include "utils/exceptions.hpp" namespace cg { rt::RayHit_ptr Sphere::intersect(const rt::Ray &ray, const Mat4 &xform) const { Vec3 new_center = xform * Vec4(this->center, 1.0); Vec3 L = new_center - ray.pos; double tca = L.dot(ray.dir.normalized()); if (tca < 0) return rt::RayHit_ptr(); // We already know if the intersection is behind us. double d2 = L.length2() - tca * tca; double radius2 = this->radius * this->radius; if(d2 > radius2) return rt::RayHit_ptr(); // The ray angle is greater than the radius. // If we made it this far, we have successfully intersected. double thc = std::sqrt(radius2 - d2); rt::RayHit_ptr rval(new rt::RayHit()); rval->distance = tca - thc; rval->data.pos = ray.pos + ray.dir.normalized() * rval->distance; rval->data.dir = (rval->data.pos - new_center).normalized(); return rval; } std::string Sphere::to_string(void) const { std::ostringstream out; out << "Sphere: Center " << this->center << " radius " << this->radius; return out.str(); } void Triangle::set_points(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2) { Vec3 A = v1 - v0; Vec3 B = v2 - v0; Vec3 C = A.cross(B); // CCW winding of points this->nml = C.normalized(); this->pt0 = v0; this->pt1 = v1; this->pt2 = v2; } rt::RayHit_ptr Triangle::intersect(const rt::Ray &ray, const Mat4 &xform) const { rt::RayHit_ptr rval; Vec3 tmp_pt0 = xform * Vec4(this->pt0, 1.0); Vec3 tmp_pt1 = xform * Vec4(this->pt1, 1.0); Vec3 tmp_pt2 = xform * Vec4(this->pt2, 1.0); Vec3 tmp_nml = xform * Vec4(this->nml, 0.0); double denom = ray.dir.dot(tmp_nml); if (denom == 0.0) return rval; // We are perfectly perpendicular to the triangle. Vec3 ptro = tmp_pt0 - ray.pos; double d = ptro.dot(tmp_nml) / denom; if(d < 0) return rval; // Is the triangle in front of the camera? Vec3 P = ray.pos + (ray.dir.normalized() * d); Vec3 edge0 = tmp_pt1 - tmp_pt0; Vec3 edge1 = tmp_pt2 - tmp_pt1; Vec3 edge2 = tmp_pt0 - tmp_pt2; Vec3 C0 = P - tmp_pt0; Vec3 C1 = P - tmp_pt1; Vec3 C2 = P - tmp_pt2; if( tmp_nml.dot(edge0.cross(C0)) > 0 && tmp_nml.dot(edge1.cross(C1)) > 0 && tmp_nml.dot(edge2.cross(C2)) > 0) // Is intersection within the triangle face? { rval.reset(new rt::RayHit()); rval->distance = d; if(tmp_nml.dot(ray.dir) > 0) tmp_nml = -tmp_nml; // Make normals forward facing. rval->data.dir = tmp_nml; rval->data.pos = P; } return rval; } std::string Triangle::to_string(void) const { return std::string("Printing a Triangle!"); } } //end namespace "cg" std::ostream & operator<<(std::ostream &out, const cg::Geometry &g) { return out << g.to_string() << "\n"; }
28.333333
94
0.616609
eestrada
86a16c0a543193840e53468d39746d700a5d187e
3,072
cpp
C++
Fuji/Source/Drivers/PS2/MFSystem_PS2.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
35
2015-01-19T22:07:48.000Z
2022-02-21T22:17:53.000Z
Fuji/Source/Drivers/PS2/MFSystem_PS2.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
1
2022-02-23T09:34:15.000Z
2022-02-23T09:34:15.000Z
Fuji/Source/Drivers/PS2/MFSystem_PS2.cpp
TurkeyMan/fuji
afd6a26c710ce23965b088ad158fe916d6a1a091
[ "BSD-2-Clause" ]
4
2015-05-11T03:31:35.000Z
2018-09-27T04:55:57.000Z
#include "Fuji_Internal.h" #if MF_SYSTEM == MF_DRIVER_PS2 #include "MFSystem_Internal.h" #include <kernel.h> // Timer Registers #define T1_COUNT ((volatile unsigned long*)0x10000800) #define T1_MODE ((volatile unsigned long*)0x10000810) #define T1_COMP ((volatile unsigned long*)0x10000820) #define T1_HOLD ((volatile unsigned long*)0x10000830) #define Tn_MODE(CLKS,GATE,GATS,GATM,ZRET,CUE,CMPE,OVFE,EQUF,OVFF) \ (u32)((u32)(CLKS) | ((u32)(GATE) << 2) | \ ((u32)(GATS) << 3) | ((u32)(GATM) << 4) | \ ((u32)(ZRET) << 6) | ((u32)(CUE) << 7) | \ ((u32)(CMPE) << 8) | ((u32)(OVFE) << 9) | \ ((u32)(EQUF) << 10) | ((u32)(OVFF) << 11)) #define kBUSCLK (147456000) #define kBUSCLKBY16 (kBUSCLK / 16) #define kBUSCLKBY256 (kBUSCLK / 256) enum { kINTC_GS, kINTC_SBUS, kINTC_VBLANK_START, kINTC_VBLANK_END, kINTC_VIF0, kINTC_VIF1, kINTC_VU0, kINTC_VU1, kINTC_IPU, kINTC_TIMER0, kINTC_TIMER1 }; // Timer statics static int s_tnInterruptID = -1; static u64 s_tnInterruptCount = 0; // Timer interrupt handler int tnTimeInterrupt(int ca) { s_tnInterruptCount++; // A write to the overflow flag will clear the overflow flag *T1_MODE |= (1 << 11); return -1; } void MFSystem_InitModulePlatformSpecific() { gpEngineInstance->currentPlatform = FP_PS2; // Init the timer and register the interrupt handler *T1_MODE = 0x0000; s_tnInterruptID = AddIntcHandler(kINTC_TIMER1, tnTimeInterrupt, 0); EnableIntc(kINTC_TIMER1); // Initialize the timer registers // CLKS: 0x02 - 1/256 of the BUSCLK (0x01 is 1/16th) // CUE: 0x01 - Start/Restart the counting // OVFE: 0x01 - An interrupt is generated when an overflow occurs // -------------------------------------------------------------- *T1_COUNT = 0; *T1_MODE = Tn_MODE(0x02, 0, 0, 0, 0, 0x01, 0, 0x01, 0, 0); s_tnInterruptCount = 0; } void MFSystem_DeinitModulePlatformSpecific() { // Stop the timer *T1_MODE = 0x0000; // Disable the interrupt if (s_tnInterruptID >= 0) { DisableIntc(kINTC_TIMER1); RemoveIntcHandler(kINTC_TIMER1, s_tnInterruptID); s_tnInterruptID = -1; } s_tnInterruptCount = 0; } void MFSystem_HandleEventsPlatformSpecific() { } void MFSystem_UpdatePlatformSpecific() { } void MFSystem_DrawPlatformSpecific() { } MF_API uint64 MFSystem_ReadRTC() { uint64 t; // Tn_COUNT is 16 bit precision. Therefore, each // <s_tnInterruptCount> is 65536 ticks // --------------------------------------------- t = *T1_COUNT + (s_tnInterruptCount << 16); t = t * 1000000 / kBUSCLKBY256; return t; } MF_API uint64 MFSystem_GetRTCFrequency() { // I am using 1/256 of the BUSCLK below in the Tn_MODE register // which means that the timer will count at a rate of: // 147,456,000 / 256 = 576,000 Hz // This implies that the accuracy of this timer is: // 1 / 576,000 = 0.0000017361 seconds (~1.74 usec!) return 1000000; } MF_API const char * MFSystem_GetSystemName() { return "Playstation2"; } #endif
22.755556
69
0.642253
TurkeyMan
86a2bb9524a136785bfefcef74e9bbd4aa6092eb
1,191
cpp
C++
Object Oriented Algo Design in C++/practice/quicksort.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
Object Oriented Algo Design in C++/practice/quicksort.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
Object Oriented Algo Design in C++/practice/quicksort.cpp
aishwaryamallampati/BTech-IIITDM
4cfc25a4e6e066b848361cb92770cad3260c7d48
[ "MIT" ]
null
null
null
/*sorting the given elements using quick sort*/ #include<iostream> using namespace std; class array { public: array(); int a[1000]; int size; }; array::array() { int index1; cout<<"\nenter the size of the array:"; cin>>size; cout<<"\nenter the elements of the array: "; for(index1=1;index1<=size;index1++) cin>>a[index1]; } class quicksorter { public: quicksorter(); void quicksort(int a[1000],int p,int r); int partition(int a[1000],int p,int r); }; quicksorter::quicksorter() { array array1; cout<<"\nthe partitions are: "<<endl; quicksort(array1.a,1,array1.size); cout<<"the sorted array:"<<endl; for(int i=1;i<=array1.size;i++) cout<<array1.a[i]<<" "; cout<<endl; } void quicksorter::quicksort(int a[1000],int p,int r) { int q; if(p<r) { q=partition(a,p,r); quicksort(a,p,q-1); quicksort(a,q+1,r); } } int quicksorter::partition(int a[1000],int p,int r) { int x,i,j,k,temp; x=a[r]; i=p-1; for(j=p;j<r;j++) { if(a[j]<=x) { i=i+1; temp=a[i]; a[i]=a[j]; a[j]=temp; } } temp=a[i+1]; a[i+1]=a[r]; a[r]=temp; for(k=p;k<=r;k++) cout<<a[k]<<" "; cout<<endl; return i+1; } main() { quicksorter quicksorter1; return 0; }
14.178571
52
0.603694
aishwaryamallampati
86a8d478527de8169fd08b97d30112281eeb3c16
4,146
hpp
C++
SpriteExtractorLib/Types.hpp
jowie94/SpriteExtractor
96934f241e33229638beb8914ac68e866696433b
[ "MIT" ]
1
2019-01-15T15:14:47.000Z
2019-01-15T15:14:47.000Z
SpriteExtractorLib/Types.hpp
jowie94/SpriteExtractor
96934f241e33229638beb8914ac68e866696433b
[ "MIT" ]
null
null
null
SpriteExtractorLib/Types.hpp
jowie94/SpriteExtractor
96934f241e33229638beb8914ac68e866696433b
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <utility> #include <cassert> #include <vector> template<class T> struct Vec2 { Vec2() {} Vec2(T x_, T y_) : X(x_) , Y(y_) { } T X = 0; T Y = 0; }; struct Color final { using channel_t = unsigned char; Color() {} Color(channel_t r, channel_t g, channel_t b, channel_t a = 255) : R(r) , G(g) , B(b) , A(a) {} void ToFloat(float colors[4]) const { static float sc = 1.0f / 255.0f; colors[0] = R * sc; colors[1] = G * sc; colors[2] = B * sc; colors[3] = A * sc; } Color& operator=(const float colors[4]) { R = static_cast<channel_t>(colors[0] * 255.0f); G = static_cast<channel_t>(colors[1] * 255.0f); B = static_cast<channel_t>(colors[2] * 255.0f); A = static_cast<channel_t>(colors[3] * 255.0f); return *this; } bool operator==(const Color& other) const { return R == other.R && G == other.G && B == other.B && A == other.A; } bool operator!=(const Color& other) const { return !operator==(other); } channel_t R = 0; channel_t G = 0; channel_t B = 0; channel_t A = 255; }; using ImageSize = Vec2<unsigned int>; struct ITextureResource { unsigned int ResourceId = 0; ImageSize Size; }; struct BBox { using bbox_t = int; bool ContainsPoint(bbox_t x, bbox_t y) const { bbox_t mX = X + Width; bbox_t mY = Y + Height; return X <= x && x <= mX && Y <= y && y <= mY; } template <typename Scalar> BBox operator*(Scalar scalar) const { static_assert(std::is_arithmetic<Scalar>::value, "Scalar must be arithmetic"); BBox newBox; newBox.X = static_cast<bbox_t>(X * scalar); newBox.Y = static_cast<bbox_t>(Y * scalar); newBox.Width = static_cast<bbox_t>(Width * scalar); newBox.Height = static_cast<bbox_t>(Height * scalar); return newBox; } bbox_t X = 0; bbox_t Y = 0; bbox_t Width = 0; bbox_t Height = 0; }; using ImageSize = Vec2<unsigned int>; class IImage { public: virtual ~IImage() = default; virtual ImageSize Size() const = 0; virtual std::unique_ptr<ITextureResource> GetTextureResource() const = 0; virtual bool Save(const char* filename) const = 0; virtual Color GetPixel(size_t x, size_t y) const = 0; }; template<typename T> class Matrix { public: using MatrixSize = std::pair<size_t, size_t>; Matrix(const MatrixSize& size_) : _size(size_) , _data(new T[_size.first * _size.second]) { assert(_size.first != 0 || _size.second != 0 && "Invalid size"); } Matrix(const MatrixSize& size_, const T& initialValue) : _size(size_) , _data(new T[_size.first * _size.second]) { assert(_size.first != 0 || _size.second != 0 && "Invalid size"); for (size_t i = 0; i < _size.first * _size.second; ++i) { _data[i] = initialValue; } } Matrix(const Matrix& other) : _size(other._size) , _data(new T[_size.first * _size.second]) { memcpy(_data, other._data, _size.first * _size.second); } Matrix(Matrix&& other) noexcept : _size(other._size) , _data(other._data) { other._size = std::make_pair(0, 0); other._data = nullptr; } ~Matrix() { delete[] _data; } const T& At(size_t i, size_t j) const { assert(0 <= i && i < _size.first && "Invalid i coordinate (column)"); assert(0 <= j && j < _size.second && "Invalid j coordinate (row)"); return _data[i * _size.second + j]; } T& At(size_t i, size_t j) { assert(0 <= i && i < _size.first && "Invalid i coordinate (column)"); assert(0 <= j && j < _size.second && "Invalid j coordinate (row)"); return _data[i * _size.second + j]; } const MatrixSize& Size() const { return _size; } private: MatrixSize _size; T* _data; };
21.59375
86
0.548722
jowie94
86aa25e8edbf2c875064fc71c27b9ffc3cdf6447
3,742
hpp
C++
include/vdds/sub.hpp
maxk-org/vdds
015473498661cb8f06868cce2dc4519a6452b861
[ "BSD-3-Clause" ]
null
null
null
include/vdds/sub.hpp
maxk-org/vdds
015473498661cb8f06868cce2dc4519a6452b861
[ "BSD-3-Clause" ]
null
null
null
include/vdds/sub.hpp
maxk-org/vdds
015473498661cb8f06868cce2dc4519a6452b861
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // SPDX-License-Identifier: BSD-3-Clause #ifndef VDDS_SUB_HPP #define VDDS_SUB_HPP #include <stdint.h> #include <map> #include <string> #include <vector> #include <mutex> #include <atomic> #include <stdexcept> #include <hogl/area.hpp> #include <hogl/post.hpp> #include "domain.hpp" #include "topic.hpp" namespace vdds { /// Typesafe subscriber. /// This is the main interface for subscribing to topics. /// It takes care of all ops: create topic, subscribe and pop data. /// @param T data type template<typename T> class sub { private: vdds::sub_queue* _queue; ///< subscriber queue pointer vdds::topic* _topic; ///< topic pointer public: /// Create subscriber. /// Creates topic and subscribes to it. /// @param[in] vd reference to the domain /// @param[in] name subscriber name /// @param[in] topic_name topic name name /// @param[in] qsize size of the queue /// @param[in] ntfr notifier pointer (null, cv, poll) explicit sub(domain& vd, const std::string& name, const std::string& topic_name, size_t qsize = 16, notifier* ntfr = nullptr) { static_assert(sizeof(T) == sizeof(data), "data type size missmatch"); _topic = vd.create_topic(topic_name, T::data_type); if (!_topic) throw std::logic_error("failed to create topic"); _queue = _topic->subscribe(name, qsize, ntfr); } /// Delete subscriber. /// Unsubscribes from the topic. The queue is flushed and removed. ~sub() { _topic->unsubscribe(_queue); } /// No copy sub( const sub& ) = delete; sub& operator=( const sub& ) = delete; /// Get name and data type const std::string& name() const { return _queue->name(); } const std::string& data_type() const { return _queue->data_type(); } /// Get queue and topic pointers vdds::sub_queue* queue() { return _queue; } vdds::topic* topic() { return _topic; } /// Pop data from fifo /// @param[out] d ref to data /// @return false if queue is empty, true otherwise bool pop(T& d) { return _topic->pop(_queue, static_cast<data&>(d)); } /// Flush all queued data void flush() { T d; while (pop(d)); } }; } // namespace vdds #endif // VDDS_SUB_HPP
32.258621
81
0.711919
maxk-org
86b02c3b1a0c490e1b95f3829daf0b2048449625
1,934
cpp
C++
Common/util/l4util.cpp
sunzhuoshi/SteamVRDemoHelper
536280f1e5df5e4bdb85fca3460353e0f19cf43d
[ "MIT" ]
null
null
null
Common/util/l4util.cpp
sunzhuoshi/SteamVRDemoHelper
536280f1e5df5e4bdb85fca3460353e0f19cf43d
[ "MIT" ]
null
null
null
Common/util/l4util.cpp
sunzhuoshi/SteamVRDemoHelper
536280f1e5df5e4bdb85fca3460353e0f19cf43d
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "l4util.h" #include <sstream> #include <minwindef.h> #include <Windows.h> #include <Psapi.h> namespace l4util { std::string getCurrentExePath() { char buf[MAX_PATH] = "", *tmp; if (GetModuleFileNameA(NULL, buf, MAX_PATH)) { tmp = strrchr(buf, '\\'); if (tmp) { *tmp = '\0'; } } return std::string(buf); } std::string getFileFullPath(const std::string &dllFileName) { std::ostringstream result; result << getCurrentExePath().c_str() << "\\" << dllFileName.c_str(); return result.str(); } std::string getCurrentProcessName() { char buf[MAX_PATH] = "", *tmp = NULL; std::string result; if (GetModuleFileNameA(NULL, buf, MAX_PATH)) { tmp = strrchr(buf, '\\'); if (tmp) { tmp++; } } if (tmp) { result = tmp; } return result; } std::string getProcessNameWithWindow(HWND wnd) { DWORD processId; GetWindowThreadProcessId(wnd, &processId); return getProcessNameWithProcessId(processId); } std::string getProcessNameWithProcessId(DWORD processId) { char buf[MAX_PATH] = "", *p = nullptr; HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processId); if (processHandle) { GetProcessImageFileName(processHandle, buf, sizeof(buf)); p = strrchr(buf, '\\'); if (p) { p++; } CloseHandle(processHandle); } else { int i = 0; i++; } if (p) { return p; } else { return ""; } } std::string loadString(UINT id) { std::string result; char buf[MAX_PATH]; // just be lazy to use MAX_PATH HMODULE instance = GetModuleHandle(NULL); if (instance) { if (0 < LoadStringA(instance, id, buf, MAX_PATH)) { result = std::string(buf); } } return result; } }
20.145833
88
0.56515
sunzhuoshi
86b23086dbf47aa4c690d23d4a6be5ca5e40d20a
4,064
cpp
C++
GTEngine/Source/Graphics/DX11/GteHLSLResource.cpp
pmjoniak/GeometricTools
ae6e933f9ab3a5474d830700ea8d9445cc78ef4b
[ "BSL-1.0" ]
4
2019-03-03T18:13:30.000Z
2020-08-25T18:15:30.000Z
GTEngine/Source/Graphics/DX11/GteHLSLResource.cpp
pmjoniak/GeometricTools
ae6e933f9ab3a5474d830700ea8d9445cc78ef4b
[ "BSL-1.0" ]
null
null
null
GTEngine/Source/Graphics/DX11/GteHLSLResource.cpp
pmjoniak/GeometricTools
ae6e933f9ab3a5474d830700ea8d9445cc78ef4b
[ "BSL-1.0" ]
6
2016-07-15T11:04:52.000Z
2021-12-07T03:11:42.000Z
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2018 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // File Version: 3.0.2 (2017/09/05) #include <GTEnginePCH.h> #include <Graphics/DX11/GteHLSLResource.h> using namespace gte; HLSLResource::~HLSLResource() { } HLSLResource::HLSLResource(D3D_SHADER_INPUT_BIND_DESC const& desc, unsigned int numBytes) : mNumBytes(numBytes) { mDesc.name = std::string(desc.Name); mDesc.bindPoint = desc.BindPoint; mDesc.bindCount = desc.BindCount; mDesc.type = desc.Type; mDesc.flags = desc.uFlags; mDesc.returnType = desc.ReturnType; mDesc.dimension = desc.Dimension; mDesc.numSamples = desc.NumSamples; } HLSLResource::HLSLResource(D3D_SHADER_INPUT_BIND_DESC const& desc, unsigned int index, unsigned int numBytes) : mNumBytes(numBytes) { mDesc.name = std::string(desc.Name) + "[" + std::to_string(index) + "]"; mDesc.bindPoint = desc.BindPoint + index; mDesc.bindCount = 1; mDesc.type = desc.Type; mDesc.flags = desc.uFlags; mDesc.returnType = desc.ReturnType; mDesc.dimension = desc.Dimension; mDesc.numSamples = desc.NumSamples; } std::string const& HLSLResource::GetName() const { return mDesc.name; } D3D_SHADER_INPUT_TYPE HLSLResource::GetType() const { return mDesc.type; } unsigned int HLSLResource::GetBindPoint() const { return mDesc.bindPoint; } unsigned int HLSLResource::GetBindCount() const { return mDesc.bindCount; } unsigned int HLSLResource::GetFlags() const { return mDesc.flags; } D3D_RESOURCE_RETURN_TYPE HLSLResource::GetReturnType() const { return mDesc.returnType; } D3D_SRV_DIMENSION HLSLResource::GetDimension() const { return mDesc.dimension; } unsigned int HLSLResource::GetNumSamples() const { return mDesc.numSamples; } unsigned int HLSLResource::GetNumBytes() const { return mNumBytes; } void HLSLResource::Print(std::ofstream& output) const { output << "name = " << mDesc.name << std::endl; output << "shader input type = " << msSIType[mDesc.type] << std::endl; output << "bind point = " << mDesc.bindPoint << std::endl; output << "bind count = " << mDesc.bindCount << std::endl; output << "flags = " << mDesc.flags << std::endl; output << "return type = " << msReturnType[mDesc.returnType] << std::endl; output << "dimension = " << msSRVDimension[mDesc.dimension] << std::endl; if (mDesc.numSamples == 0xFFFFFFFFu) { output << "samples = -1" << std::endl; } else { output << "samples = " << mDesc.numSamples << std::endl; } output << "number of bytes = " << mNumBytes << std::endl; } std::string const HLSLResource::msSIType[] = { "D3D_SIT_CBUFFER", "D3D_SIT_TBUFFER", "D3D_SIT_TEXTURE", "D3D_SIT_SAMPLER", "D3D_SIT_UAV_RWTYPED", "D3D_SIT_STRUCTURED", "D3D_SIT_UAV_RWSTRUCTURED", "D3D_SIT_BYTEADDRESS", "D3D_SIT_UAV_RWBYTEADDRESS", "D3D_SIT_UAV_APPEND_STRUCTURED", "D3D_SIT_UAV_CONSUME_STRUCTURED", "D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER" }; std::string const HLSLResource::msReturnType[] = { "none", // There is no D3D_RESOURCE_RETURN_TYPE for value 0. "D3D_RETURN_TYPE_UNORM", "D3D_RETURN_TYPE_SNORM", "D3D_RETURN_TYPE_SINT", "D3D_RETURN_TYPE_UINT", "D3D_RETURN_TYPE_FLOAT", "D3D_RETURN_TYPE_MIXED", "D3D_RETURN_TYPE_DOUBLE", "D3D_RETURN_TYPE_CONTINUED" }; std::string const HLSLResource::msSRVDimension[] = { "D3D_SRV_DIMENSION_UNKNOWN", "D3D_SRV_DIMENSION_BUFFER", "D3D_SRV_DIMENSION_TEXTURE1D", "D3D_SRV_DIMENSION_TEXTURE1DARRAY", "D3D_SRV_DIMENSION_TEXTURE2D", "D3D_SRV_DIMENSION_TEXTURE2DARRAY", "D3D_SRV_DIMENSION_TEXTURE2DMS", "D3D_SRV_DIMENSION_TEXTURE2DMSARRAY", "D3D_SRV_DIMENSION_TEXTURE3D", "D3D_SRV_DIMENSION_TEXTURECUBE", "D3D_SRV_DIMENSION_TEXTURECUBEARRAY", "D3D_SRV_DIMENSION_BUFFEREX" };
25.88535
78
0.697835
pmjoniak
86b6c31525dac0f661a90f9c8635444d2b501cbf
22,309
cpp
C++
SpatialFilter/GaussianFilterAM.cpp
norishigefukushima/OpenCP
63090131ec975e834f85b04e84ec29b2893845b2
[ "BSD-3-Clause" ]
137
2015-03-27T07:11:19.000Z
2022-03-30T05:58:22.000Z
SpatialFilter/GaussianFilterAM.cpp
Pandinosaurus/OpenCP
a5234ed531c610d7944fa14d42f7320442ea34a1
[ "BSD-3-Clause" ]
2
2016-05-18T06:33:16.000Z
2016-07-11T17:39:17.000Z
SpatialFilter/GaussianFilterAM.cpp
Pandinosaurus/OpenCP
a5234ed531c610d7944fa14d42f7320442ea34a1
[ "BSD-3-Clause" ]
43
2015-02-20T15:34:25.000Z
2022-01-27T14:59:37.000Z
#include "stdafx.h" using namespace std; using namespace cv; namespace cp { #pragma region GaussianFilterAM_Naive template<typename Type> GaussianFilterAM_Naive<Type>::GaussianFilterAM_Naive(cv::Size imgSize, Type sigma, int order) : SpatialFilterBase(imgSize, cp::typeToCVDepth<Type>()), order(order), sigma(sigma), tol(Type(1.0e-6)) { const double q = sigma * (1.0 + (0.3165 * order + 0.5695) / ((order + 0.7818) * (order + 0.7818))); const double lambda = (q * q) / (2.0 * order); const double dnu = (1.0 + 2.0 * lambda - sqrt(1.0 + 4.0 * lambda)) / (2.0 * lambda); nu = (Type)dnu; r_init = (int)ceil(log((1.0 - nu) * tol) / log(nu)); scale = (Type)(pow(dnu / lambda, order)); h = new Type[r_init]; h[0] = (Type)1.0; for (int i = 1; i < r_init; ++i) { h[i] = nu * h[i - 1]; } } template<typename Type> GaussianFilterAM_Naive<Type>::~GaussianFilterAM_Naive() { delete[] h; } template<typename Type> void GaussianFilterAM_Naive<Type>::horizontalbody(cv::Mat& img) { const int width = imgSize.width; const int height = imgSize.height; Type* imgPtr; Type accum; //forward direction imgPtr = img.ptr<Type>(); for (int y = 0; y < height; ++y, imgPtr += width) { //boundary processing accum = imgPtr[0]; for (int m = 1; m < r_init; ++m) { accum += h[m] * imgPtr[ref_lborder(-m, borderType)]; } imgPtr[0] = accum; //IIR filtering for (int x = 1; x < width; ++x) { imgPtr[x] += nu * imgPtr[x - 1]; } } //reverse direction imgPtr = img.ptr<Type>(); for (int y = 0; y < height; ++y, imgPtr += width) { //boundary processing imgPtr[width - 1] /= ((Type)1.0 - nu); //IIR filtering for (int x = width - 2; 0 <= x; --x) { imgPtr[x] += nu * imgPtr[x + 1]; } } }; template<typename Type> void GaussianFilterAM_Naive<Type>::verticalbody(Mat& img) { const int width = imgSize.width; const int height = imgSize.height; Type* imgPtr; Type* prePtr; Type accum; //forward direction imgPtr = img.ptr<Type>(); for (int x = 0; x < width; ++x) { //boundary processing accum = imgPtr[x]; for (int m = 1; m < r_init; ++m) { accum += h[m] * *(imgPtr + ref_tborder(-m, width, borderType) + x); } imgPtr[x] = accum; } //IIR filtering prePtr = imgPtr; imgPtr += width; for (int y = 1; y < height; ++y, prePtr = imgPtr, imgPtr += width) { for (int x = 0; x < width; ++x) { imgPtr[x] += nu * prePtr[x]; } } //reverse direction //boundary processing imgPtr = img.ptr<Type>(height - 1); for (int x = 0; x < width; ++x) { imgPtr[x] /= ((Type)1.0 - nu); } //IIR filtering prePtr = imgPtr; imgPtr -= width; for (int y = height - 2; 0 <= y; --y, prePtr = imgPtr, imgPtr -= width) { for (int x = 0; x < width; ++x) { imgPtr[x] += nu * prePtr[x]; } } }; template<class Type> void GaussianFilterAM_Naive<Type>::body(const cv::Mat& src, cv::Mat& dst, const int border) { if (src.depth() == depth) multiply(src, scale, dst); else src.convertTo(dst, depth, scale); for (int k = 0; k < order; ++k) { horizontalbody(dst); } dst = scale * dst; for (int k = 0; k < order; ++k) { verticalbody(dst); } } template class GaussianFilterAM_Naive<float>; template class GaussianFilterAM_Naive<double>; #pragma endregion #pragma region GaussianFilterAM_AVX_32F void GaussianFilterAM_AVX_32F::allocBuffer() { const double q = sigma * (1.0 + (0.3165 * gf_order + 0.5695) / ((gf_order + 0.7818) * (gf_order + 0.7818))); const double lambda = (q * q) / (2.0 * gf_order); const double dnu = ((1.0 + 2.0 * lambda - sqrt(1.0 + 4.0 * lambda)) / (2.0 * lambda)); this->nu = (float)dnu; this->r_init = (int)ceil(log((1.0 - dnu) * tol) / log(dnu)); this->scale = (float)(pow(dnu / lambda, gf_order)); this->norm = float(1.0 - (double)nu); delete[] h; this->h = new float[r_init]; h[0] = 1.f; for (int i = 1; i < r_init; ++i) { h[i] = nu * h[i - 1]; } } GaussianFilterAM_AVX_32F::GaussianFilterAM_AVX_32F(cv::Size imgSize, float sigma, int order) : SpatialFilterBase(imgSize, CV_32F) { this->gf_order = order; this->sigma = sigma; allocBuffer(); } GaussianFilterAM_AVX_32F::GaussianFilterAM_AVX_32F(const int dest_depth) { this->dest_depth = dest_depth; this->depth = CV_32F; } GaussianFilterAM_AVX_32F::~GaussianFilterAM_AVX_32F() { delete[] h; } //gather_vload->store transpose unroll 8 void GaussianFilterAM_AVX_32F::horizontalFilterVLoadGatherTransposeStore(cv::Mat& img) { const int width = imgSize.width; const __m256i mm_offset = _mm256_set_epi32(7 * width, 6 * width, 5 * width, 4 * width, 3 * width, 2 * width, width, 0); __m256 patch[8]; __m256 patch_t[8]; const int height = imgSize.height; float* img_ptr; float* dst; __m256 input; int refx; //forward direction for (int y = 0; y < height; y += 8) { //boundary processing img_ptr = img.ptr<float>(y); dst = img_ptr; patch[0] = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float)); for (int m = 1; m < r_init; ++m) { refx = ref_lborder(-m, borderType); input = _mm256_i32gather_ps(img_ptr + refx, mm_offset, sizeof(float)); //patch[0] = _mm256_add_ps(patch[0], _mm256_mul_ps(_mm256_set1_ps(h[m]), input)); patch[0] = _mm256_fmadd_ps(_mm256_set1_ps(h[m]), input, patch[0]); } ++img_ptr; for (int i = 1; i < 8; ++i) { input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float)); //patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i - 1])); patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i - 1], input); ++img_ptr; } _mm256_transpose8_ps(patch, patch_t); _mm256_storepatch_ps(dst, patch_t, width); dst += 8; //IIR filtering for (int x = 8; x < width; x += 8) { input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float)); //patch[0] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[7])); patch[0] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[7], input); ++img_ptr; for (int i = 1; i < 8; ++i) { input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float)); //patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i - 1])); patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i - 1], input); ++img_ptr; } _mm256_transpose8_ps(patch, patch_t); _mm256_storepatch_ps(dst, patch_t, width); dst += 8; } } //reverse direction for (int y = 0; y < height; y += 8) { //boundary processing img_ptr = img.ptr<float>(y) + width - 1; dst = img_ptr - 7; input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float)); patch[7] = _mm256_div_ps(input, _mm256_set1_ps(norm)); --img_ptr; for (int i = 6; i >= 0; --i) { input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float)); //patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i + 1])); patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i + 1], input); --img_ptr; } _mm256_transpose8_ps(patch, patch_t); _mm256_storepatch_ps(dst, patch_t, width); dst -= 8; //IIR filtering for (int x = width - 16; 0 <= x; x -= 8) { input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float)); //patch[7] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[0])); patch[7] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[0], input); --img_ptr; for (int i = 6; i >= 0; --i) { input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float)); //patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i + 1])); patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i + 1], input); --img_ptr; } _mm256_transpose8_ps(patch, patch_t); _mm256_storepatch_ps(dst, patch_t, width); dst -= 8; } } } //set_vload->store transpose unroll 8 void GaussianFilterAM_AVX_32F::horizontalFilterVLoadSetTransposeStore(cv::Mat& img) { const int width = imgSize.width; const int height = imgSize.height; float* img_ptr; float* dst; __m256 input; __m256 patch[8]; __m256 patch_t[8]; int refx; //forward direction for (int y = 0; y < height; y += 8) { //boundary processing img_ptr = img.ptr<float>(y); dst = img_ptr; patch[0] = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]); for (int m = 1; m < r_init; ++m) { refx = ref_lborder(-m, borderType); input = _mm256_set_ps(img_ptr[7 * width + refx], img_ptr[6 * width + refx], img_ptr[5 * width + refx], img_ptr[4 * width + refx], img_ptr[3 * width + refx], img_ptr[2 * width + refx], img_ptr[width + refx], img_ptr[refx]); //patch[0] = _mm256_add_ps(patch[0], _mm256_mul_ps(_mm256_set1_ps(h[m]), input)); patch[0] = _mm256_fmadd_ps(_mm256_set1_ps(h[m]), input, patch[0]); } ++img_ptr; for (int i = 1; i < 8; ++i) { input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]); //patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i - 1])); patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i - 1], input); ++img_ptr; } _mm256_transpose8_ps(patch, patch_t); _mm256_storepatch_ps(dst, patch_t, width); dst += 8; //IIR filtering for (int x = 8; x < width; x += 8) { input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]); //patch[0] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[7])); patch[0] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[7], input); ++img_ptr; for (int i = 1; i < 8; ++i) { input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]); //patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i - 1])); patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i - 1], input); ++img_ptr; } _mm256_transpose8_ps(patch, patch_t); _mm256_storepatch_ps(dst, patch_t, width); dst += 8; } } //reverse direction for (int y = 0; y < height; y += 8) { //boundary processing img_ptr = img.ptr<float>(y) + width - 1; dst = img_ptr - 7; input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]); patch[7] = _mm256_div_ps(input, _mm256_set1_ps(norm)); --img_ptr; for (int i = 6; i >= 0; --i) { input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]); //patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i + 1])); patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i + 1], input); --img_ptr; } _mm256_transpose8_ps(patch, patch_t); _mm256_storepatch_ps(dst, patch_t, width); dst -= 8; //IIR filtering for (int x = width - 16; 0 <= x; x -= 8) { input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]); //patch[7] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[0])); patch[7] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[0], input); --img_ptr; for (int i = 6; i >= 0; --i) { input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]); //patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i + 1])); patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i + 1], input); --img_ptr; } _mm256_transpose8_ps(patch, patch_t); _mm256_storepatch_ps(dst, patch_t, width); dst -= 8; } } } void GaussianFilterAM_AVX_32F::verticalFilter(Mat& img) { const int width = imgSize.width; const int height = imgSize.height; float* imgPtr; __m256 accum; //forward processing imgPtr = img.ptr<float>(); for (int x = 0; x < width; x += 8) { accum = _mm256_setzero_ps(); for (int m = 0; m < r_init; ++m) { accum = _mm256_add_ps(accum, _mm256_mul_ps(_mm256_set1_ps(h[m]), *(__m256*)(imgPtr + x + ref_tborder(-m, width, borderType)))); } _mm256_store_ps(imgPtr + x, accum); } for (int y = 1; y < height; ++y) { imgPtr = img.ptr<float>(y); for (int x = 0; x < width; x += 8) *(__m256*)(imgPtr + x) = _mm256_add_ps(*(__m256*)(imgPtr + x), _mm256_mul_ps(_mm256_set1_ps(nu), *(__m256*)(imgPtr + x - width))); } //backward processing imgPtr = img.ptr<float>(height - 1); for (int x = 0; x < width; x += 8) *(__m256*)(imgPtr + x) = _mm256_div_ps(*(__m256*)(imgPtr + x), _mm256_set1_ps(norm)); for (int y = height - 2; y >= 0; --y) { imgPtr = img.ptr<float>(y); for (int x = 0; x < width; x += 8) *(__m256*)(imgPtr + x) = _mm256_add_ps(*(__m256*)(imgPtr + x), _mm256_mul_ps(_mm256_set1_ps(nu), *(__m256*)(imgPtr + x + width))); } } void GaussianFilterAM_AVX_32F::body(const cv::Mat& src, cv::Mat& dst, const int borderType) { this->borderType = borderType; CV_Assert(src.cols % 8 == 0); CV_Assert(src.rows % 8 == 0); CV_Assert(src.depth()==CV_8U|| src.depth() == CV_32F); if (dest_depth == CV_32F) { if (src.depth() == CV_32F) multiply(src, scale, dst); else src.convertTo(dst, CV_32F, scale); for (int k = 0; k < gf_order; ++k) { //horizontalFilterVLoadSetTransposeStore(dst); horizontalFilterVLoadGatherTransposeStore(dst); } multiply(dst, scale, dst); for (int k = 0; k < gf_order; ++k) { verticalFilter(dst); } } else { inter.create(src.size(), CV_32F); if (src.depth() == CV_32F) multiply(src, scale, inter); else src.convertTo(inter, CV_32F, scale); for (int k = 0; k < gf_order; ++k) { //horizontalFilterVLoadSetTransposeStore(inter); horizontalFilterVLoadGatherTransposeStore(inter); } multiply(inter, scale, inter); for (int k = 0; k < gf_order; ++k) { verticalFilter(inter); } inter.convertTo(dst, dest_depth); } } void GaussianFilterAM_AVX_32F::filter(const cv::Mat& src, cv::Mat& dst, const double sigma, const int order, const int borderType) { if (this->sigma != sigma || this->gf_order != order || imgSize != src.size()) { this->sigma = sigma; this->gf_order = order; this->imgSize = src.size(); allocBuffer(); } body(src, dst, borderType); } #pragma endregion #pragma region GaussianFilterAM_AVX_64F void GaussianFilterAM_AVX_64F::allocBuffer() { const double q = sigma * (1.0 + (0.3165 * gf_order + 0.5695) / ((gf_order + 0.7818) * (gf_order + 0.7818))); const double lambda = (q * q) / (2.0 * gf_order); nu = ((1.0 + 2.0 * lambda - sqrt(1.0 + 4.0 * lambda)) / (2.0 * lambda)); r_init = (int)ceil(log((1.0 - nu) * tol) / log(nu)); scale = pow(nu / lambda, gf_order); __m256d mm_nu = _mm256_broadcast_sd(&nu); this->mm_h = (__m256d*)_mm_malloc(r_init * sizeof(__m256d), 32); this->mm_h[0] = _mm256_set1_pd(1.0); for (int i = 1; i < r_init; ++i) { this->mm_h[i] = _mm256_mul_pd(mm_nu, mm_h[i - 1]); } } GaussianFilterAM_AVX_64F::GaussianFilterAM_AVX_64F(cv::Size imgSize, double sigma, int order) : SpatialFilterBase(imgSize, CV_64F) { this->gf_order = order; this->sigma = sigma; allocBuffer(); } GaussianFilterAM_AVX_64F::GaussianFilterAM_AVX_64F(const int dest_depth) { this->dest_depth = dest_depth; this->depth = CV_64F; } GaussianFilterAM_AVX_64F::~GaussianFilterAM_AVX_64F() { _mm_free(mm_h); } //gather_vload->store transpose unroll 4 void GaussianFilterAM_AVX_64F::horizontalFilterVloadGatherTranposeStore(cv::Mat& img) { const int width = imgSize.width; const int height = imgSize.height; double* img_ptr; __m256d cur; __m256d patch[4]; __m256d patch_t[4]; __m128i mm_offset = _mm_set_epi32(3 * width, 2 * width, width, 0); __m256d mm_nu= _mm256_broadcast_sd(&nu); __m256d mm_norm= _mm256_set1_pd((1.0 - nu)); //forward direction for (int y = 0; y < height; y += 4) { //boundary processing img_ptr = img.ptr<double>(y); patch[0] = _mm256_setzero_pd(); for (int m = 0; m < r_init; ++m) { cur = _mm256_i32gather_pd(img_ptr + ref_lborder(-m, borderType), mm_offset, sizeof(double)); //patch[0] = _mm256_add_pd(patch[0], _mm256_mul_pd(mm_h[m], cur)); patch[0] = _mm256_fmadd_pd(mm_h[m], cur, patch[0]); } for (int i = 1; i < 4; ++i) { cur = _mm256_i32gather_pd(img_ptr + i, mm_offset, sizeof(double)); //patch[i] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[i - 1])); patch[i] = _mm256_fmadd_pd(mm_nu, patch[i - 1], cur); } _mm256_transpose4_pd(patch, patch_t); _mm256_storeupatch_pd(img_ptr, patch_t, width); //IIR filtering for (int x = 4; x < width; x += 4) { cur = _mm256_i32gather_pd(img_ptr + x, mm_offset, sizeof(double)); //patch[0] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[3])); patch[0] = _mm256_fmadd_pd(mm_nu, patch[3], cur); for (int i = 1; i < 4; ++i) { cur = _mm256_i32gather_pd(img_ptr + x + i, mm_offset, sizeof(double)); //patch[i] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[i - 1])); patch[i] = _mm256_fmadd_pd(mm_nu, patch[i - 1], cur); } _mm256_transpose4_pd(patch, patch_t); _mm256_storeupatch_pd(img_ptr + x, patch_t, width); } } //reverse direction for (int y = 0; y < height; y += 4) { //boundary processing img_ptr = img.ptr<double>(y); patch[3] = _mm256_i32gather_pd(img_ptr + width - 1, mm_offset, sizeof(double)); patch[3] = _mm256_div_pd(patch[3], mm_norm); for (int i = 2; i >= 0; --i) { cur = _mm256_i32gather_pd(img_ptr + width - 4 + i, mm_offset, sizeof(double)); //patch[i] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[i + 1])); patch[i] = _mm256_fmadd_pd(mm_nu, patch[i + 1], cur); } _mm256_transpose4_pd(patch, patch_t); _mm256_storeupatch_pd(img_ptr + width - 4, patch_t, width); //IIR filtering for (int x = width - 8; 0 <= x; x -= 4) { cur = _mm256_i32gather_pd(img_ptr + x + 3, mm_offset, sizeof(double)); //patch[3] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[0])); patch[3] = _mm256_fmadd_pd(mm_nu, patch[0], cur); for (int i = 2; i >= 0; --i) { cur = _mm256_i32gather_pd(img_ptr + x + i, mm_offset, sizeof(double)); //patch[i] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[i + 1])); patch[i] = _mm256_fmadd_pd(mm_nu, patch[i + 1], cur); } _mm256_transpose4_pd(patch, patch_t); _mm256_storeupatch_pd(img_ptr + x, patch_t, width); } } } void GaussianFilterAM_AVX_64F::verticalFilter(Mat& img) { const int width = imgSize.width; const int height = imgSize.height; //forward direction double* imgPtr = img.ptr<double>(); __m256d mm_nu = _mm256_broadcast_sd(&nu); __m256d mm_norm = _mm256_set1_pd((1.0 - nu)); for (int x = 0; x < width; x += 4) { //boundary processing __m256d accum = _mm256_setzero_pd(); for (int m = 0; m < r_init; ++m) { //accum = _mm256_add_pd(accum, _mm256_mul_pd(mm_h[m], *(__m256d*)(imgPtr + x + ref_tborder(-m, width, borderType)))); accum = _mm256_fmadd_pd(mm_h[m], *(__m256d*)(imgPtr + x + ref_tborder(-m, width, borderType)), accum); } _mm256_store_pd(imgPtr + x, accum); } //IIR filtering for (int y = 1; y < height; ++y) { imgPtr = img.ptr<double>(y); for (int x = 0; x < width; x += 4) { //*(__m256d*)(imgPtr + x) = _mm256_add_pd(*(__m256d*)(imgPtr + x), _mm256_mul_pd(mm_nu, *(__m256d*)(imgPtr + x - width))); *(__m256d*)(imgPtr + x) = _mm256_fmadd_pd(mm_nu, *(__m256d*)(imgPtr + x - width), *(__m256d*)(imgPtr + x)); } } //reverse direction imgPtr = img.ptr<double>(height - 1); __m256d mdiv = _mm256_div_pd(_mm256_set1_pd(1.0), mm_norm); //boundary processing for (int x = 0; x < width; x += 4) { *(__m256d*)(imgPtr + x) = _mm256_mul_pd(*(__m256d*)(imgPtr + x), mdiv); } //IIR filtering for (int y = height - 2; y >= 0; --y) { imgPtr = img.ptr<double>(y); for (int x = 0; x < width; x += 4) { //*(__m256d*)(imgPtr + x) = _mm256_add_pd(*(__m256d*)(imgPtr + x), _mm256_mul_pd(mm_nu, *(__m256d*)(imgPtr + x + width))); *(__m256d*)(imgPtr + x) = _mm256_fmadd_pd(mm_nu, *(__m256d*)(imgPtr + x + width), *(__m256d*)(imgPtr + x)); } } } void GaussianFilterAM_AVX_64F::body(const cv::Mat& src, cv::Mat& dst, const int borderType) { this->borderType = borderType; CV_Assert(src.cols % 4 == 0); CV_Assert(src.rows % 4 == 0); CV_Assert(src.depth() == CV_8U || src.depth() == CV_32F || src.depth() == CV_64F); if (dest_depth == CV_64F) { if (src.depth() == CV_64F) multiply(src, scale, dst); else src.convertTo(dst, CV_64F, scale); for (int k = 0; k < gf_order; ++k) { horizontalFilterVloadGatherTranposeStore(dst); } multiply(dst, scale, dst); for (int k = 0; k < gf_order; ++k) { verticalFilter(dst); } } else { inter.create(src.size(), CV_64F); if (src.depth() == CV_64F) multiply(src, scale, inter); else src.convertTo(inter, CV_64F, scale); for (int k = 0; k < gf_order; ++k) { horizontalFilterVloadGatherTranposeStore(inter); } multiply(inter, scale, inter); for (int k = 0; k < gf_order; ++k) { verticalFilter(inter); } inter.convertTo(dst, dest_depth); } } void GaussianFilterAM_AVX_64F::filter(const cv::Mat& src, cv::Mat& dst, const double sigma, const int order, const int borderType) { if (this->sigma != sigma || this->gf_order != order || imgSize != src.size()) { this->sigma = sigma; this->gf_order = order; this->imgSize = src.size(); allocBuffer(); } body(src, dst, borderType); } #pragma endregion }
28.785806
226
0.621588
norishigefukushima
86b98be3e4213c1664fcf3eeae72e9a77b84759a
35,519
cpp
C++
AdsLedMatrixCMS/v3.0.1/soft_v3/MatrixSimulator.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
null
null
null
AdsLedMatrixCMS/v3.0.1/soft_v3/MatrixSimulator.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
null
null
null
AdsLedMatrixCMS/v3.0.1/soft_v3/MatrixSimulator.cpp
cuongquay/led-matrix-display
6dd0e3be9ee23862610dab7b0d40970c6900e5e4
[ "Apache-2.0" ]
1
2020-06-13T08:34:26.000Z
2020-06-13T08:34:26.000Z
// MatrixSimulator.cpp : implementation file // #include "stdafx.h" #include "MATRIX.h" #include "FontDisp.h" #include "MatrixSimulator.h" #include "resource.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define TIMER_ID 1001 #define CLOCK_ID 1002 extern FONT_CHAR char_map[256]; #define LAYER_COUNT 4 #define BLANK_STATE 0x00 static BYTE buffer[2048*8][32]; // 512 characters max - 64KBs static BYTE __SCREEN_LAYER[LAYER_COUNT][DATA_LINE*DATA_LENGTH]; static BYTE __FONT_BUFFER[LAYER_COUNT][DATA_LINE*DATA_LENGTH]; ///////////////////////////////////////////////////////////////////////////// // CMatrixSimulator CMatrixSimulator::CMatrixSimulator() { m_cx = 0; m_cy = 0; m_pBuffer = NULL; m_ptPosition = CPoint(0,0); m_pOrigin = new BYTE[DATA_LINE*DATA_LENGTH]; m_pEnd = m_pOrigin + DATA_LINE*DATA_LENGTH; memset(m_pOrigin,BLANK_STATE,DATA_LINE*DATA_LENGTH); m_pClock = new BYTE[DATA_LINE*CLOCK_LENGTH]; memset(m_pClock,BLANK_STATE,DATA_LINE*CLOCK_LENGTH); m_bHitScroll = FALSE; m_bReCalcMatrix = FALSE; m_szBkPos = CSize(0,0); m_pDCMem = NULL; m_nChar = 0; m_nColumeH = 0; m_nColumeL = 0; m_nTextLength = 0; m_nFontTextLength = 0; m_pStart = m_pOrigin; m_pStaticLine = NULL; m_nCurrentLayer = 0; m_bScrolling = FALSE; m_nFontPixelLenght = 0; m_bLoadBkgndImgs = FALSE; m_bVisibleBkLayer = TRUE; m_bVisibleLayer[0] = TRUE; m_bVisibleLayer[1] = TRUE; m_bVisibleLayer[2] = TRUE; m_bVisibleLayer[3] = TRUE; for (int i = 0; i<LAYER_COUNT; i++) { m_szTextPos[i] = CSize(0,0); m_nTextLengthPixel[i] = 0; m_bLoadImage[i] = FALSE; memset(__SCREEN_LAYER[i],BLANK_STATE,DATA_LINE*DATA_LENGTH); memset(__FONT_BUFFER[i],BLANK_STATE,DATA_LINE*DATA_LENGTH); } } CMatrixSimulator::~CMatrixSimulator() { if (m_pDCMem){ //m_pDCMem->SelectObject(m_pOldBitmap); //m_pDCMem->DeleteDC(); delete m_pDCMem; } } BEGIN_MESSAGE_MAP(CMatrixSimulator, CStatic) ON_WM_CONTEXTMENU() //{{AFX_MSG_MAP(CMatrixSimulator) ON_WM_DESTROY() ON_WM_PAINT() ON_WM_TIMER() ON_WM_CREATE() ON_COMMAND(ID_POPUP_CHANGESCALE_1X1, OnPopupChangescale1x1) ON_COMMAND(ID_POPUP_CHANGESCALE_2X2, OnPopupChangescale2x2) ON_COMMAND(ID_POPUP_CHANGESCALE_3X3, OnPopupChangescale3x3) ON_COMMAND(ID_POPUP_CHANGESCALE_4X4, OnPopupChangescale4x4) ON_COMMAND(ID_POPUP_STARTSCROLL, OnPopupStartscroll) ON_COMMAND(ID_POPUP_STOPSCROLL, OnPopupStopscroll) ON_COMMAND(ID_POPUP_LOADFRAMESIMAGE, OnPopupLoadframesimage) ON_COMMAND(ID_POPUP_LOADBACKGROUNDIMAGE, OnPopupLoadbackgroundimage) ON_WM_VSCROLL() ON_WM_HSCROLL() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMatrixSimulator message handlers void CMatrixSimulator::OnDestroy() { CStatic::OnDestroy(); if (m_pOrigin) delete[] m_pOrigin; if (m_pStaticLine) delete[] m_pStaticLine; if (m_pClock) delete[] m_pClock; } void CMatrixSimulator::OnPaint() { CPaintDC dc(this); // device context for painting CDC* pDC =&dc; CRect rect; GetClientRect(rect); if (m_pDCMem == NULL){ m_pDCMem = new CDC(); m_pDCMem->CreateCompatibleDC(pDC); m_bmpDCMem.CreateCompatibleBitmap(pDC, rect.Width(),rect.Height() ); m_pOldBitmap = m_pDCMem->SelectObject(&m_bmpDCMem); this->DisplayFrame(m_pDCMem,FALSE); } else if (m_bReCalcMatrix){ m_bReCalcMatrix = FALSE; if(m_bmpDCMem.DeleteObject()){ m_bmpDCMem.CreateCompatibleBitmap(pDC, rect.Width(),rect.Height() ); m_pOldBitmap = m_pDCMem->SelectObject(&m_bmpDCMem); this->DisplayFrame(m_pDCMem,FALSE); } } if (m_bHitScroll){ m_bHitScroll = FALSE; dc.BitBlt(0,0,rect.Width(), rect.Height(),m_pDCMem,0,0,SRCCOPY); } else{ this->DisplayFrame(pDC,FALSE); } pDC->DrawEdge(&rect,BDR_RAISEDINNER,BF_RECT|BF_ADJUST); pDC->DrawEdge(&rect,BDR_SUNKENOUTER,BF_RECT|BF_ADJUST); } void CMatrixSimulator::OnTimer(UINT nIDEvent) { if (nIDEvent == TIMER_ID && m_nScrollMode) { if (m_wCharWidth[m_nChar] >= m_cx) { m_pStart ++; } else { m_pStart += 8; if (m_pStart > m_pOrigin + m_cx - m_wCharWidth[m_nChar]) { m_nChar++; m_pStart = m_pOrigin + m_wCharWidth[m_nChar]; } } int nTextLengthPixel = m_nTextLengthPixel[0] - m_szTextPos[0].cx; for (int i=0; i< LAYER_COUNT; i++) { if (nTextLengthPixel < m_nTextLengthPixel[i] - m_szTextPos[0].cx) nTextLengthPixel = m_nTextLengthPixel[i] - m_szTextPos[0].cx; } int cx = m_cx + nTextLengthPixel; if (m_pStart >= m_pOrigin + (cx + 10)) { m_pStart = m_pOrigin; m_nChar = 0; } CClientDC dc(this); CDC* pDC =&dc; this->Invalidate(FALSE); } else if (nIDEvent == CLOCK_ID) { CTime time = CTime::GetCurrentTime(); CString csText = time.Format(_T("%H:%M:%S")); char szText[50] = {0x01,0x02,0x03,0x00}; #ifdef _UNICODE LPTSTR szData = (LPTSTR)csText.GetBuffer(csText.GetLength()); int length = WideCharToMultiByte(CP_ACP,0,szData,wcslen(szData),szText,sizeof(szText),NULL,NULL); szText[length] = '\0'; #endif ShowClock(szText); } CStatic::OnTimer(nIDEvent); } void CMatrixSimulator::SetPixelSize(int cx, int cy) { m_cx = cx; m_cy = cy; if (m_pStaticLine) delete[] m_pStaticLine; m_pStaticLine = new BYTE[m_cx*8]; memset(m_pStaticLine,BLANK_STATE,m_cx*8); ClearScreen(); for (int i =0;i < LAYER_COUNT;i++) ClearLayer(i); } void CMatrixSimulator::SetCurrentLayer(int nLayer) { m_nCurrentLayer = nLayer; } CSize CMatrixSimulator::GetPixelSize() const { return CSize(m_cx,m_cy); } void CMatrixSimulator::GetPixelSize(int *cx, int *cy) { *cx = m_cx; *cy = m_cy; } void CMatrixSimulator::DisplayFrame(CDC*pDC, BOOL bRefresh) { // display one frame in the screen at the specific time int count_col = 0, count_row = 0; if (pDC){ if (pDC->m_hDC){ m_nColumeL = m_cx - (m_pStart - m_pOrigin) + m_wCharWidth[m_nChar]; m_nColumeH = m_cx - (m_pStart - m_pOrigin) + m_wCharWidth[m_nChar+1]; for (m_pBuffer = m_pStart;m_pBuffer < m_pEnd; m_pBuffer++) { DrawBitCol(pDC,count_col,count_row); if ( ++count_col >= m_cx) { count_col = 0; // reset for next colume if (++count_row >= 8) { // reset row for next row count_row = 0; } m_pBuffer += DATA_LENGTH - m_cx; } } if (bRefresh){ this->Invalidate(FALSE); } } } } extern CGeneralSettings __SETTING; void CMatrixSimulator::ReCalcLayout(int scale, BOOL bRedraw) { m_bReCalcMatrix = TRUE; SetWindowPos(NULL,0,0,m_cx*scale+1,m_cy*scale+1,SWP_NOMOVE); if (bRedraw) { this->RedrawWindow(); GetParent()->RedrawWindow(); } __SETTING.m_nScale = scale; } int CMatrixSimulator::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CStatic::OnCreate(lpCreateStruct) == -1) return -1; return 0; } void CMatrixSimulator::DrawBitCol(CDC *pDC, int bit_col, int bit_row) { CRect rect = CRect(); GetClientRect(&rect); int cx = rect.Width()/m_cx; int cy = rect.Height()/m_cy; CBrush brR(RGB(255,0,0)); CBrush brG(RGB(0,255,0)); CBrush brY(RGB(255,255,0)); CBrush brW(RGB(50,50,50)); CBrush* pBrC = NULL; CBrush* pBrOld = pDC->SelectObject(&brR); // drawing 4 lines with 2 colors here BYTE mask = 0x01; BOOL bR = FALSE, bG = FALSE; // one byte in m_pBuffer[] contain 8 lines for (int line = 0; line < m_cy/8; line++) { CRect rc = CRect(rect); rc.right = rc.left + cx +1; rc.bottom = rc.top + cy +1; rc.OffsetRect(0,cy*line*8); for (int i = 0; i< bit_col; i++) rc.OffsetRect(cx,0); for (int j = 0; j< bit_row; j++) rc.OffsetRect(0,cy); // select white color pDC->SelectObject(brW); bR = FALSE; bG = FALSE; // processing scroll mode BYTE data = 0; if (m_bScrolling) { if (m_wCharWidth[m_nChar] < m_cx) { if (bit_col < m_wCharWidth[m_nChar]) { data = m_pOrigin[m_cx + bit_col + DATA_LENGTH*bit_row]; } else if ((bit_col > m_nColumeL) && (bit_col < m_nColumeH)) data = (*m_pBuffer); else data = 0x00; } else { data = (*m_pBuffer); } if (bit_col < 80) { data = m_pClock[bit_col+bit_row*CLOCK_LENGTH] ; } } else { if (m_bVisibleBkLayer) data = (data) | (m_pStaticLine[bit_col+bit_row*m_cx]); for (int l=LAYER_COUNT-1; l>= 0; l--) { if (m_bVisibleLayer[l]) data = ExtORByte(data,__SCREEN_LAYER[l][bit_col + DATA_LENGTH*bit_row + m_cx]); } } COLORREF clr = RGB(0,0,0); // check red color if (data&mask) { bR = TRUE; clr = RGB(255,0,0); pDC->SelectObject(brR); } mask = mask<<1; // check green color if (data&mask) { bG = TRUE; clr = RGB(0,255,0); pDC->SelectObject(brG); } // check yellow color if (bR && bG){ clr = RGB(255,255,0); pDC->SelectObject(brY); } if ( cx > 1 ){ pDC->Ellipse(rc); } else{ pDC->SetPixel(CPoint(rc.left,rc.top),clr); } mask = mask<<1; } pDC->SelectObject(pBrOld); } void CMatrixSimulator::ClearScreen() { memset(m_pOrigin,BLANK_STATE,DATA_LINE*DATA_LENGTH); memset(m_pClock,BLANK_STATE,DATA_LINE*CLOCK_LENGTH); this->Invalidate(FALSE); } void CMatrixSimulator::ClearLayer(int nLayer) { m_szTextPos[nLayer] = CSize(0,0); m_bLoadImage[m_nCurrentLayer] = FALSE; memset(__SCREEN_LAYER[nLayer],BLANK_STATE,DATA_LINE*DATA_LENGTH); this->Invalidate(FALSE); } void CMatrixSimulator::ClearBkGnd() { m_szBkPos = CSize(0,0); m_bLoadBkgndImgs = FALSE; memset(m_pStaticLine,BLANK_STATE,m_cx*DATA_LINE); this->Invalidate(FALSE); } void CMatrixSimulator::SetRate(int nRate) { m_nRate = nRate; } void CMatrixSimulator::StartScroll(int nRate) { this->ClearScreen(); for (int i=3; i>= 0; i--) if (m_bVisibleLayer[i]) this->MergeLayer(i); m_pStart = m_pOrigin + 0; m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE; m_bScrolling = TRUE; SetTimer(TIMER_ID,m_nRate=nRate,NULL); SetTimer(CLOCK_ID,500,NULL); } void CMatrixSimulator::StopScroll() { m_bScrolling = FALSE; KillTimer(TIMER_ID); KillTimer(CLOCK_ID); this->Invalidate(FALSE); } void CMatrixSimulator::LoadData(PBYTE pData, int nSize) { #if 0 if (DATA_LINE*DATA_LENGTH > nSize) memcpy(m_pOrigin,pData,nSize); else memcpy(m_pOrigin,pData,DATA_LINE*DATA_LENGTH); #else static int i = 0; static int row = 0; m_pOrigin[i + row*DATA_LENGTH] = *pData; if (++i >= nSize) { i = 0; if (++row>=8) row =0; } Invalidate(); #endif } void CMatrixSimulator::LoadText(const char *szText, int nColor, BOOL bGradient) { int cx =0, nPixel =0; PBYTE pData = __SCREEN_LAYER[m_nCurrentLayer] + m_cx; if (m_bLoadImage[m_nCurrentLayer]==FALSE){ memset(__SCREEN_LAYER[m_nCurrentLayer],BLANK_STATE,DATA_LINE*DATA_LENGTH); } nPixel = TextFromFont(szText,nColor, FALSE/*bGradient*/, (PBYTE*)&pData,DATA_LENGTH); m_wCharWidth[0] = 0; int len = m_nTextLength = strlen(szText); for (int i = 0; i< len; i++) { BYTE sz = BYTE(szText[i]); if (sz >255) sz =255; cx += char_map[sz].width; if (i <256){ m_wCharWidth[i + 1] = cx; } if (cx > DATA_LENGTH) break; // cut off too long text } m_nTextLengthPixel[m_nCurrentLayer] = nPixel; MoveText(m_szTextPos[m_nCurrentLayer].cx,m_szTextPos[m_nCurrentLayer].cy,m_nCurrentLayer,FALSE); m_pStart = m_pOrigin + m_cx; m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE; if (bGradient) GradientLayer(nColor,m_nCurrentLayer); this->Invalidate(FALSE); } void CMatrixSimulator::LoadCharMap(LPCTSTR szFile) { #ifdef __OLD_VER_SAVE_FONT CFile file(szFile,CFile::modeRead); CArchive ar(&file,CArchive::load); for (int i = 0; i < 256; i++) { ar>>char_map[i].heigth>>char_map[i].width; for (int x = 0; x < char_map[i].width; x++) { for (int y = 0; y < char_map[i].heigth; y++) { ar>>char_map[i].pdata[x][y]; } } } ar.Close(); file.Close(); #else DecompressFont(szFile); LoadFont(); #endif } int CMatrixSimulator::GetBuffer(PBYTE *pBuffer, int nLayer) { *pBuffer = __SCREEN_LAYER[m_nCurrentLayer] + m_cx; int nTextLengthPixel = m_nTextLengthPixel[m_nCurrentLayer] - m_szTextPos[m_nCurrentLayer].cx; return nTextLengthPixel; } int CMatrixSimulator::GetBuffer(PBYTE *pBuffer) { *pBuffer = m_pOrigin + m_cx; int nTextLengthPixel = m_nTextLengthPixel[0] - m_szTextPos[0].cx; for (int i=0; i< LAYER_COUNT; i++) { if (nTextLengthPixel < m_nTextLengthPixel[i] - m_szTextPos[i].cx) nTextLengthPixel = m_nTextLengthPixel[i] - m_szTextPos[i].cx; } return (nTextLengthPixel); } int CMatrixSimulator::GetStaticBuffer(PBYTE* pBuffer) { *pBuffer = m_pStaticLine; return (m_cx); } void CMatrixSimulator::LoadStaticText(const char *szText, int nColor, BOOL bGradient) { PBYTE pData = m_pStaticLine; if (m_bLoadBkgndImgs==FALSE){ memset(m_pStaticLine,0x00,m_cx*8); } UINT nLength = TextFromFont(szText,nColor, FALSE/*bGradient*/, (PBYTE*)&m_pStaticLine,m_cx); MoveStaticText(m_szBkPos.cx,m_szBkPos.cy,FALSE); if (bGradient) GradientLayer(nColor,-1); this->Invalidate(FALSE); } void CMatrixSimulator::SetScrollMode(int nMode) { m_nScrollMode = nMode; } void CMatrixSimulator::MoveText(int x, int y, int layer, BOOL bUpdate) { PBYTE pBuffer = __SCREEN_LAYER[layer]; if (bUpdate) { m_szTextPos[layer].cx += x; m_szTextPos[layer].cy += y; } // moving on x-axis if (x > 0) for (int j = 0; j < 8; j++) for (int i = 0; i < DATA_LENGTH; i++) if ( i >= DATA_LENGTH - x) pBuffer[i + (DATA_LENGTH*j)] = 0; else pBuffer[i + (DATA_LENGTH*j)] = pBuffer[i+x+(DATA_LENGTH*j)]; else if (x < 0) for (int j = 0; j < 8; j++) for (int i = DATA_LENGTH-1; i >=0 ; i--) if ( i < -x ) pBuffer[i + (DATA_LENGTH*j)] = 0; else pBuffer[i + (DATA_LENGTH*j)] = pBuffer[i+x+(DATA_LENGTH*j)]; // moving on y-axis if (y > 0) for (int b = 0; b < y ; b++) for (int i = 0; i < DATA_LENGTH ; i++) { BYTE mask = 0x03; for (int x=0;x<4;x++){ pBuffer[i +(DATA_LENGTH*0)]= pBuffer[i +(DATA_LENGTH*0)]&(~mask) | pBuffer[i +(DATA_LENGTH*1)]&mask; pBuffer[i +(DATA_LENGTH*1)]= pBuffer[i +(DATA_LENGTH*1)]&(~mask) | pBuffer[i +(DATA_LENGTH*2)]&mask; pBuffer[i +(DATA_LENGTH*2)]= pBuffer[i +(DATA_LENGTH*2)]&(~mask) | pBuffer[i +(DATA_LENGTH*3)]&mask; pBuffer[i +(DATA_LENGTH*3)]= pBuffer[i +(DATA_LENGTH*3)]&(~mask) | pBuffer[i +(DATA_LENGTH*4)]&mask; pBuffer[i +(DATA_LENGTH*4)]= pBuffer[i +(DATA_LENGTH*4)]&(~mask) | pBuffer[i +(DATA_LENGTH*5)]&mask; pBuffer[i +(DATA_LENGTH*5)]= pBuffer[i +(DATA_LENGTH*5)]&(~mask) | pBuffer[i +(DATA_LENGTH*6)]&mask; pBuffer[i +(DATA_LENGTH*6)]= pBuffer[i +(DATA_LENGTH*6)]&(~mask) | pBuffer[i +(DATA_LENGTH*7)]&mask; pBuffer[i +(DATA_LENGTH*7)]= pBuffer[i +(DATA_LENGTH*7)]&(~mask) | (pBuffer[i +(DATA_LENGTH*0)]&(mask<<2))>>2; mask = mask<<2; } } else if (y < 0) for (int b = 0; b < -y ; b++) for (int i = 0; i < DATA_LENGTH ; i++) { BYTE mask = 0xC0; for (int x=0;x<4;x++){ pBuffer[i +(DATA_LENGTH*7)]= pBuffer[i +(DATA_LENGTH*7)]&(~mask) | pBuffer[i +(DATA_LENGTH*6)]&mask; pBuffer[i +(DATA_LENGTH*6)]= pBuffer[i +(DATA_LENGTH*6)]&(~mask) | pBuffer[i +(DATA_LENGTH*5)]&mask; pBuffer[i +(DATA_LENGTH*5)]= pBuffer[i +(DATA_LENGTH*5)]&(~mask) | pBuffer[i +(DATA_LENGTH*4)]&mask; pBuffer[i +(DATA_LENGTH*4)]= pBuffer[i +(DATA_LENGTH*4)]&(~mask) | pBuffer[i +(DATA_LENGTH*3)]&mask; pBuffer[i +(DATA_LENGTH*3)]= pBuffer[i +(DATA_LENGTH*3)]&(~mask) | pBuffer[i +(DATA_LENGTH*2)]&mask; pBuffer[i +(DATA_LENGTH*2)]= pBuffer[i +(DATA_LENGTH*2)]&(~mask) | pBuffer[i +(DATA_LENGTH*1)]&mask; pBuffer[i +(DATA_LENGTH*1)]= pBuffer[i +(DATA_LENGTH*1)]&(~mask) | pBuffer[i +(DATA_LENGTH*0)]&mask; pBuffer[i +(DATA_LENGTH*0)]= pBuffer[i +(DATA_LENGTH*0)]&(~mask) | (pBuffer[i +(DATA_LENGTH*7)]&(mask>>2))<<2; mask = mask>>2; } } this->Invalidate(FALSE); } void CMatrixSimulator::MoveStaticText(int x, int y, BOOL bUpdate) { PBYTE pBuffer = m_pStaticLine; if (bUpdate) { m_szBkPos.cx += x; m_szBkPos.cy += y; } // moving on x-axis if (x > 0) for (int j = 0; j < 8; j++) for (int i = 0; i < m_cx; i++) if ( i >= m_cx - x) pBuffer[i + (m_cx*j)] = 0; else pBuffer[i + (m_cx*j)] = pBuffer[i+x+(m_cx*j)]; else if (x < 0) for (int j = 0; j < 8; j++) for (int i = m_cx-1; i >=0 ; i--) if ( i < -x ) pBuffer[i + (m_cx*j)] = 0; else pBuffer[i + (m_cx*j)] = pBuffer[i+x+(m_cx*j)]; // moving on y-axis if (y > 0) for (int b = 0; b < y ; b++) for (int i = 0; i < m_cx ; i++) { BYTE mask = 0x03; for (int x=0;x<4;x++){ pBuffer[i +(m_cx*0)]= pBuffer[i +(m_cx*0)]&(~mask) | pBuffer[i +(m_cx*1)]&mask; pBuffer[i +(m_cx*1)]= pBuffer[i +(m_cx*1)]&(~mask) | pBuffer[i +(m_cx*2)]&mask; pBuffer[i +(m_cx*2)]= pBuffer[i +(m_cx*2)]&(~mask) | pBuffer[i +(m_cx*3)]&mask; pBuffer[i +(m_cx*3)]= pBuffer[i +(m_cx*3)]&(~mask) | pBuffer[i +(m_cx*4)]&mask; pBuffer[i +(m_cx*4)]= pBuffer[i +(m_cx*4)]&(~mask) | pBuffer[i +(m_cx*5)]&mask; pBuffer[i +(m_cx*5)]= pBuffer[i +(m_cx*5)]&(~mask) | pBuffer[i +(m_cx*6)]&mask; pBuffer[i +(m_cx*6)]= pBuffer[i +(m_cx*6)]&(~mask) | pBuffer[i +(m_cx*7)]&mask; pBuffer[i +(m_cx*7)]= pBuffer[i +(m_cx*7)]&(~mask) | (pBuffer[i +(m_cx*0)]&(mask<<2))>>2; mask = mask<<2; } } else if (y < 0) for (int b = 0; b < -y ; b++) for (int i = 0; i < m_cx ; i++) { BYTE mask = 0xC0; for (int x=0;x<4;x++){ pBuffer[i +(m_cx*7)]= pBuffer[i +(m_cx*7)]&(~mask) | pBuffer[i +(m_cx*6)]&mask; pBuffer[i +(m_cx*6)]= pBuffer[i +(m_cx*6)]&(~mask) | pBuffer[i +(m_cx*5)]&mask; pBuffer[i +(m_cx*5)]= pBuffer[i +(m_cx*5)]&(~mask) | pBuffer[i +(m_cx*4)]&mask; pBuffer[i +(m_cx*4)]= pBuffer[i +(m_cx*4)]&(~mask) | pBuffer[i +(m_cx*3)]&mask; pBuffer[i +(m_cx*3)]= pBuffer[i +(m_cx*3)]&(~mask) | pBuffer[i +(m_cx*2)]&mask; pBuffer[i +(m_cx*2)]= pBuffer[i +(m_cx*2)]&(~mask) | pBuffer[i +(m_cx*1)]&mask; pBuffer[i +(m_cx*1)]= pBuffer[i +(m_cx*1)]&(~mask) | pBuffer[i +(m_cx*0)]&mask; pBuffer[i +(m_cx*0)]= pBuffer[i +(m_cx*0)]&(~mask) | (pBuffer[i +(m_cx*7)]&(mask>>2))<<2; mask = mask>>2; } } this->Invalidate(FALSE); } void CMatrixSimulator::MergeLayer(int nLayer) { for (int y=0 ; y < DATA_LINE; y++) { for (int x=0 ; x < DATA_LENGTH; x++) { m_pOrigin[x + DATA_LENGTH*y] = ExtORByte(m_pOrigin[x + DATA_LENGTH*y],__SCREEN_LAYER[nLayer][x + DATA_LENGTH*y]); } } // clear layer merged // memset(__SCREEN_LAYER[nLayer],0x00,DATA_LINE*DATA_LENGTH); m_pStart = m_pOrigin + m_cx; m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE; this->Invalidate(FALSE); } BYTE CMatrixSimulator::ExtORByte(BYTE byte1, BYTE byte2) { BYTE result = 0; BYTE mask = 0x03; for (int i =0; i< 4; i++) { if (byte2&mask) result |= byte2&mask; else result |= byte1&mask; mask = mask<<2; } return result; } void CMatrixSimulator::SetVisibleLayer(BOOL *bLayer) { memcpy(m_bVisibleLayer,bLayer,sizeof(m_bVisibleLayer)); } void CMatrixSimulator::SetVisibleBkLayer(BOOL bVisible) { m_bVisibleBkLayer = bVisible; } void CMatrixSimulator::OnContextMenu(CWnd*, CPoint point) { // CG: This block was added by the Pop-up Menu component { if (point.x == -1 && point.y == -1){ //keystroke invocation CRect rect; GetClientRect(rect); ClientToScreen(rect); point = rect.TopLeft(); point.Offset(5, 5); } CMenu menu; VERIFY(menu.LoadMenu(CG_IDR_POPUP_MATRIX_SIMULATOR)); CMenu* pPopup = menu.GetSubMenu(0); ASSERT(pPopup != NULL); CWnd* pWndPopupOwner = this; pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWndPopupOwner); } } void CMatrixSimulator::LoadBkGnd(LPCTSTR szBmpFile) { this->LoadImage(szBmpFile,TRUE); } void CMatrixSimulator::LoadImage(LPCTSTR szBmpFile, BOOL bBkGnd) { CDib dib; dib.Load(szBmpFile); CClientDC dc(this); CDC memDC; memDC.CreateCompatibleDC(&dc); CBitmap bitmap; if (dib.GetSize().cx > DATA_LENGTH || dib.GetSize().cy > 32) { MessageBox(_T("T\x1EAD"L"p tin \x1EA3"L"nh c\xF3"L" k\xED"L"ch th\x1B0"L"\x1EDB"L"c qu\xE1"L" l\x1EDB"L"n"),_T("Nap \x1EA3"L"nh"),MB_OK); return; } int cx = dib.GetSize().cx; int cy = dib.GetSize().cy; if (cx > DATA_LENGTH ) cx = DATA_LENGTH; if (cy > m_cy ) cy = m_cy; CRect rcDest = CRect(0,0,cx,cy); CRect rcSrc = CRect(0,0,cx,cy); dib.Draw(&dc,&rcDest,&rcSrc); bitmap.CreateCompatibleBitmap(&dc, cx, cy ); CBitmap* pOldBitmap = memDC.SelectObject(&bitmap); memDC.BitBlt(0, 0, cx, cy, &dc, 0, 0, SRCCOPY); BYTE buffer[DATA_LENGTH][32]; memset(buffer,0xFF,DATA_LENGTH*32); for (int x = 0; x < cx; x++) { for (int y = 0; y < cy; y++) { COLORREF clr = memDC.GetPixel(x,y); int nColor = 0; if ( GetRValue(clr) > 150 ) nColor = 1; if ( GetGValue(clr) > 150 ) nColor = 2; if ( GetRValue(clr) > 150 && GetGValue(clr) > 150 ) nColor = 3; buffer[x][y] = nColor; } } PBYTE pData = bBkGnd?m_pStaticLine:__SCREEN_LAYER[m_nCurrentLayer] + m_cx; if (!bBkGnd) memset(__SCREEN_LAYER[m_nCurrentLayer],0x00,DATA_LINE*DATA_LENGTH); else memset(m_pStaticLine,0x00,m_cx*DATA_LINE); for (int z=0; z< 8 ; z+=2) for (int y=0; y< 8 ; y++) { for (int x=0; x< (bBkGnd?m_cx:cx); x++) { if (buffer[x][y + z*4]) { pData[x + (y)*(bBkGnd?m_cx:DATA_LENGTH)] |= (buffer[x][y + z*4]<<z); } else if (buffer[x][y + z*4]==0) pData[x + (y)*(bBkGnd?m_cx:DATA_LENGTH)] &= ~(buffer[x][y + z*4]<<z); } } if (!bBkGnd) { m_pStart = m_pOrigin + m_cx; m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE; m_nTextLengthPixel[m_nCurrentLayer] = m_cx; m_bLoadImage[m_nCurrentLayer] = TRUE; } else{ m_bLoadBkgndImgs = TRUE; } memDC.SelectObject(pOldBitmap); GetParent()->RedrawWindow(CRect(0,0,m_cx,m_cy)); } void CMatrixSimulator::ChangeBkColor(int nColor, BOOL bGradient) { PBYTE pBuffer = m_pStaticLine; for (int i =0; i< m_cx*DATA_LINE; i++) { pBuffer[i] = ChangeColor(nColor,BYTE(pBuffer[i])); } if (bGradient) GradientLayer(nColor,-1); } BYTE CMatrixSimulator::ChangeColor(int nColor, BYTE data) { BYTE maskR = 0x01; BYTE maskG = 0x02; for (int i =0; i< 4; i++) { if (data&maskR) // red { data &= ~maskR; // clear old data |= nColor<<(i*2); //add new } else if (data&maskG) // green { data &= ~maskG; // clear old data |= nColor<<(i*2); //add new } if (data&maskR && data&maskG) // yeallow { data &= ~maskR; // clear old data &= ~maskG; // clear old data |= nColor<<(i*2); //add new } maskR = maskR<<2; maskG = maskG<<2; } return data; } void CMatrixSimulator::ChangeColor(int nColor, int nLayer, BOOL bGradient) { PBYTE pBuffer = __SCREEN_LAYER[nLayer]; for (int i =0; i< DATA_LENGTH*DATA_LINE; i++) { pBuffer[i] = ChangeColor(nColor,BYTE(pBuffer[i])); } if (bGradient) GradientLayer(nColor,nLayer); } void CMatrixSimulator::OnPopupChangescale1x1() { this->ReCalcLayout(1,TRUE); } void CMatrixSimulator::OnPopupChangescale2x2() { this->ReCalcLayout(2,TRUE); } void CMatrixSimulator::OnPopupChangescale3x3() { this->ReCalcLayout(3,TRUE); } void CMatrixSimulator::OnPopupChangescale4x4() { this->ReCalcLayout(4,TRUE); } void CMatrixSimulator::OnPopupStartscroll() { this->StartScroll(); } void CMatrixSimulator::OnPopupStopscroll() { this->StopScroll(); } void CMatrixSimulator::OnPopupLoadframesimage() { /////////////////////////////////////////////////////////////////// // OPEN FILE TO IMPORT /*****************************************************************/ CFileDialog dlg(TRUE,NULL,NULL,NULL,_T("Bitmap File(*.bmp)|*.bmp||")); if ( dlg.DoModal() == IDCANCEL ) { return ; // nothing selected } CString csFile = dlg.GetPathName(); #ifdef _UNICODE char szBuffer[MAX_PATH]; LPTSTR szData = (LPTSTR)csFile.GetBuffer(csFile.GetLength()); if (wcslen(szData)>=1024) szData[1024] = '\0'; int len = WideCharToMultiByte(CP_ACP,0,szData,wcslen(szData),szBuffer,sizeof(szBuffer),NULL,NULL); szBuffer[len] = '\0'; #endif LoadImage(csFile); RedrawWindow(); } void CMatrixSimulator::OnPopupLoadbackgroundimage() { /////////////////////////////////////////////////////////////////// // OPEN FILE TO IMPORT /*****************************************************************/ CFileDialog dlg(TRUE,NULL,NULL,NULL,_T("Bitmap File(*.bmp)|*.bmp||")); if ( dlg.DoModal() == IDCANCEL ) { return ; // nothing selected } CString csFile = dlg.GetPathName(); #ifdef _UNICODE char szBuffer[MAX_PATH]; LPTSTR szData = (LPTSTR)csFile.GetBuffer(csFile.GetLength()); if (wcslen(szData)>=1024) szData[1024] = '\0'; int len = WideCharToMultiByte(CP_ACP,0,szData,wcslen(szData),szBuffer,sizeof(szBuffer),NULL,NULL); szBuffer[len] = '\0'; #endif LoadBkGnd(csFile); RedrawWindow(); } #define FONT_HEIGHT 32 void CMatrixSimulator::CompressFont(LPCTSTR szFile) { BYTE dim[256][2]; BYTE buffer[FONT_HEIGHT*8*256]; memset(buffer,0x00,sizeof(buffer)); for (int i=0; i< 256; i++) { for (int x=0; x< FONT_HEIGHT; x++) { for (int y=0; y < FONT_HEIGHT; y++) { if (char_map[i].pdata[y][x]) buffer[y + (x/8)*FONT_HEIGHT + i*FONT_HEIGHT*FONT_HEIGHT/8] |= 1<<(x%8); else buffer[y + (x/8)*FONT_HEIGHT + i*FONT_HEIGHT*FONT_HEIGHT/8] &= ~(1<<(x%8)); } } dim[i][0] = char_map[i].heigth; dim[i][1] = char_map[i].width ; } CFile file(szFile,CFile::modeCreate|CFile::modeWrite); file.WriteHuge(buffer,sizeof(buffer)); file.SeekToBegin(); file.Write(dim,sizeof(dim)); file.Close(); } void CMatrixSimulator::DecompressFont(LPCTSTR szFile) { BYTE dim[256][2]; BYTE buffer[FONT_HEIGHT*8*256]; memset(buffer,0x00,sizeof(buffer)); CFile file(szFile,CFile::modeRead); file.ReadHuge(buffer,sizeof(buffer)); file.SeekToBegin(); file.Read(dim,sizeof(dim)); file.Close(); for (int i=0; i< 256; i++) { for (int x=0; x< FONT_HEIGHT; x++) { for (int y=0; y < FONT_HEIGHT; y++) { if (buffer[y + (x/8)*FONT_HEIGHT + i*FONT_HEIGHT*FONT_HEIGHT/8] & (1<<(x%8))) char_map[i].pdata[y][x] = 1; else char_map[i].pdata[y][x] = 0; } } char_map[i].heigth = dim[i][0]; char_map[i].width = dim[i][1]; } } int CMatrixSimulator::GetCharWidthBuffer(PBYTE pBuffer) { if (m_nTextLength > 256) m_nTextLength = 256; memcpy(pBuffer,m_wCharWidth,m_nTextLength*sizeof(WORD)); return m_nTextLength; } int CMatrixSimulator::GetFontCharWidthBuffer(PBYTE pBuffer) { if (m_nFontTextLength > 256) m_nFontTextLength = 256; memcpy(pBuffer,m_wFontCharWidth[m_nCurrentLayer],m_nFontTextLength*sizeof(WORD)); return m_nFontTextLength; } void CMatrixSimulator::GradientLayer(int nColor, int nLayer) { PBYTE pBuffer = NULL; UINT cx = 0, length = 0; if (nLayer>=0) { cx = DATA_LENGTH; length = m_nTextLengthPixel[nLayer]; pBuffer = (__SCREEN_LAYER[nLayer] + m_cx); } else { cx = m_cx; length = m_cx; pBuffer = m_pStaticLine; } int color = nColor; int c[2] = {2,3}; if (color == 1) { c[0] = 2; c[1] = 3; } if (color == 2) { c[0] = 3; c[1] = 1; } if (color == 3) { c[0] = 1; c[1] = 2; } for (int x=0; x< 8; x++) { if (x >=0 && x <4) color = c[0]; if (x >=4 && x <8) color = c[1]; for (int y =0; y< (int)length; y++) { BYTE data = ChangeColor(color,pBuffer[y + cx*x]); pBuffer[y + cx*x] = (data & 0x33) | (pBuffer[y + cx*x]&(~0x33)); } } } void CMatrixSimulator::InitDefaultFont() { for (int i =0; i < LAYER_COUNT; i++) LoadFont(__FONT_BUFFER[i],sizeof(__FONT_BUFFER[i]),i); } void CMatrixSimulator::LoadFont() { LoadFont(__FONT_BUFFER[m_nCurrentLayer],sizeof(__FONT_BUFFER[m_nCurrentLayer]),m_nCurrentLayer); } void CMatrixSimulator::LoadFont(PBYTE pData,int nDataLength, int nLayer) { int cx = 0; char szText[512] = {' '}; CString csText = _T(" "); for (int c = 0; c< 256; c++) { CString csTemp = _T(""); csTemp.Format(_T("%c"),c); csText += csTemp; } #ifdef _UNICODE LPTSTR szData = (LPTSTR)csText.GetBuffer(csText.GetLength()); int length = WideCharToMultiByte(CP_ACP,0,szData,wcslen(szData),szText,sizeof(szText),NULL,NULL); szText[length] = '\0'; #endif int pos = 0, nPixel =0; m_nFontTextLength = strlen(szText); memset(pData,BLANK_STATE,nDataLength); pos += TextToMatrix(szText+pos,cx,nLayer); // 512 characters nPixel += cx; pData = MatrixToPixel(pData,cx,(nDataLength/DATA_LINE),3); m_nFontPixelLenght = nPixel; } PBYTE CMatrixSimulator::MatrixToPixel(PBYTE pData, int nPixelLenght, int nBufferLength, int nColor) { for (int z=0; z< 8 ; z+=2) { for (int y=0; y< 8 ; y++) { for (int x=0; x< nPixelLenght; x++) { if ((buffer)[x][(y + z*4)]==1) pData[x + (y)*nBufferLength] |= (nColor<<z); else if ((buffer)[x][(y + z*4)]==0) pData[x + (y)*nBufferLength] &= ~(nColor<<z); } } } return pData + nBufferLength*8 + nPixelLenght; } int CMatrixSimulator::TextToMatrix(const char *szText, int &cx, int nLayer) { int len = strlen(szText); m_wFontCharWidth[nLayer][0] = 0; memset(buffer,BLANK_STATE,2048*8*32); for (int i = 0; i< len; i++) { BYTE sz = BYTE(szText[i]); for (int x = 0; x < char_map[sz].width; x++) { for (int y = 0; y < char_map[sz].heigth; y++) { buffer[x + cx][y] = char_map[sz].pdata[x][y]; } } cx+=char_map[sz].width; m_wFontCharWidth[nLayer][i + 1] = cx; if (cx > 2048*8) break; // cut off too long text } return int(i); } int CMatrixSimulator::GetFontBuffer(PBYTE *pBuffer) { *pBuffer = __SCREEN_LAYER[m_nCurrentLayer]; memcpy(*pBuffer,__FONT_BUFFER[m_nCurrentLayer],DATA_LINE*DATA_LENGTH); MoveText(0,m_szTextPos[m_nCurrentLayer].cy,m_nCurrentLayer,FALSE); return m_nFontPixelLenght; } void CMatrixSimulator::ShowClock(const char *szText) { TextFromFont(szText,3,TRUE,&m_pClock,CLOCK_LENGTH); } int CMatrixSimulator::TextFromFont(const char *szText, int nColor, BOOL bGradient, PBYTE *pBuffer, UINT nLenght) { int pos = 0; int len = strlen(szText); BYTE mask = 0x00; BYTE mask_clr[2] = {0x00}; switch (nColor) { case 0: mask = 0xFF; // BLANK mask_clr[0] = 0xFF; mask_clr[1] = 0xFF; break; case 1: mask = 0xAA; // RED RRRR mask_clr[0] = 0x99; // GREEN RGRG mask_clr[1] = 0x88; // YELLOW RYRY break; case 2: mask = 0x55; // GREEN GGGG mask_clr[0] = 0x44; // YELLOW GYGY mask_clr[1] = 0x66; // RED GRGR break; case 3: mask = 0x00; // YELLOW YYYY mask_clr[0] = 0x22; // RED YRYR mask_clr[1] = 0x11; // GREEN YGYG break; default: break; } for (int i=0; i< len; i++) { BYTE c = szText[i]; if (c >255) c =255; int nWidth = m_wFontCharWidth[m_nCurrentLayer][c+1] - m_wFontCharWidth[m_nCurrentLayer][c]; if (pos + nWidth > int(nLenght)) break; for (int y=0; y< 8 ; y++) { if (bGradient) { if (y >=0 && y <4) mask = mask_clr[0]; if (y >=4 && y <8) mask = mask_clr[1]; } for (int x=0; x< nWidth; x++) { (*pBuffer)[x + pos + y*nLenght] = (~mask) & __FONT_BUFFER[m_nCurrentLayer][x + m_wFontCharWidth[m_nCurrentLayer][c] + y*DATA_LENGTH]; } } pos += nWidth; } return pos; } void CMatrixSimulator::SaveWorkspace(CFile &file) { file.Write(&m_szBkPos.cx,sizeof(m_szBkPos.cx)); file.Write(&m_szBkPos.cy,sizeof(m_szBkPos.cy)); file.Write(&m_cx,sizeof(m_cx)); file.Write(&m_cy,sizeof(m_cy)); file.Write(m_pStaticLine,m_cx*8); file.Write(&m_bLoadBkgndImgs,sizeof(m_bLoadBkgndImgs)); file.Write(&m_nCurrentLayer,sizeof(m_nCurrentLayer)); file.Write(m_wCharWidth,sizeof(m_wCharWidth)); file.Write(&m_nFontPixelLenght,sizeof(m_nFontPixelLenght)); file.Write(&m_nTextLength,sizeof(m_nTextLength)); file.Write(&m_nFontTextLength,sizeof(m_nFontTextLength)); for(int i=0; i< 4; i++){ file.Write(&m_bLoadImage[i],sizeof(m_bLoadImage[i])); file.Write(&m_szTextPos[i].cx,sizeof(m_szTextPos[i].cx)); file.Write(&m_szTextPos[i].cy,sizeof(m_szTextPos[i].cy)); file.Write((LPVOID)__SCREEN_LAYER[i],sizeof(__SCREEN_LAYER[i])); file.Write((LPVOID)__FONT_BUFFER[i],sizeof(__FONT_BUFFER[i])); file.Write(m_wFontCharWidth[i],sizeof(m_wFontCharWidth[i])); file.Write(&m_nTextLengthPixel[i],sizeof(m_nTextLengthPixel[i])); } } void CMatrixSimulator::LoadWorkspace(CFile &file) { file.Read(&m_szBkPos.cx,sizeof(m_szBkPos.cx)); file.Read(&m_szBkPos.cy,sizeof(m_szBkPos.cy)); file.Read(&m_cx,sizeof(m_cx)); file.Read(&m_cy,sizeof(m_cy)); file.Read(m_pStaticLine,m_cx*8); file.Read(&m_bLoadBkgndImgs,sizeof(m_bLoadBkgndImgs)); file.Read(&m_nCurrentLayer,sizeof(m_nCurrentLayer)); file.Read(m_wCharWidth,sizeof(m_wCharWidth)); file.Read(&m_nFontPixelLenght,sizeof(m_nFontPixelLenght)); file.Read(&m_nTextLength,sizeof(m_nTextLength)); file.Read(&m_nFontTextLength,sizeof(m_nFontTextLength)); for(int i=0; i< 4; i++){ file.Read(&m_bLoadImage[i],sizeof(m_bLoadImage[i])); file.Read(&m_szTextPos[i].cx,sizeof(m_szTextPos[i].cx)); file.Read(&m_szTextPos[i].cy,sizeof(m_szTextPos[i].cy)); file.Read((LPVOID)__SCREEN_LAYER[i],sizeof(__SCREEN_LAYER[i])); file.Read((LPVOID)__FONT_BUFFER[i],sizeof(__FONT_BUFFER[i])); file.Read(m_wFontCharWidth[i],sizeof(m_wFontCharWidth[i])); file.Read(&m_nTextLengthPixel[i],sizeof(m_nTextLengthPixel[i])); } m_pStart = m_pOrigin + m_cx; m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE; } void CMatrixSimulator::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { m_ptPosition.y = -int(nPos); m_bHitScroll = TRUE; SetWindowPos(NULL,m_ptPosition.x,m_ptPosition.y,0,0,SWP_NOSIZE|SWP_NOREDRAW); this->DisplayFrame(m_pDCMem,TRUE); } void CMatrixSimulator::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { m_ptPosition.x = -int(nPos); m_bHitScroll = TRUE; SetWindowPos(NULL,m_ptPosition.x,m_ptPosition.y,0,0,SWP_NOSIZE|SWP_NOREDRAW); this->DisplayFrame(m_pDCMem,TRUE); }
26.040323
146
0.61598
cuongquay
86baf412b42932124acf064931e68fa6638e9078
1,202
cpp
C++
Week13/701.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
101
2021-02-26T14:32:37.000Z
2022-03-16T18:46:37.000Z
Week13/701.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
null
null
null
Week13/701.cpp
bobsingh149/LeetCode
293ed4931960bf5b9a3d5c4331ba4dfddccfcd55
[ "MIT" ]
30
2021-03-09T05:16:48.000Z
2022-03-16T21:16:33.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void get_data(vector<int> &contain, TreeNode* root){ if(root==NULL){ return; } get_data(contain, root->left); contain.push_back(root->val); get_data(contain, root->right); } TreeNode* create(vector<int> &contain, int start, int end){ if(start>end){ return NULL; } int mid=(start+end)/2; struct TreeNode* a= new TreeNode(contain[mid]); a->left=create(contain, start, mid-1); a->right=create(contain,mid+1, end); return a; } TreeNode* insertIntoBST(TreeNode* root, int val) { vector<int> contain; get_data(contain, root); contain.push_back(val); sort(contain.begin(), contain.end()); return create(contain, 0, contain.size()-1); } };
30.05
93
0.563228
bobsingh149
86bdf01183e05b00bb2f0561b71eb902f4cbbd20
709
cpp
C++
C/C1433.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
C/C1433.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
C/C1433.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main(){ int max = -1,t,n,indx; cin>>t; while(t--){ cin>>n; vector<int> v(n); max = -1; indx = -1; for(int i=0;i<n;i++){ cin>>v[i]; if(max < v[i]){ max = v[i]; } } for(int i=0;i<n;i++){ if(v[i] == max){ if(i > 0 && v[i - 1] < max){ indx = i; break; }else if(i < n - 1 && v[i + 1] < max){ indx = i; break; } } } cout<<(indx == -1 ? -1: indx + 1)<<endl; } }
22.870968
54
0.294781
Darknez07
86c12c8abab5a921e7fc00b8151a64ee1103a5ec
2,491
hpp
C++
include/scapin/fft_helper.hpp
sbrisard/gollum
25d5b9aea63a8f2812c4b41850450fcbead64da7
[ "BSD-3-Clause" ]
null
null
null
include/scapin/fft_helper.hpp
sbrisard/gollum
25d5b9aea63a8f2812c4b41850450fcbead64da7
[ "BSD-3-Clause" ]
4
2020-09-24T07:32:21.000Z
2020-12-01T08:06:00.000Z
include/scapin/fft_helper.hpp
sbrisard/gollum
25d5b9aea63a8f2812c4b41850450fcbead64da7
[ "BSD-3-Clause" ]
1
2020-02-02T18:05:15.000Z
2020-02-02T18:05:15.000Z
/** * @file fft_utils.h * * @brief Helper functions to work with discrete Fourier transforms. * * This module is heavily inspired by the `numpy.fft.helper` module, see * * <https://docs.scipy.org/doc/numpy/reference/routines.fft.html#helper-routines> * */ #pragma once #include <cmath> #include <numbers> #include "core.hpp" namespace fft_helper { /** * Return the Discrete Fourier Transform sample frequencies. * * The returned float array `freq` contains the frequency bin centers in cycles * per unit of the sample spacing (with zero at the start). For instance, if the * sample spacing is in seconds, then the frequency unit is cycles/second. * * Given a window length `n` and a sample spacing `d` * * f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d * n) if n is even * f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d * n) if n is odd * * If `freq == nullptr`, then a `new double[n]` array is allocated and * returned. Otherwise, `freq` must be a preallocated `double[n]` array, which * is modified in place and returned. */ DllExport double *fftfreq(int n, double d, double *freq) { if (freq == nullptr) { freq = new double[n]; } int const m = n / 2; int const rem = n % 2; double const f = 1. / (d * n); for (int i = 0; i < m + rem; i++) { freq[i] = f * i; } for (int i = m + rem; i < n; i++) { freq[i] = -f * (n - i); } return freq; } /** * Return the Discrete Fourier Transform sample wavenumbers. * * The returned float array `k` contains the wavenumbers bin centers in radians * per unit of the L (with zero at the start). For instance, if the * sample L is in seconds, then the frequency unit is radians/second. * * Given a window length `n` and the sample `L` * * k = [0, 1, ..., n/2-1, -n/2, ..., -1] * Δk if n is even * k = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] * Δk if n is odd * * where `Δk = 2π / (n * L)`. * * If `k == nullptr`, then a `new double[n]` array is allocated and * returned. Otherwise, `k` must be a preallocated `double[n]` array, which * is modified in place and returned. */ DllExport double *fftwavnum(int n, double L, double *k) { if (k == nullptr) { k = new double[n]; } int const m = n / 2; int const rem = n % 2; double const delta_k = 2 * std::numbers::pi / (n * L); for (int i = 0; i < m + rem; i++) { k[i] = delta_k * i; } for (int i = m + rem; i < n; i++) { k[i] = -delta_k * (n - i); } return k; } } // namespace fft_helper
29.305882
81
0.59173
sbrisard
86c15fbcaa76966acfcaf38e56429152a80c7d74
1,992
cpp
C++
gym/102829/J.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
1
2021-07-16T19:59:39.000Z
2021-07-16T19:59:39.000Z
gym/102829/J.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
gym/102829/J.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <random> #include <chrono> using namespace std; using namespace __gnu_pbds; #define endl '\n' typedef long long ll; typedef pair<int, int> pii; // typedef tree<int, null_type,less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // template<typename T> // static T randint(T lo, T hi){ // return uniform_int_distribution<T>(lo, hi)(rng); // } const int maxn = 500 + 5; int pi[maxn * maxn], idx[maxn][maxn], n; ll mn[maxn * maxn], sz[maxn * maxn], a[maxn][maxn]; ll ans = 0, cnt = 0; bool valid(int x, int y){ return x >= 0 && x < n && y >= 0 && y < n; } int root(int x){ return pi[x] == x ? x : root(pi[x]); } void merge(int a, int b){ a = root(a), b = root(b); if(a == b) return; if(sz[a] > sz[b]) swap(a, b); sz[b] += sz[a]; mn[b] = min(mn[b], mn[a]); pi[a] = b; ll val = mn[b] * sz[b]; if(val > ans || (val == ans && sz[b] > cnt)){ ans = val; cnt = sz[b]; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); // freopen("settling.in", "r", stdin); // freopen("settling.out", "w", stdout); cin >> n; int pos = 0; vector<pair<ll, pii>> spots; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++){ cin >> a[i][j]; idx[i][j] = pos; sz[pos] = 1; mn[pos] = a[i][j]; pi[pos] = pos; pos++; spots.push_back({a[i][j], {i, j}}); } vector<int> dx = {1, -1, 0, 0}; vector<int> dy = {0, 0, 1, -1}; sort(spots.rbegin(), spots.rend()); for(auto &p : spots){ ll val = p.first; int x = p.second.first; int y = p.second.second; if(val > ans || (val == ans && 1 > cnt)){ ans = val; cnt = 1; } for(int i = 0; i < 4; i++){ int nx = x + dx[i]; int ny = y + dy[i]; if(valid(nx, ny) && a[nx][ny] >= val) merge(idx[x][y], idx[nx][ny]); } } cout << ans << " " << cnt << endl; return 0; }
19.339806
102
0.545683
albexl
f866d8ef182572b70dd423abdfcad0fbb73e0d0d
2,077
cc
C++
mod/test/case/wrd/syntax/commentTest.cc
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
1
2019-02-02T07:07:32.000Z
2019-02-02T07:07:32.000Z
mod/test/case/wrd/syntax/commentTest.cc
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
25
2016-09-23T16:36:19.000Z
2019-02-12T14:14:32.000Z
mod/test/case/wrd/syntax/commentTest.cc
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
null
null
null
#include "../../../wrdSyntaxTest.hpp" using namespace wrd; using namespace std; namespace { struct commentTest : public wrdSyntaxTest {}; } TEST_F(commentTest, singleLineComment) { // control group. make().parse(R"SRC( age int // age is age main() int // main is also a main return 0 )SRC").shouldVerified(true); scope& owns = (scope&) (((scopes&) getSlot().subs()).getContainer()); scope& shares = (scope&) (((scopes&) getSubPack().subs()).getNext().getContainer()); ASSERT_FALSE(nul(shares)); ASSERT_FALSE(nul(owns)); ASSERT_EQ(owns.len(), 1); // 1 for age ASSERT_EQ(shares.len(), 2); // 1 for main() 1 for @ctor } TEST_F(commentTest, multiLineComment) { // control group. make().parse(R"SRC( age int /* age is age main() int */ main() flt return 2.5 )SRC").shouldVerified(true); scope& owns = (scope&) (((scopes&) getSlot().subs()).getContainer()); scope& shares = (scope&) (((scopes&) getSubPack().subs()).getNext().getContainer()); ASSERT_FALSE(nul(shares)); ASSERT_FALSE(nul(owns)); ASSERT_EQ(owns.len(), 1); // 1 for age ASSERT_EQ(shares.len(), 2); // 1 for main() 1 for @ctor } TEST_F(commentTest, multiLineComment2) { // control group. make().parse(R"SRC( age /* age is age main() int sdfas */int main() void return )SRC").shouldVerified(true); scope& owns = (scope&) (((scopes&) getSlot().subs()).getContainer()); scope& shares = (scope&) (((scopes&) getSubPack().subs()).getNext().getContainer()); ASSERT_FALSE(nul(shares)); ASSERT_FALSE(nul(owns)); ASSERT_EQ(owns.len(), 1); // 1 for age ASSERT_EQ(shares.len(), 2); // 1 for main() 1 for @ctor } TEST_F(commentTest, multiLineComment3) { // control group. make().parse(R"SRC( age int /* age is age main() int sdfas*/main() int return 33 )SRC").shouldParsed(false); /* above case is same to, * * age int main() bool * return false */ }
28.452055
88
0.584015
kniz
f86b78dd5854f0da41a656d457189bd8a83d0826
3,318
hpp
C++
mlir/include/mlir-extensions/analysis/memory_ssa.hpp
nbpatel/mlir-extensions
1270a2550694a53a0c70fd5b17d518eef133802b
[ "Apache-2.0" ]
28
2021-08-10T12:07:31.000Z
2022-03-13T10:54:40.000Z
mlir/include/mlir-extensions/analysis/memory_ssa.hpp
nbpatel/mlir-extensions
1270a2550694a53a0c70fd5b17d518eef133802b
[ "Apache-2.0" ]
21
2021-09-28T12:58:22.000Z
2022-03-25T21:08:56.000Z
mlir/include/mlir-extensions/analysis/memory_ssa.hpp
nbpatel/mlir-extensions
1270a2550694a53a0c70fd5b17d518eef133802b
[ "Apache-2.0" ]
6
2021-08-23T16:54:40.000Z
2022-03-11T23:43:56.000Z
// Copyright 2021 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <iterator> #include <llvm/ADT/ArrayRef.h> #include <llvm/ADT/DenseMap.h> #include <llvm/ADT/Optional.h> #include <llvm/ADT/simple_ilist.h> #include <llvm/Support/Allocator.h> namespace mlir { struct LogicalResult; class Operation; class Region; } // namespace mlir namespace plier { class MemorySSA { public: enum class NodeType { Root, Def, Use, Phi, Term }; struct Node; MemorySSA() = default; MemorySSA(const MemorySSA &) = delete; MemorySSA(MemorySSA &&) = default; MemorySSA &operator=(const MemorySSA &) = delete; MemorySSA &operator=(MemorySSA &&) = default; Node *createDef(mlir::Operation *op, Node *arg); Node *createUse(mlir::Operation *op, Node *arg); Node *createPhi(mlir::Operation *op, llvm::ArrayRef<Node *> args); void eraseNode(Node *node); NodeType getNodeType(Node *node) const; mlir::Operation *getNodeOperation(Node *node) const; Node *getNodeDef(Node *node) const; llvm::SmallVector<Node *> getUsers(Node *node); Node *getRoot(); Node *getTerm(); Node *getNode(mlir::Operation *op) const; struct NodesIterator { using iterator_category = std::bidirectional_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = Node; using pointer = value_type *; using reference = value_type &; using internal_iterator = llvm::simple_ilist<Node>::iterator; NodesIterator(internal_iterator iter); NodesIterator(const NodesIterator &) = default; NodesIterator(NodesIterator &&) = default; NodesIterator &operator=(const NodesIterator &) = default; NodesIterator &operator=(NodesIterator &&) = default; bool operator==(const NodesIterator &rhs) const { return iterator == rhs.iterator; } bool operator!=(const NodesIterator &rhs) const { return iterator != rhs.iterator; } NodesIterator &operator++(); NodesIterator operator++(int); NodesIterator &operator--(); NodesIterator operator--(int); reference operator*(); pointer operator->(); private: internal_iterator iterator; }; llvm::iterator_range<NodesIterator> getNodes(); void print(llvm::raw_ostream &os); void print(Node *node, llvm::raw_ostream &os); mlir::LogicalResult optimizeUses( llvm::function_ref<bool(mlir::Operation *, mlir::Operation *)> mayAlias); private: Node *root = nullptr; Node *term = nullptr; llvm::DenseMap<mlir::Operation *, Node *> nodesMap; llvm::BumpPtrAllocator allocator; llvm::simple_ilist<Node> nodes; Node *createNode(mlir::Operation *op, NodeType type, llvm::ArrayRef<Node *> args); }; llvm::Optional<plier::MemorySSA> buildMemorySSA(mlir::Region &region); } // namespace plier
28.603448
79
0.705244
nbpatel
f873e81edc799f9a9101767be4c0c89189e11c1e
4,759
cpp
C++
core/src/GarbageCollector.cpp
Devronium/ConceptApplicationServer
c1fcb8de8d752f352485840aab13511dd1aa6a15
[ "BSD-2-Clause" ]
11
2016-01-24T18:53:36.000Z
2021-01-21T08:59:01.000Z
core/src/GarbageCollector.cpp
Devronium/ConceptApplicationServer
c1fcb8de8d752f352485840aab13511dd1aa6a15
[ "BSD-2-Clause" ]
1
2016-01-22T21:38:38.000Z
2016-01-30T17:25:01.000Z
core/src/GarbageCollector.cpp
Devronium/ConceptApplicationServer
c1fcb8de8d752f352485840aab13511dd1aa6a15
[ "BSD-2-Clause" ]
null
null
null
#include "GarbageCollector.h" #include "CompiledClass.h" #include "ClassCode.h" #include "Array.h" #include "PIFAlizator.h" POOLED_IMPLEMENTATION(_GarbageElement) POOLED_IMPLEMENTATION(GarbageCollector) GarbageCollector::GarbageCollector() { BASE = 0; } void GarbageCollector::Call_All_Destructors(void *PIF) { #ifdef USE_HASHTABLE_GC if (BASE) { for (khint_t k = kh_begin(BASE); k != kh_end(BASE); ++k) { if (kh_exist(BASE, k)) { CompiledClass *ptr = (struct CompiledClass *)(uintptr_t)kh_key(BASE, k); if (CompiledClass_HasDestructor(ptr)) CompiledClass_Destroy(ptr, (PIFAlizator *)PIF); } } } #else GarbageElement *NODE = BASE; GarbageElement *NODE2 = 0; while (NODE) { NODE2 = NODE->NEXT; CompiledClass *ptr = (struct CompiledClass *)NODE->DATA; if (CompiledClass_HasDestructor(ptr)) { CompiledClass_Destroy(PIF); } NODE = NODE2; } #endif } void GarbageCollector::EndOfExecution_SayBye_Objects() { #ifdef USE_HASHTABLE_GC if (BASE) { khash_t (int64hashtable) *BASE2 = BASE; BASE = 0; for (khint_t k = kh_begin(BASE2); k != kh_end(BASE2); ++k) { if (kh_exist(BASE2, k)) { CompiledClass *ptr = (struct CompiledClass *)(uintptr_t)kh_key(BASE2, k); if (ptr) { ptr->LINKS = -1; if (ptr->_CONTEXT) { FAST_FREE(GET_PIF(ptr), ptr->_CONTEXT); ptr->_CONTEXT = NULL; } delete_CompiledClass(ptr); } } } kh_destroy(int64hashtable, BASE2); } #else GarbageElement *NODE = BASE; GarbageElement *NODE2 = 0; // to prevent recursive re-execution BASE = 0; while (NODE) { NODE2 = NODE->NEXT; CompiledClass *ptr = (struct CompiledClass *)NODE->DATA; free(NODE); NODE = NODE2; ptr->LINKS = -1; if (ptr->_CONTEXT) { FAST_FREE(ptr->_CONTEXT); ptr->_CONTEXT = NULL; } delete_CompiledClass(ptr); } #endif } void GarbageCollector::EndOfExecution_SayBye_Arrays() { #ifdef USE_HASHTABLE_GC if (BASE) { khash_t (int64hashtable) *BASE2 = BASE; BASE = 0; for (khint_t k = kh_begin(BASE2); k != kh_end(BASE2); ++k) { if (kh_exist(BASE2, k)) { Array *ptr = (struct Array *)(uintptr_t)kh_key(BASE2, k); if (ptr) { ptr->LINKS = -1; delete_Array(ptr); } } } kh_destroy(int64hashtable, BASE2); } #else GarbageElement *NODE = BASE; GarbageElement *NODE2 = 0; BASE = 0; while (NODE) { NODE2 = NODE->NEXT; Array *ptr = (struct Array *)NODE->DATA; free(NODE); NODE = NODE2; ptr->LINKS = -1; delete_Array(ptr); } #endif } void GarbageCollector::EndOfExecution_SayBye_Variables() { #ifdef USE_HASHTABLE_GC if (BASE) { khash_t (int64hashtable) *BASE2 = BASE; BASE = 0; for (khint_t k = kh_begin(BASE2); k != kh_end(BASE2); ++k) { if (kh_exist(BASE2, k)) { VariableDATA *ptr = (VariableDATA *)(uintptr_t)kh_key(BASE2, k); if (ptr) { if (ptr->CLASS_DATA) { if (ptr->TYPE == VARIABLE_STRING) plainstring_delete((struct plainstring *)ptr->CLASS_DATA); else if (ptr->TYPE == VARIABLE_DELEGATE) free_Delegate(ptr->CLASS_DATA); ptr->CLASS_DATA = NULL; } VAR_FREE(ptr); } } } kh_destroy(int64hashtable, BASE2); } #else GarbageElement *NODE = BASE; GarbageElement *NODE2 = 0; BASE = 0; while (NODE) { NODE2 = NODE->NEXT; VariableDATA *ptr = (VariableDATA *)NODE->DATA; free(NODE); NODE = NODE2; if (ptr) VAR_FREE(ptr); } #endif } GarbageCollector::~GarbageCollector() { #ifdef USE_HASHTABLE_GC if (BASE) { kh_destroy(int64hashtable, BASE); BASE = 0; } #else GarbageElement *NODE = BASE; GarbageElement *NODE2 = 0; while (NODE) { NODE2 = NODE->NEXT; free(NODE); NODE = NODE2; } #endif }
27.350575
90
0.499895
Devronium
f875187c4caccdffd3fe1f218c5f5e72d6a48cb8
1,091
cpp
C++
c3dEngine/c3dEngine/core/c3dModel.cpp
wantnon2/superSingleCell-c3dEngine
512f99c649f1809bf63ef0e3e02342648372e2ce
[ "MIT" ]
12
2015-02-12T10:54:20.000Z
2019-02-18T22:15:53.000Z
c3dEngine/c3dEngine/core/c3dModel.cpp
wantnon2/superSingleCell-c3dEngine
512f99c649f1809bf63ef0e3e02342648372e2ce
[ "MIT" ]
null
null
null
c3dEngine/c3dEngine/core/c3dModel.cpp
wantnon2/superSingleCell-c3dEngine
512f99c649f1809bf63ef0e3e02342648372e2ce
[ "MIT" ]
11
2015-02-10T04:02:14.000Z
2021-12-08T09:12:10.000Z
// // c3dActor.cpp // HelloOpenGL // // Created by wantnon (yang chao) on 12-12-20. // // #include "c3dModel.h" void Cc3dModel::addMesh(Cc3dMesh*mesh){ assert(mesh); m_meshList.push_back(mesh); // mesh->setName("?"); this->addChild(mesh); } void Cc3dModel::submitVertex(GLenum usage){ int nMesh=(int)getMeshCount(); for(int i=0;i<nMesh;i++){ Cc3dMesh*mesh=m_meshList[i]; int nSubMesh=(int)mesh->getSubMeshCount(); for(int j=0;j<nSubMesh;j++){ Cc3dSubMesh*psubMesh=mesh->getSubMeshByIndex(j); psubMesh->getIndexVBO()->submitVertex(psubMesh->getSubMeshData()->vlist, usage); } } } void Cc3dModel::submitIndex(GLenum usage){ int nMesh=(int)getMeshCount(); for(int i=0;i<nMesh;i++){ Cc3dMesh*mesh=m_meshList[i]; int nSubMesh=(int)mesh->getSubMeshCount(); for(int j=0;j<nSubMesh;j++){ Cc3dSubMesh*psubMesh=mesh->getSubMeshByIndex(j); psubMesh->getIndexVBO()->submitIndex(psubMesh->getSubMeshData()->IDtriList, usage); } } }
25.372093
95
0.612282
wantnon2
f8769575f228c445245a6a0385378c2333da12ac
658
cpp
C++
test/math/log2.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
test/math/log2.cpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
test/math/log2.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/catch/begin.hpp> #include <fcppt/catch/end.hpp> #include <fcppt/math/log2.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <fcppt/config/external_end.hpp> FCPPT_CATCH_BEGIN TEST_CASE("math::log2", "[math]") { CHECK(fcppt::math::log2(1U) == 0U); CHECK(fcppt::math::log2(2U) == 1U); CHECK(fcppt::math::log2(4U) == 2U); CHECK(fcppt::math::log2(8U) == 3U); } FCPPT_CATCH_END
24.37037
61
0.683891
freundlich
f87e89d1064fba1d2721358c40ba63553b595437
2,229
cpp
C++
src/core/logic.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
14
2018-08-08T19:02:21.000Z
2022-01-07T14:42:43.000Z
src/core/logic.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
null
null
null
src/core/logic.cpp
JackWolfard/cash
a646c0b94d075fa424a93904b7499a0dee90ac89
[ "BSD-3-Clause" ]
3
2020-04-20T20:58:34.000Z
2021-11-23T14:50:14.000Z
#include "logic.h" #include "proxyimpl.h" #include "context.h" using namespace ch::internal; logic_buffer::logic_buffer(uint32_t size, const std::string& name, const source_location& sloc) : lnode(ctx_curr()->create_node<proxyimpl>(size, name, sloc)) {} logic_buffer::logic_buffer(uint32_t size, const logic_buffer& src, uint32_t src_offset, const std::string& name, const source_location& sloc) : lnode(ctx_curr()->create_node<refimpl>( src.impl(), src_offset, size, ((!src.name().empty() && !name.empty()) ? (src.name() + '.' + name) : ""), sloc)) {} const logic_buffer& logic_buffer::source() const { assert(impl_); return reinterpret_cast<const logic_buffer&>(impl_->src(0)); } void logic_buffer::write(uint32_t dst_offset, const lnode& src, uint32_t src_offset, uint32_t length) { assert(impl_); this->ensure_proxy(); reinterpret_cast<proxyimpl*>(impl_)->write(dst_offset, src.impl(), src_offset, length, impl_->sloc()); } lnodeimpl* logic_buffer::clone(const std::string& name, const source_location& sloc) const { assert(impl_); this->ensure_proxy(); auto node = reinterpret_cast<proxyimpl*>(impl_)->source(0, impl_->size(), name, sloc); if (node != impl_->src(0).impl()) return node; return ctx_curr()->create_node<proxyimpl>(node, name, sloc); } lnodeimpl* logic_buffer::sliceref(size_t size, size_t start, const std::string& name, const source_location& sloc) const { const_cast<logic_buffer*>(this)->ensure_proxy(); return ctx_curr()->create_node<refimpl>(impl_, start, size, name, sloc); } void logic_buffer::ensure_proxy() const { auto impl = impl_; if (type_proxy == impl->type()) return; auto proxy = ctx_curr()->create_node<proxyimpl>(impl->size(), "", impl->sloc()); impl->replace_uses(proxy); proxy->write(0, impl, 0, impl->size(), impl->sloc()); }
33.268657
104
0.577389
JackWolfard
f87e8b380cf1a015a1f191be94654d611ac51251
38,559
cpp
C++
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/src/node.cpp
kmiya/AutowareArchitectureProposal.iv
386b52c9cc90f4535ad833014f2f9500f0e64ccf
[ "Apache-2.0" ]
null
null
null
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/src/node.cpp
kmiya/AutowareArchitectureProposal.iv
386b52c9cc90f4535ad833014f2f9500f0e64ccf
[ "Apache-2.0" ]
null
null
null
planning/scenario_planning/lane_driving/motion_planning/obstacle_avoidance_planner/src/node.cpp
kmiya/AutowareArchitectureProposal.iv
386b52c9cc90f4535ad833014f2f9500f0e64ccf
[ "Apache-2.0" ]
1
2021-07-20T09:38:30.000Z
2021-07-20T09:38:30.000Z
// Copyright 2020 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "obstacle_avoidance_planner/node.hpp" #include <algorithm> #include <chrono> #include <limits> #include <memory> #include <string> #include <vector> #include "autoware_perception_msgs/msg/dynamic_object.hpp" #include "autoware_perception_msgs/msg/dynamic_object_array.hpp" #include "autoware_planning_msgs/msg/path.hpp" #include "autoware_planning_msgs/msg/trajectory.hpp" #include "boost/optional.hpp" #include "geometry_msgs/msg/transform_stamped.hpp" #include "geometry_msgs/msg/twist_stamped.hpp" #include "obstacle_avoidance_planner/debug.hpp" #include "obstacle_avoidance_planner/eb_path_optimizer.hpp" #include "obstacle_avoidance_planner/mpt_optimizer.hpp" #include "obstacle_avoidance_planner/process_cv.hpp" #include "obstacle_avoidance_planner/util.hpp" #include "opencv2/core.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp/time.hpp" #include "std_msgs/msg/bool.hpp" #include "tf2/utils.h" #include "tf2_ros/transform_listener.h" #include "vehicle_info_util/vehicle_info.hpp" #include "visualization_msgs/msg/marker_array.hpp" ObstacleAvoidancePlanner::ObstacleAvoidancePlanner() : Node("obstacle_avoidance_planner"), min_num_points_for_getting_yaw_(2) { rclcpp::Clock::SharedPtr clock = std::make_shared<rclcpp::Clock>(RCL_ROS_TIME); tf_buffer_ptr_ = std::make_unique<tf2_ros::Buffer>(clock); tf_listener_ptr_ = std::make_unique<tf2_ros::TransformListener>(*tf_buffer_ptr_); rclcpp::QoS durable_qos{1}; durable_qos.transient_local(); trajectory_pub_ = create_publisher<autoware_planning_msgs::msg::Trajectory>("~/output/path", 1); avoiding_traj_pub_ = create_publisher<autoware_planning_msgs::msg::Trajectory>( "/planning/scenario_planning/lane_driving/obstacle_avoidance_candidate_trajectory", durable_qos); debug_smoothed_points_pub_ = create_publisher<autoware_planning_msgs::msg::Trajectory>( "~/debug/smoothed_points", durable_qos); is_avoidance_possible_pub_ = create_publisher<autoware_planning_msgs::msg::IsAvoidancePossible>( "/planning/scenario_planning/lane_driving/obstacle_avoidance_ready", durable_qos); debug_markers_pub_ = create_publisher<visualization_msgs::msg::MarkerArray>("~/debug/marker", durable_qos); debug_clearance_map_pub_ = create_publisher<nav_msgs::msg::OccupancyGrid>("~/debug/clearance_map", durable_qos); debug_object_clearance_map_pub_ = create_publisher<nav_msgs::msg::OccupancyGrid>("~/debug/object_clearance_map", durable_qos); debug_area_with_objects_pub_ = create_publisher<nav_msgs::msg::OccupancyGrid>("~/debug/area_with_objects", durable_qos); path_sub_ = create_subscription<autoware_planning_msgs::msg::Path>( "~/input/path", rclcpp::QoS{1}, std::bind(&ObstacleAvoidancePlanner::pathCallback, this, std::placeholders::_1)); twist_sub_ = create_subscription<geometry_msgs::msg::TwistStamped>( "/localization/twist", rclcpp::QoS{1}, std::bind(&ObstacleAvoidancePlanner::twistCallback, this, std::placeholders::_1)); objects_sub_ = create_subscription<autoware_perception_msgs::msg::DynamicObjectArray>( "~/input/objects", rclcpp::QoS{10}, std::bind(&ObstacleAvoidancePlanner::objectsCallback, this, std::placeholders::_1)); is_avoidance_sub_ = create_subscription<autoware_planning_msgs::msg::EnableAvoidance>( "/planning/scenario_planning/lane_driving/obstacle_avoidance_approval", rclcpp::QoS{10}, std::bind(&ObstacleAvoidancePlanner::enableAvoidanceCallback, this, std::placeholders::_1)); is_publishing_area_with_objects_ = declare_parameter("is_publishing_area_with_objects", false); is_publishing_clearance_map_ = declare_parameter("is_publishing_clearance_map", false); is_showing_debug_info_ = declare_parameter("is_showing_debug_info", true); is_using_vehicle_config_ = declare_parameter("is_using_vehicle_config", false); is_stopping_if_outside_drivable_area_ = declare_parameter("is_stopping_if_outside_drivable_area", true); enable_avoidance_ = declare_parameter("enable_avoidance", true); qp_param_ = std::make_unique<QPParam>(); traj_param_ = std::make_unique<TrajectoryParam>(); constrain_param_ = std::make_unique<ConstrainParam>(); vehicle_param_ = std::make_unique<VehicleParam>(); mpt_param_ = std::make_unique<MPTParam>(); qp_param_->max_iteration = declare_parameter("qp_max_iteration", 10000); qp_param_->eps_abs = declare_parameter("qp_eps_abs", 1.0e-8); qp_param_->eps_rel = declare_parameter("qp_eps_rel", 1.0e-11); qp_param_->eps_abs_for_extending = declare_parameter("qp_eps_abs_for_extending", 1.0e-6); qp_param_->eps_rel_for_extending = declare_parameter("qp_eps_rel_for_extending", 1.0e-8); qp_param_->eps_abs_for_visualizing = declare_parameter("qp_eps_abs_for_visualizing", 1.0e-6); qp_param_->eps_rel_for_visualizing = declare_parameter("qp_eps_rel_for_visualizing", 1.0e-8); traj_param_->num_sampling_points = declare_parameter("num_sampling_points", 100); traj_param_->num_joint_buffer_points = declare_parameter("num_joint_buffer_points", 2); traj_param_->num_joint_buffer_points_for_extending = declare_parameter("num_joint_buffer_points_for_extending", 4); traj_param_->num_offset_for_begin_idx = declare_parameter("num_offset_for_begin_idx", 2); traj_param_->num_fix_points_for_extending = declare_parameter("num_fix_points_for_extending", 2); traj_param_->forward_fixing_mpt_distance = declare_parameter("forward_fixing_mpt_distance", 10); traj_param_->delta_arc_length_for_optimization = declare_parameter("delta_arc_length_for_optimization", 1.0); traj_param_->delta_arc_length_for_mpt_points = declare_parameter("delta_arc_length_for_mpt_points", 1.0); traj_param_->delta_arc_length_for_trajectory = declare_parameter("delta_arc_length_for_trajectory", 0.1); traj_param_->delta_dist_threshold_for_closest_point = declare_parameter("delta_dist_threshold_for_closest_point", 3.0); traj_param_->delta_yaw_threshold_for_closest_point = declare_parameter("delta_yaw_threshold_for_closest_point", 1.0); traj_param_->delta_yaw_threshold_for_straight = declare_parameter("delta_yaw_threshold_for_straight", 0.02); traj_param_->trajectory_length = declare_parameter("trajectory_length", 200); traj_param_->forward_fixing_distance = declare_parameter("forward_fixing_distance", 10.0); traj_param_->backward_fixing_distance = declare_parameter("backward_fixing_distance", 5.0); traj_param_->max_avoiding_ego_velocity_ms = declare_parameter("max_avoiding_ego_velocity_ms", 6.0); traj_param_->max_avoiding_objects_velocity_ms = declare_parameter("max_avoiding_objects_velocity_ms", 0.1); traj_param_->center_line_width = declare_parameter("center_line_width", 1.7); traj_param_->acceleration_for_non_deceleration_range = declare_parameter("acceleration_for_non_deceleration_range", 1.0); traj_param_->max_dist_for_extending_end_point = declare_parameter("max_dist_for_extending_end_point", 5.0); traj_param_->is_avoiding_unknown = declare_parameter("avoiding_object_type.unknown", true); traj_param_->is_avoiding_car = declare_parameter("avoiding_object_type.car", true); traj_param_->is_avoiding_truck = declare_parameter("avoiding_object_type.truck", true); traj_param_->is_avoiding_bus = declare_parameter("avoiding_object_type.bus", true); traj_param_->is_avoiding_bicycle = declare_parameter("avoiding_object_type.bicycle", true); traj_param_->is_avoiding_motorbike = declare_parameter("avoiding_object_type.motorbike", true); traj_param_->is_avoiding_pedestrian = declare_parameter("avoiding_object_type.pedestrian", true); traj_param_->is_avoiding_animal = declare_parameter("avoiding_object_type.animal", true); constrain_param_->is_getting_constraints_close2path_points = declare_parameter("is_getting_constraints_close2path_points", false); constrain_param_->clearance_for_straight_line = declare_parameter("clearance_for_straight_line", 0.05); constrain_param_->clearance_for_joint = declare_parameter("clearance_for_joint", 0.1); constrain_param_->range_for_extend_joint = declare_parameter("range_for_extend_joint", 1.6); constrain_param_->clearance_for_only_smoothing = declare_parameter("clearance_for_only_smoothing", 0.1); constrain_param_->clearance_from_object_for_straight = declare_parameter("clearance_from_object_for_straight", 10.0); constrain_param_->clearance_from_road = declare_parameter("clearance_from_road", 0.1); constrain_param_->clearance_from_object = declare_parameter("clearance_from_object", 0.6); constrain_param_->extra_desired_clearance_from_road = declare_parameter("extra_desired_clearance_from_road", 0.2); constrain_param_->min_object_clearance_for_joint = declare_parameter("min_object_clearance_for_joint", 3.2); constrain_param_->max_x_constrain_search_range = declare_parameter("max_x_constrain_search_range", 0.4); constrain_param_->coef_x_constrain_search_resolution = declare_parameter("coef_x_constrain_search_resolution", 1.0); constrain_param_->coef_y_constrain_search_resolution = declare_parameter("coef_y_constrain_search_resolution", 0.5); constrain_param_->keep_space_shape_x = declare_parameter("keep_space_shape_x", 3.0); constrain_param_->keep_space_shape_y = declare_parameter("keep_space_shape_y", 2.0); constrain_param_->max_lon_space_for_driveable_constraint = declare_parameter("max_lon_space_for_driveable_constraint", 0.5); constrain_param_->clearance_for_fixing = 0.0; min_delta_dist_for_replan_ = declare_parameter("min_delta_dist_for_replan", 5.0); min_delta_time_sec_for_replan_ = declare_parameter("min_delta_time_sec_for_replan", 1.0); distance_for_path_shape_change_detection_ = declare_parameter("distance_for_path_shape_change_detection", 2.0); // vehicle param vehicle_info_util::VehicleInfo vehicle_info = vehicle_info_util::VehicleInfo::create(*this); vehicle_param_->width = vehicle_info.vehicle_width_m_; vehicle_param_->length = vehicle_info.vehicle_length_m_; vehicle_param_->wheelbase = vehicle_info.wheel_base_m_; vehicle_param_->rear_overhang = vehicle_info.rear_overhang_m_; vehicle_param_->front_overhang = vehicle_info.front_overhang_m_; if (is_using_vehicle_config_) { double vehicle_width = vehicle_info.vehicle_width_m_; traj_param_->center_line_width = vehicle_width; constrain_param_->keep_space_shape_y = vehicle_width; } constrain_param_->min_object_clearance_for_deceleration = constrain_param_->clearance_from_object + constrain_param_->keep_space_shape_y * 0.5; double max_steer_deg = 0; max_steer_deg = declare_parameter("max_steer_deg", 30.0); vehicle_param_->max_steer_rad = max_steer_deg * M_PI / 180.0; vehicle_param_->steer_tau = declare_parameter("steer_tau", 0.1); // mpt param mpt_param_->is_hard_fixing_terminal_point = declare_parameter("is_hard_fixing_terminal_point", true); mpt_param_->num_curvature_sampling_points = declare_parameter("num_curvature_sampling_points", 5); mpt_param_->base_point_weight = declare_parameter("base_point_weight", 2000.0); mpt_param_->top_point_weight = declare_parameter("top_point_weight", 1000.0); mpt_param_->mid_point_weight = declare_parameter("mid_point_weight", 1000.0); mpt_param_->lat_error_weight = declare_parameter("lat_error_weight", 10.0); mpt_param_->yaw_error_weight = declare_parameter("yaw_error_weight", 0.0); mpt_param_->steer_input_weight = declare_parameter("steer_input_weight", 0.1); mpt_param_->steer_rate_weight = declare_parameter("steer_rate_weight", 100.0); mpt_param_->steer_acc_weight = declare_parameter("steer_acc_weight", 0.000001); mpt_param_->terminal_lat_error_weight = declare_parameter("terminal_lat_error_weight", 0.0); mpt_param_->terminal_yaw_error_weight = declare_parameter("terminal_yaw_error_weight", 100.0); mpt_param_->terminal_path_lat_error_weight = declare_parameter("terminal_path_lat_error_weight", 1000.0); mpt_param_->terminal_path_yaw_error_weight = declare_parameter("terminal_path_yaw_error_weight", 1000.0); mpt_param_->zero_ff_steer_angle = declare_parameter("zero_ff_steer_angle", 0.5); mpt_param_->clearance_from_road = vehicle_param_->width * 0.5 + constrain_param_->clearance_from_road + constrain_param_->extra_desired_clearance_from_road; mpt_param_->clearance_from_object = vehicle_param_->width * 0.5 + constrain_param_->clearance_from_object; mpt_param_->base_point_dist_from_base_link = 0; mpt_param_->top_point_dist_from_base_link = (vehicle_param_->length - vehicle_param_->rear_overhang); mpt_param_->mid_point_dist_from_base_link = (mpt_param_->base_point_dist_from_base_link + mpt_param_->top_point_dist_from_base_link) * 0.5; in_objects_ptr_ = std::make_unique<autoware_perception_msgs::msg::DynamicObjectArray>(); // set parameter callback set_param_res_ = this->add_on_set_parameters_callback( std::bind(&ObstacleAvoidancePlanner::paramCallback, this, std::placeholders::_1)); initialize(); } ObstacleAvoidancePlanner::~ObstacleAvoidancePlanner() {} rcl_interfaces::msg::SetParametersResult ObstacleAvoidancePlanner::paramCallback( const std::vector<rclcpp::Parameter> & parameters) { auto update_param = [&](const std::string & name, double & v) { auto it = std::find_if( parameters.cbegin(), parameters.cend(), [&name](const rclcpp::Parameter & parameter) {return parameter.get_name() == name;}); if (it != parameters.cend()) { v = it->as_double(); return true; } return false; }; // trajectory total/fixing length update_param("trajectory_length", traj_param_->trajectory_length); update_param("forward_fixing_distance", traj_param_->forward_fixing_distance); update_param("backward_fixing_distance", traj_param_->backward_fixing_distance); // clearance for unique points update_param("clearance_for_straight_line", constrain_param_->clearance_for_straight_line); update_param("clearance_for_joint", constrain_param_->clearance_for_joint); update_param("clearance_for_only_smoothing", constrain_param_->clearance_for_only_smoothing); update_param( "clearance_from_object_for_straight", constrain_param_->clearance_from_object_for_straight); // clearance(distance) when generating trajectory update_param("clearance_from_road", constrain_param_->clearance_from_road); update_param("clearance_from_object", constrain_param_->clearance_from_object); update_param("min_object_clearance_for_joint", constrain_param_->min_object_clearance_for_joint); update_param( "extra_desired_clearance_from_road", constrain_param_->extra_desired_clearance_from_road); // avoiding param update_param("max_avoiding_objects_velocity_ms", traj_param_->max_avoiding_objects_velocity_ms); update_param("max_avoiding_ego_velocity_ms", traj_param_->max_avoiding_ego_velocity_ms); update_param("center_line_width", traj_param_->center_line_width); update_param( "acceleration_for_non_deceleration_range", traj_param_->acceleration_for_non_deceleration_range); // mpt param update_param("base_point_weight", mpt_param_->base_point_weight); update_param("top_point_weight", mpt_param_->top_point_weight); update_param("mid_point_weight", mpt_param_->mid_point_weight); update_param("lat_error_weight", mpt_param_->lat_error_weight); update_param("yaw_error_weight", mpt_param_->yaw_error_weight); update_param("steer_input_weight", mpt_param_->steer_input_weight); update_param("steer_rate_weight", mpt_param_->steer_rate_weight); update_param("steer_acc_weight", mpt_param_->steer_acc_weight); rcl_interfaces::msg::SetParametersResult result; result.successful = true; result.reason = "success"; return result; } // ROS callback functions void ObstacleAvoidancePlanner::pathCallback(const autoware_planning_msgs::msg::Path::SharedPtr msg) { std::lock_guard<std::mutex> lock(mutex_); current_ego_pose_ptr_ = getCurrentEgoPose(); if ( msg->points.empty() || msg->drivable_area.data.empty() || !current_ego_pose_ptr_ || !current_twist_ptr_) { return; } autoware_planning_msgs::msg::Trajectory output_trajectory_msg = generateTrajectory(*msg); trajectory_pub_->publish(output_trajectory_msg); } void ObstacleAvoidancePlanner::twistCallback(const geometry_msgs::msg::TwistStamped::SharedPtr msg) { current_twist_ptr_ = std::make_unique<geometry_msgs::msg::TwistStamped>(*msg); } void ObstacleAvoidancePlanner::objectsCallback( const autoware_perception_msgs::msg::DynamicObjectArray::SharedPtr msg) { in_objects_ptr_ = std::make_unique<autoware_perception_msgs::msg::DynamicObjectArray>(*msg); } void ObstacleAvoidancePlanner::enableAvoidanceCallback( const autoware_planning_msgs::msg::EnableAvoidance::SharedPtr msg) { enable_avoidance_ = msg->enable_avoidance; } // End ROS callback functions autoware_planning_msgs::msg::Trajectory ObstacleAvoidancePlanner::generateTrajectory( const autoware_planning_msgs::msg::Path & path) { auto t_start = std::chrono::high_resolution_clock::now(); const auto traj_points = generateOptimizedTrajectory(*current_ego_pose_ptr_, path); const auto post_processed_traj = generatePostProcessedTrajectory(*current_ego_pose_ptr_, path.points, traj_points); autoware_planning_msgs::msg::Trajectory output; output.header = path.header; output.points = post_processed_traj; prev_path_points_ptr_ = std::make_unique<std::vector<autoware_planning_msgs::msg::PathPoint>>(path.points); auto t_end = std::chrono::high_resolution_clock::now(); float elapsed_ms = std::chrono::duration<float, std::milli>(t_end - t_start).count(); RCLCPP_INFO_EXPRESSION( get_logger(), is_showing_debug_info_, "Total time: = %f [ms]\n==========================", elapsed_ms); return output; } std::vector<autoware_planning_msgs::msg::TrajectoryPoint> ObstacleAvoidancePlanner::generateOptimizedTrajectory( const geometry_msgs::msg::Pose & ego_pose, const autoware_planning_msgs::msg::Path & path) { if (!needReplan( ego_pose, prev_ego_pose_ptr_, path.points, prev_replanned_time_ptr_, prev_path_points_ptr_, prev_trajectories_ptr_)) { return getPrevTrajectory(path.points); } prev_ego_pose_ptr_ = std::make_unique<geometry_msgs::msg::Pose>(ego_pose); prev_replanned_time_ptr_ = std::make_unique<rclcpp::Time>(this->now()); DebugData debug_data; const auto optional_trajs = eb_path_optimizer_ptr_->generateOptimizedTrajectory( enable_avoidance_, ego_pose, path, prev_trajectories_ptr_, in_objects_ptr_->objects, &debug_data); if (!optional_trajs) { RCLCPP_WARN_THROTTLE( get_logger(), *get_clock(), std::chrono::milliseconds(1000).count(), "[Avoidance] Optimization failed, passing previous trajectory"); const bool is_prev_traj = true; const auto prev_trajs_inside_area = calcTrajectoryInsideArea( getPrevTrajs(path.points), path.points, debug_data.clearance_map, path.drivable_area.info, &debug_data, is_prev_traj); prev_trajectories_ptr_ = std::make_unique<Trajectories>( makePrevTrajectories(*current_ego_pose_ptr_, path.points, prev_trajs_inside_area.get())); const auto prev_traj = util::concatTraj(prev_trajs_inside_area.get()); publishingDebugData(debug_data, path, prev_traj, *vehicle_param_); return prev_traj; } const auto trajs_inside_area = getTrajectoryInsideArea( optional_trajs.get(), path.points, debug_data.clearance_map, path.drivable_area.info, &debug_data); prev_trajectories_ptr_ = std::make_unique<Trajectories>( makePrevTrajectories(*current_ego_pose_ptr_, path.points, trajs_inside_area)); const auto optimized_trajectory = util::concatTraj(trajs_inside_area); publishingDebugData(debug_data, path, optimized_trajectory, *vehicle_param_); return optimized_trajectory; } void ObstacleAvoidancePlanner::initialize() { RCLCPP_WARN(get_logger(), "[ObstacleAvoidancePlanner] Resetting"); eb_path_optimizer_ptr_ = std::make_unique<EBPathOptimizer>( is_showing_debug_info_, *qp_param_, *traj_param_, *constrain_param_, *vehicle_param_, *mpt_param_); prev_path_points_ptr_ = nullptr; prev_trajectories_ptr_ = nullptr; } std::unique_ptr<geometry_msgs::msg::Pose> ObstacleAvoidancePlanner::getCurrentEgoPose() { geometry_msgs::msg::TransformStamped tf_current_pose; try { tf_current_pose = tf_buffer_ptr_->lookupTransform( "map", "base_link", rclcpp::Time(0), rclcpp::Duration::from_seconds(1.0)); } catch (tf2::TransformException ex) { RCLCPP_ERROR(get_logger(), "[ObstacleAvoidancePlanner] %s", ex.what()); return nullptr; } geometry_msgs::msg::Pose p; p.orientation = tf_current_pose.transform.rotation; p.position.x = tf_current_pose.transform.translation.x; p.position.y = tf_current_pose.transform.translation.y; p.position.z = tf_current_pose.transform.translation.z; std::unique_ptr<geometry_msgs::msg::Pose> p_ptr = std::make_unique<geometry_msgs::msg::Pose>(p); return p_ptr; } std::vector<autoware_planning_msgs::msg::TrajectoryPoint> ObstacleAvoidancePlanner::generatePostProcessedTrajectory( const geometry_msgs::msg::Pose & ego_pose, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const std::vector<autoware_planning_msgs::msg::TrajectoryPoint> & optimized_points) const { auto t_start = std::chrono::high_resolution_clock::now(); std::vector<autoware_planning_msgs::msg::TrajectoryPoint> trajectory_points; if (path_points.empty()) { autoware_planning_msgs::msg::TrajectoryPoint tmp_point; tmp_point.pose = ego_pose; tmp_point.twist.linear.x = 0; trajectory_points.push_back(tmp_point); return trajectory_points; } if (optimized_points.empty()) { trajectory_points = util::convertPathToTrajectory(path_points); return trajectory_points; } trajectory_points = convertPointsToTrajectory(path_points, optimized_points); auto t_end = std::chrono::high_resolution_clock::now(); float elapsed_ms = std::chrono::duration<float, std::milli>(t_end - t_start).count(); RCLCPP_INFO_EXPRESSION( get_logger(), is_showing_debug_info_, "Post processing time: = %f [ms]", elapsed_ms); return trajectory_points; } bool ObstacleAvoidancePlanner::needReplan( const geometry_msgs::msg::Pose & ego_pose, const std::unique_ptr<geometry_msgs::msg::Pose> & prev_ego_pose, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const std::unique_ptr<rclcpp::Time> & prev_replanned_time, const std::unique_ptr<std::vector<autoware_planning_msgs::msg::PathPoint>> & prev_path_points, std::unique_ptr<Trajectories> & prev_trajs) { if (!prev_ego_pose || !prev_replanned_time || !prev_path_points || !prev_trajs) { return true; } if (isPathShapeChanged(ego_pose, path_points, prev_path_points)) { RCLCPP_INFO(get_logger(), "[Avoidance] Path shape is changed, reset prev trajs"); prev_trajs = nullptr; return true; } if (!util::hasValidNearestPointFromEgo( *current_ego_pose_ptr_, *prev_trajectories_ptr_, *traj_param_)) { RCLCPP_INFO( get_logger(), "[Avoidance] Could not find valid nearest point from ego, reset prev trajs"); prev_trajs = nullptr; return true; } const double delta_dist = util::calculate2DDistance(ego_pose.position, prev_ego_pose->position); if (delta_dist > min_delta_dist_for_replan_) { return true; } rclcpp::Duration delta_time = this->now() - *prev_replanned_time; const double delta_time_sec = delta_time.seconds(); if (delta_time_sec > min_delta_time_sec_for_replan_) { return true; } return false; } bool ObstacleAvoidancePlanner::isPathShapeChanged( const geometry_msgs::msg::Pose & ego_pose, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const std::unique_ptr<std::vector<autoware_planning_msgs::msg::PathPoint>> & prev_path_points) { if (!prev_path_points) { return true; } const int default_nearest_prev_path_idx = 0; const int nearest_prev_path_idx = util::getNearestIdx( *prev_path_points, ego_pose, default_nearest_prev_path_idx, traj_param_->delta_yaw_threshold_for_closest_point); const int default_nearest_path_idx = 0; const int nearest_path_idx = util::getNearestIdx( path_points, ego_pose, default_nearest_path_idx, traj_param_->delta_yaw_threshold_for_closest_point); const auto prev_first = prev_path_points->begin() + nearest_prev_path_idx; const auto prev_last = prev_path_points->end(); std::vector<autoware_planning_msgs::msg::PathPoint> truncated_prev_points(prev_first, prev_last); const auto first = path_points.begin() + nearest_path_idx; const auto last = path_points.end(); std::vector<autoware_planning_msgs::msg::PathPoint> truncated_points(first, last); for (const auto & prev_point : truncated_prev_points) { double min_dist = std::numeric_limits<double>::max(); for (const auto & point : truncated_points) { const double dist = util::calculate2DDistance(point.pose.position, prev_point.pose.position); if (dist < min_dist) { min_dist = dist; } } if (min_dist > distance_for_path_shape_change_detection_) { return true; } } return false; } std::vector<autoware_planning_msgs::msg::TrajectoryPoint> ObstacleAvoidancePlanner::convertPointsToTrajectory( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const std::vector<autoware_planning_msgs::msg::TrajectoryPoint> & trajectory_points) const { std::vector<geometry_msgs::msg::Point> interpolated_points = util::getInterpolatedPoints(trajectory_points, traj_param_->delta_arc_length_for_trajectory); // add discarded point in the process of interpolation interpolated_points.push_back(trajectory_points.back().pose.position); if (interpolated_points.size() < min_num_points_for_getting_yaw_) { return util::convertPathToTrajectory(path_points); } std::vector<geometry_msgs::msg::Point> candidate_points = interpolated_points; geometry_msgs::msg::Pose last_pose; last_pose.position = candidate_points.back(); last_pose.orientation = util::getQuaternionFromPoints( candidate_points.back(), candidate_points[candidate_points.size() - 2]); const auto extended_point_opt = util::getLastExtendedPoint( path_points.back(), last_pose, traj_param_->delta_yaw_threshold_for_closest_point, traj_param_->max_dist_for_extending_end_point); if (extended_point_opt) { candidate_points.push_back(extended_point_opt.get()); } const int zero_velocity_idx = util::getZeroVelocityIdx( is_showing_debug_info_, candidate_points, path_points, prev_trajectories_ptr_, *traj_param_); auto traj_points = util::convertPointsToTrajectoryPointsWithYaw(candidate_points); traj_points = util::fillTrajectoryWithVelocity(traj_points, 1e4); if (prev_trajectories_ptr_) { const int max_skip_comparison_velocity_idx_for_optimized_points = calculateNonDecelerationRange(traj_points, *current_ego_pose_ptr_, current_twist_ptr_->twist); const auto optimized_trajectory = util::concatTraj(*prev_trajectories_ptr_); traj_points = util::alignVelocityWithPoints( traj_points, optimized_trajectory, zero_velocity_idx, max_skip_comparison_velocity_idx_for_optimized_points); } const int max_skip_comparison_idx_for_path_points = -1; traj_points = util::alignVelocityWithPoints( traj_points, path_points, zero_velocity_idx, max_skip_comparison_idx_for_path_points); return traj_points; } void ObstacleAvoidancePlanner::publishingDebugData( const DebugData & debug_data, const autoware_planning_msgs::msg::Path & path, const std::vector<autoware_planning_msgs::msg::TrajectoryPoint> & traj_points, const VehicleParam & vehicle_param) { autoware_planning_msgs::msg::Trajectory traj; traj.header = path.header; traj.points = debug_data.foa_data.avoiding_traj_points; avoiding_traj_pub_->publish(traj); autoware_planning_msgs::msg::Trajectory debug_smoothed_points; debug_smoothed_points.header = path.header; debug_smoothed_points.points = debug_data.smoothed_points; debug_smoothed_points_pub_->publish(debug_smoothed_points); autoware_planning_msgs::msg::IsAvoidancePossible is_avoidance_possible; is_avoidance_possible.is_avoidance_possible = debug_data.foa_data.is_avoidance_possible; is_avoidance_possible_pub_->publish(is_avoidance_possible); std::vector<autoware_planning_msgs::msg::TrajectoryPoint> traj_points_debug = traj_points; // Add z information for virtual wall if (!traj_points_debug.empty()) { const int idx = util::getNearestIdx( path.points, traj_points.back().pose, 0, traj_param_->delta_yaw_threshold_for_closest_point); traj_points_debug.back().pose.position.z = path.points.at(idx).pose.position.z + 1.0; } debug_markers_pub_->publish( getDebugVisualizationMarker(debug_data, traj_points_debug, vehicle_param)); if (is_publishing_area_with_objects_) { debug_area_with_objects_pub_->publish( getDebugCostmap(debug_data.area_with_objects_map, path.drivable_area)); } if (is_publishing_clearance_map_) { debug_clearance_map_pub_->publish( getDebugCostmap(debug_data.clearance_map, path.drivable_area)); debug_object_clearance_map_pub_->publish( getDebugCostmap(debug_data.only_object_clearance_map, path.drivable_area)); } } int ObstacleAvoidancePlanner::calculateNonDecelerationRange( const std::vector<autoware_planning_msgs::msg::TrajectoryPoint> & traj_points, const geometry_msgs::msg::Pose & ego_pose, const geometry_msgs::msg::Twist & ego_twist) const { const int default_idx = 0; const int nearest_idx = util::getNearestIdx( traj_points, ego_pose, default_idx, traj_param_->delta_yaw_threshold_for_closest_point); const double non_decelerating_arc_length = (ego_twist.linear.x - traj_param_->max_avoiding_ego_velocity_ms) / traj_param_->acceleration_for_non_deceleration_range; if (non_decelerating_arc_length < 0 || traj_points.size() < 2) { return 0; } double accum_arc_length = 0; for (int i = nearest_idx + 1; i < traj_points.size(); i++) { accum_arc_length += util::calculate2DDistance(traj_points[i].pose.position, traj_points[i - 1].pose.position); if (accum_arc_length > non_decelerating_arc_length) { return i; } } return 0; } Trajectories ObstacleAvoidancePlanner::getTrajectoryInsideArea( const Trajectories & trajs, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const cv::Mat & road_clearance_map, const nav_msgs::msg::MapMetaData & map_info, DebugData * debug_data) const { debug_data->current_vehicle_footprints = util::getVehicleFootprints(trajs.model_predictive_trajectory, *vehicle_param_); const auto current_trajs_inside_area = calcTrajectoryInsideArea(trajs, path_points, road_clearance_map, map_info, debug_data); if (!current_trajs_inside_area) { RCLCPP_WARN( get_logger(), "[Avoidance] Current trajectory is not inside drivable area, passing previous one. " "Might stop at the end of drivable trajectory."); auto prev_trajs = getPrevTrajs(path_points); const bool is_prev_traj = true; const auto prev_trajs_inside_area = calcTrajectoryInsideArea( prev_trajs, path_points, road_clearance_map, map_info, debug_data, is_prev_traj); return prev_trajs_inside_area.get(); } return current_trajs_inside_area.get(); } boost::optional<Trajectories> ObstacleAvoidancePlanner::calcTrajectoryInsideArea( const Trajectories & trajs, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const cv::Mat & road_clearance_map, const nav_msgs::msg::MapMetaData & map_info, DebugData * debug_data, const bool is_prev_traj) const { if (!is_stopping_if_outside_drivable_area_) { const auto stop_idx = getStopIdx(path_points, trajs, map_info, road_clearance_map, debug_data); if (stop_idx) { auto clock = rclcpp::Clock(RCL_ROS_TIME); RCLCPP_WARN_THROTTLE( get_logger(), clock, std::chrono::milliseconds(1000).count(), "[Avoidance] Expecting over drivable area"); } return getBaseTrajectory(path_points, trajs); } const auto optional_stop_idx = getStopIdx(path_points, trajs, map_info, road_clearance_map, debug_data); if (!is_prev_traj && optional_stop_idx) { return boost::none; } auto tmp_trajs = getBaseTrajectory(path_points, trajs); if (is_prev_traj) { tmp_trajs.extended_trajectory = std::vector<autoware_planning_msgs::msg::TrajectoryPoint>{}; debug_data->is_expected_to_over_drivable_area = true; } if (optional_stop_idx && !prev_trajectories_ptr_) { if (optional_stop_idx.get() < trajs.model_predictive_trajectory.size()) { tmp_trajs.model_predictive_trajectory = std::vector<autoware_planning_msgs::msg::TrajectoryPoint>{ trajs.model_predictive_trajectory.begin(), trajs.model_predictive_trajectory.begin() + optional_stop_idx.get()}; tmp_trajs.extended_trajectory = std::vector<autoware_planning_msgs::msg::TrajectoryPoint>{}; debug_data->is_expected_to_over_drivable_area = true; } } return tmp_trajs; } Trajectories ObstacleAvoidancePlanner::getPrevTrajs( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points) const { if (!prev_trajectories_ptr_) { const auto traj = util::convertPathToTrajectory(path_points); Trajectories trajs; trajs.smoothed_trajectory = traj; trajs.model_predictive_trajectory = traj; return trajs; } else { return *prev_trajectories_ptr_; } } std::vector<autoware_planning_msgs::msg::TrajectoryPoint> ObstacleAvoidancePlanner::getPrevTrajectory( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points) const { std::vector<autoware_planning_msgs::msg::TrajectoryPoint> traj; const auto & trajs = getPrevTrajs(path_points); traj.insert( traj.end(), trajs.model_predictive_trajectory.begin(), trajs.model_predictive_trajectory.end()); traj.insert(traj.end(), trajs.extended_trajectory.begin(), trajs.extended_trajectory.end()); return traj; } Trajectories ObstacleAvoidancePlanner::makePrevTrajectories( const geometry_msgs::msg::Pose & ego_pose, const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const Trajectories & trajs) const { const auto post_processed_smoothed_traj = generatePostProcessedTrajectory(ego_pose, path_points, trajs.smoothed_trajectory); Trajectories trajectories; trajectories.smoothed_trajectory = post_processed_smoothed_traj; trajectories.mpt_ref_points = trajs.mpt_ref_points; trajectories.model_predictive_trajectory = trajs.model_predictive_trajectory; trajectories.extended_trajectory = trajs.extended_trajectory; return trajectories; } Trajectories ObstacleAvoidancePlanner::getBaseTrajectory( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const Trajectories & trajs) const { auto basee_trajs = trajs; if (!trajs.extended_trajectory.empty()) { const auto extended_point_opt = util::getLastExtendedTrajPoint( path_points.back(), trajs.extended_trajectory.back().pose, traj_param_->delta_yaw_threshold_for_closest_point, traj_param_->max_dist_for_extending_end_point); if (extended_point_opt) { basee_trajs.extended_trajectory.push_back(extended_point_opt.get()); } } else if (!trajs.model_predictive_trajectory.empty()) { const auto extended_point_opt = util::getLastExtendedTrajPoint( path_points.back(), trajs.model_predictive_trajectory.back().pose, traj_param_->delta_yaw_threshold_for_closest_point, traj_param_->max_dist_for_extending_end_point); if (extended_point_opt) { basee_trajs.extended_trajectory.push_back(extended_point_opt.get()); } } double prev_velocity = 1e4; for (auto & p : basee_trajs.model_predictive_trajectory) { if (p.twist.linear.x < 1e-6) { p.twist.linear.x = prev_velocity; } else { prev_velocity = p.twist.linear.x; } } for (auto & p : basee_trajs.extended_trajectory) { if (p.twist.linear.x < 1e-6) { p.twist.linear.x = prev_velocity; } else { prev_velocity = p.twist.linear.x; } } return basee_trajs; } boost::optional<int> ObstacleAvoidancePlanner::getStopIdx( const std::vector<autoware_planning_msgs::msg::PathPoint> & path_points, const Trajectories & trajs, const nav_msgs::msg::MapMetaData & map_info, const cv::Mat & road_clearance_map, DebugData * debug_data) const { const int nearest_idx = util::getNearestIdx( path_points, *current_ego_pose_ptr_, 0, traj_param_->delta_yaw_threshold_for_closest_point); const double accum_ds = util::getArcLength(path_points, nearest_idx); auto target_points = trajs.model_predictive_trajectory; if (accum_ds < traj_param_->num_sampling_points * traj_param_->delta_arc_length_for_mpt_points) { target_points.insert( target_points.end(), trajs.extended_trajectory.begin(), trajs.extended_trajectory.end()); const auto extended_mpt_point_opt = util::getLastExtendedTrajPoint( path_points.back(), trajs.model_predictive_trajectory.back().pose, traj_param_->delta_yaw_threshold_for_closest_point, traj_param_->max_dist_for_extending_end_point); if (extended_mpt_point_opt) { target_points.push_back(extended_mpt_point_opt.get()); } } const auto footprints = util::getVehicleFootprints(target_points, *vehicle_param_); const int debug_nearest_footprint_idx = util::getNearestIdx(target_points, current_ego_pose_ptr_->position); std::vector<util::Footprint> debug_truncated_footprints( footprints.begin() + debug_nearest_footprint_idx, footprints.end()); debug_data->vehicle_footprints = debug_truncated_footprints; const auto optional_idx = process_cv::getStopIdx(footprints, *current_ego_pose_ptr_, road_clearance_map, map_info); return optional_idx; }
46.400722
100
0.784331
kmiya
f888b9b913bea0295d270b2f4bb06291fd8d0310
252
cpp
C++
src/fatal.cpp
franko/elementary-plotlib
d11b56a13893781d84a8e93183f01b13140dd4e3
[ "MIT" ]
14
2020-04-03T02:14:08.000Z
2021-07-16T21:05:56.000Z
src/fatal.cpp
franko/elementary-plotlib
d11b56a13893781d84a8e93183f01b13140dd4e3
[ "MIT" ]
2
2020-04-22T15:40:42.000Z
2020-04-28T21:17:23.000Z
src/fatal.cpp
franko/libcanvas
d11b56a13893781d84a8e93183f01b13140dd4e3
[ "MIT" ]
1
2020-04-30T07:49:02.000Z
2020-04-30T07:49:02.000Z
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include "fatal.h" void fatal_exception(const char* msg, ...) { va_list ap; va_start(ap, msg); vfprintf(stderr, msg, ap); fputs("\n", stderr); va_end(ap); abort(); }
14
37
0.599206
franko
f88a00d3eec19507b915f09fa3f1c1554e0e594c
636
cpp
C++
source/ImageSymLoader.cpp
xzrunner/s2loader
6317bbec560db93f866bda78373ef58aed504ca3
[ "MIT" ]
null
null
null
source/ImageSymLoader.cpp
xzrunner/s2loader
6317bbec560db93f866bda78373ef58aed504ca3
[ "MIT" ]
null
null
null
source/ImageSymLoader.cpp
xzrunner/s2loader
6317bbec560db93f866bda78373ef58aed504ca3
[ "MIT" ]
null
null
null
#include "s2loader/ImageSymLoader.h" #include <gum/Image.h> #include <gum/ImageSymbol.h> #include <gum/ImagePool.h> #include <simp/NodeID.h> namespace s2loader { ImageSymLoader::ImageSymLoader(gum::ImageSymbol& sym) : m_sym(sym) { } void ImageSymLoader::Load(const bimp::FilePath& res_path, float scale, bool async) { int pkg_id = simp::NodeID::GetPkgID(m_sym.GetID()); auto img = gum::ImagePool::Instance()->Create(pkg_id, res_path, async); if (!img) { return; } m_sym.SetImage(img); auto w = img->GetWidth(); auto h = img->GetHeight(); m_sym.SetRegion(sm::ivec2(0, 0), sm::ivec2(w, h), sm::vec2(0, 0), 0, scale); } }
20.516129
82
0.687107
xzrunner
f88b48791b1989df091bd1f5243a99ff90fcd269
14,690
cpp
C++
test/unit/module/bessel/cyl_bessel_in.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
test/unit/module/bessel/cyl_bessel_in.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
test/unit/module/bessel/cyl_bessel_in.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <eve/function/cyl_bessel_in.hpp> #include <eve/function/diff/cyl_bessel_in.hpp> #include <eve/constant/inf.hpp> #include <eve/constant/minf.hpp> #include <eve/constant/nan.hpp> #include <eve/platform.hpp> #include <cmath> #include <boost/math/special_functions/bessel.hpp> #include <boost/math/special_functions/bessel_prime.hpp> //================================================================================================== //== Types tests //================================================================================================== EVE_TEST_TYPES( "Check return types of cyl_bessel_in" , eve::test::simd::ieee_reals ) <typename T>(eve::as<T>) { using v_t = eve::element_type_t<T>; using i_t = eve::as_integer_t<v_t>; using I_t = eve::wide<i_t, eve::cardinal_t<T>>; TTS_EXPR_IS( eve::cyl_bessel_in(T(), T()) , T); TTS_EXPR_IS( eve::cyl_bessel_in(v_t(),v_t()), v_t); TTS_EXPR_IS( eve::cyl_bessel_in(i_t(),T()), T); TTS_EXPR_IS( eve::cyl_bessel_in(I_t(),T()), T); TTS_EXPR_IS( eve::cyl_bessel_in(i_t(),v_t()), v_t); TTS_EXPR_IS( eve::cyl_bessel_in(I_t(),v_t()), T); }; //================================================================================================== //== integral orders //================================================================================================== EVE_TEST( "Check behavior of cyl_bessel_in on wide with integral order" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::ramp(0), eve::test::randoms(0.0, 10.0)) ) <typename T>(T n , T a0) { using v_t = eve::element_type_t<T>; auto eve__cyl_bessel_in = [](auto n, auto x) { return eve::cyl_bessel_in(n, x); }; auto std__cyl_bessel_in = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_i(n, x); }; if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(0, eve::minf(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, eve::inf(eve::as<v_t>())), eve::inf(eve::as<v_t>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, eve::nan(eve::as<v_t>())), eve::nan(eve::as<v_t>()), 0); } //scalar large x TTS_ULP_EQUAL(eve__cyl_bessel_in(3, v_t(1500)), eve::inf(eve::as<v_t>()), 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, v_t(50)), std__cyl_bessel_in(2, v_t(50)), 5.0); //scalar forward TTS_ULP_EQUAL(eve__cyl_bessel_in(0, v_t(10)), std__cyl_bessel_in(0, v_t(10)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(1, v_t(5)), std__cyl_bessel_in(1, v_t(5)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, v_t(10)), std__cyl_bessel_in(2, v_t(10)) , 35.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, v_t(5)), std__cyl_bessel_in(3, v_t(5)) , 35.0); //scalar small TTS_ULP_EQUAL(eve__cyl_bessel_in(0, v_t(0.1)), std__cyl_bessel_in(0, v_t(0.1)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(1, v_t(0.2)), std__cyl_bessel_in(1, v_t(0.2)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, v_t(0.1)), std__cyl_bessel_in(2, v_t(0.1)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, v_t(0.2)), std__cyl_bessel_in(3, v_t(0.2)) , 5.0); //scalar medium TTS_ULP_EQUAL(eve__cyl_bessel_in(10, v_t(8)), std__cyl_bessel_in(10, v_t(8)) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(20, v_t(8)), std__cyl_bessel_in(20, v_t(8)) , 5.0); if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(0, eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } //simd large x TTS_ULP_EQUAL(eve__cyl_bessel_in(3, T(1500)), eve::inf(eve::as<T>()), 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, T(50)), T(std__cyl_bessel_in(2, v_t(50))), 5.0); //simd forward TTS_ULP_EQUAL(eve__cyl_bessel_in(2, T(10)), T(std__cyl_bessel_in(2, v_t(10))) , 35.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, T(5)), T(std__cyl_bessel_in(3, v_t(5))) , 35.0); //simd small TTS_ULP_EQUAL(eve__cyl_bessel_in(0, T(0.1)), T(std__cyl_bessel_in(0, v_t(0.1))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(1, T(0.2)), T(std__cyl_bessel_in(1, v_t(0.2))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(2, T(0.1)), T(std__cyl_bessel_in(2, v_t(0.1))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(3, T(0.2)), T(std__cyl_bessel_in(3, v_t(0.2))) , 5.0); //simd medium TTS_ULP_EQUAL(eve__cyl_bessel_in(10, T(8)), T(std__cyl_bessel_in(10, v_t(8))) , 7.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(20, T(8)), T(std__cyl_bessel_in(20, v_t(8))) , 5.0); if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(0), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3), T(1500)), eve::inf(eve::as<T>()), 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2), T(50)), T(std__cyl_bessel_in(2, v_t(50))), 5.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2), T(10)), T(std__cyl_bessel_in(2, v_t(10))) , 35.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3), T(5)), T(std__cyl_bessel_in(3, v_t(5))) , 35.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2), T(0.1)), T(std__cyl_bessel_in(2, v_t(0.1))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3), T(0.2)), T(std__cyl_bessel_in(3, v_t(0.2))) , 5.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(T(10), T(8)), T(std__cyl_bessel_in(10, v_t(8))) , 7.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(20), T(8)), T(std__cyl_bessel_in(20, v_t(8))) , 5.0); using i_t = eve::as_integer_t<v_t>; using I_t = eve::wide<i_t, eve::cardinal_t<T>>; if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(0), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(2), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(3), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(3), T(1500)), eve::inf(eve::as<T>()), 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(2), T(50)), T(std__cyl_bessel_in(2, v_t(50))), 5.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(2), T(10)), T(std__cyl_bessel_in(2, v_t(10))) , 35.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(3), T(5)), T(std__cyl_bessel_in(3, v_t(5))) , 35.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(2), T(0.1)), T(std__cyl_bessel_in(2, v_t(0.1))) , 5.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(3), T(0.2)), T(std__cyl_bessel_in(3, v_t(0.2))) , 5.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(10), T(8)), T(std__cyl_bessel_in(10, v_t(8))) , 7.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(I_t(20), T(8)), T(std__cyl_bessel_in(20, v_t(8))) , 5.0); TTS_ULP_EQUAL(map(eve__cyl_bessel_in, n, a0), map(std__cyl_bessel_in, n, a0) , 500.0); TTS_ULP_EQUAL(map(eve__cyl_bessel_in, -n, a0), map(std__cyl_bessel_in, -n, a0) , 500.0); }; //================================================================================================== //== non integral orders //================================================================================================== EVE_TEST( "Check behavior of cyl_bessel_in on wide with non integral order" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::randoms(0.0, 10.0) , eve::test::randoms(0.0, 10.0)) ) <typename T>(T n, T a0 ) { using v_t = eve::element_type_t<T>; auto eve__cyl_bessel_in = [](auto n, auto x) { return eve::cyl_bessel_in(n, x); }; auto std__cyl_bessel_in = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_i(double(n), double(x)); }; if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(3.5), v_t(1500)), eve::inf(eve::as<v_t>()), 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(2.5), v_t(50)), std__cyl_bessel_in(v_t(2.5), v_t(50)), 10.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(2.5), v_t(10)), std__cyl_bessel_in(v_t(2.5), v_t(10)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(3.5), v_t(5)), std__cyl_bessel_in(v_t(3.5), v_t(5)) , 10.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(2.5), v_t(0.1)), std__cyl_bessel_in(v_t(2.5), v_t(0.1)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(3.5), v_t(0.2)), std__cyl_bessel_in(v_t(3.5), v_t(0.2)) , 10.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(10.5), v_t(8)), std__cyl_bessel_in(v_t(10.5), v_t(8)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(10.5), v_t(8)), std__cyl_bessel_in(v_t(10.5), v_t(8)) , 10.0); if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), T(700)), T(std__cyl_bessel_in(v_t(3.5), v_t(700))), 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), T(50)), T(std__cyl_bessel_in(v_t(2.5), v_t(50))), 10.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), T(10)), T(std__cyl_bessel_in(v_t(2.5), v_t(10))) , 310.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), T(5)), T(std__cyl_bessel_in(v_t(3.5), v_t(5))) , 310.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(T(2.5), T(0.1)), T(std__cyl_bessel_in(v_t(2.5), v_t(0.1))) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(3.5), T(0.2)), T(std__cyl_bessel_in(v_t(3.5), v_t(0.2))) , 10.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(T(10.5), T(8)), T(std__cyl_bessel_in(v_t(10.5), v_t(8))) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(10.5), T(8)), T(std__cyl_bessel_in(v_t(10.5), v_t(8))) , 10.0); TTS_RELATIVE_EQUAL(eve__cyl_bessel_in(n, a0), map(std__cyl_bessel_in, n, a0) , 1.0e-3); }; EVE_TEST( "Check behavior of cyl_bessel_in on wide with negative non integral order" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::randoms(0.0, 10.0) , eve::test::randoms(0.0, 10.0)) ) <typename T>(T n, T a0 ) { using v_t = eve::element_type_t<T>; auto eve__cyl_bessel_in = [](auto n, auto x) { return eve::cyl_bessel_in(n, x); }; auto std__cyl_bessel_in = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_i(double(n), double(x)); }; if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-3.5), v_t(1500)), eve::inf(eve::as<v_t>()), 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-2.5), v_t(60)), std__cyl_bessel_in(v_t(-2.5), v_t(60)), 10.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-2.5), v_t(10)), std__cyl_bessel_in(v_t(-2.5), v_t(10)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-3.5), v_t(5)), std__cyl_bessel_in(v_t(-3.5), v_t(5)) , 10.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-2.5), v_t(0.1)), std__cyl_bessel_in(v_t(-2.5), v_t(0.1)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-3.5), v_t(0.2)), std__cyl_bessel_in(v_t(-3.5), v_t(0.2)) , 10.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-10.5), v_t(8)), std__cyl_bessel_in(v_t(-10.5), v_t(8)) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(v_t(-10.5), v_t(8)), std__cyl_bessel_in(v_t(-10.5), v_t(8)) , 10.0); if constexpr( eve::platform::supports_invalids ) { TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-0.5), eve::minf(eve::as<T>())), eve::nan(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), eve::inf(eve::as<T>())), eve::inf(eve::as<T>()), 0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), eve::nan(eve::as<T>())), eve::nan(eve::as<T>()), 0); } // large x TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), T(1500)), eve::inf(eve::as<T>()), 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), T(50)), T(std__cyl_bessel_in(v_t(-2.5), v_t(50))), 10.0); // forward TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), T(10)), T(std__cyl_bessel_in(v_t(-2.5), v_t(10))) , 310.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), T(5)), T(std__cyl_bessel_in(v_t(-3.5), v_t(5))) , 310.0); // serie TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-2.5), T(0.1)), T(std__cyl_bessel_in(v_t(-2.5), v_t(0.1))) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-3.5), T(0.2)), T(std__cyl_bessel_in(v_t(-3.5), v_t(0.2))) , 10.0); // besseljy TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-10.5), T(8)), T(std__cyl_bessel_in(v_t(-10.5), v_t(8))) , 10.0); TTS_ULP_EQUAL(eve__cyl_bessel_in(T(-10.5), T(8)), T(std__cyl_bessel_in(v_t(-10.5), v_t(8))) , 10.0); TTS_RELATIVE_EQUAL(eve__cyl_bessel_in(-n, a0), map(std__cyl_bessel_in, -n, a0) , 1.0e-3); }; EVE_TEST( "Check behavior of diff of cyl_bessel_in on wide" , eve::test::simd::ieee_reals , eve::test::generate(eve::test::randoms(0.0, 10.0) , eve::test::randoms(0.0, 10.0)) ) <typename T>(T n, T a0 ) { using v_t = eve::element_type_t<T>; auto eve__diff_bessel_in = [](auto n, auto x) { return eve::diff(eve::cyl_bessel_in)(n, x); }; auto std__diff_bessel_in = [](auto n, auto x)->v_t { return boost::math::cyl_bessel_i_prime(double(n), double(x)); }; TTS_RELATIVE_EQUAL(eve__diff_bessel_in(n, a0), map(std__diff_bessel_in, n, a0) , 1.0e-3); };
55.855513
120
0.608169
the-moisrex
f88c2a22990818344fa1d81a415acb3b7c0a2ad5
7,184
cxx
C++
RhoNNO/TRadon.cxx
marcelkunze/rhonno
b9a06557c5e059ab25ad9077a13dbaeb449ed85e
[ "MIT" ]
2
2019-07-12T12:16:22.000Z
2020-09-19T14:51:47.000Z
RhoNNO/TRadon.cxx
marcelkunze/rhonno
b9a06557c5e059ab25ad9077a13dbaeb449ed85e
[ "MIT" ]
null
null
null
RhoNNO/TRadon.cxx
marcelkunze/rhonno
b9a06557c5e059ab25ad9077a13dbaeb449ed85e
[ "MIT" ]
2
2017-09-27T13:12:39.000Z
2019-07-12T12:14:43.000Z
// radon_function // various functions for performing the fuzzy Radon transform // M.Kunze, Heidelberg University, 2018 #include <stdlib.h> #include <math.h> #include "TNtuple.h" #include "TVector3.h" #include "TH2D.h" #include "TPolyMarker3D.h" #include "TPolyLine3D.h" #include "TRadon.h" #include <string> #include <iostream> #include <random> using namespace std; ClassImp(TRadon) #define DGAMMA 0.1 #define NGAMMA 40 #define DKAPPA 0.125 #define NKAPPA 25 #define DPHI M_PI/30. #define NPHI 30 #define TAUMAX 0.5*M_PI #define DRAWTRACK false #define signum(x) (x > 0) ? 1 : ((x < 0) ? -1 : 0) TRadon::TRadon(double sig, double thr) : sigma(sig), threshold(thr), Hlist(0) { nt1 = new TNtuple("RadonTransform","Radon Transform","kappa:phi:gamma:sigma:density:x:y:z"); nt2 = new TNtuple("RadonTrackParameters","Radon Track Parameters","kappa:phi:gamma:sigma:density:x:y:z"); float gamma = -2.0; for (int i=0;i<NGAMMA;i++,gamma+=DGAMMA) { string name = "Gamma=" + to_string(gamma); string title = "Radon density in r/Phi " + name; Hlist.Add(new TH2D(name.data(),title.data(),40,0.0,4.,30,0.0,3.0)); } } TRadon::~TRadon() { Hlist.Write(); nt1->Write(); delete nt1; nt2->Write(); delete nt2; } /* * Do a RADON transform of coordinates (all lengths in meter) * (1 GeV/c == 2.22m Radius at B=1.5T) */ std::vector<RADON>& TRadon::Transform(std::vector<TVector3> &points) { hits = points; double kappa,gamma,phi; long k=0,g=0,p=0; gamma = -2.0; for (g=0;g<NGAMMA;g++,gamma += DGAMMA) { kappa = -1.125; for (k=0;k<NKAPPA;k++) { kappa = kappa + DKAPPA; phi = 0.; for (p=0;p<NPHI;p++) { phi = phi + DPHI; RADON t; t.kappa = kappa; t.phi = phi; t.gamma = gamma; t.sigma = sigma; long nhits = Density(t,hits); if (t.density > threshold && nhits > 3) { printf("\nDensity: %f",t.density); TH2D *h = (TH2D *) Hlist[(int) g]; h->Fill(1./kappa,phi,t.density); rt.push_back(t); // Note the candidate track parameters } } } } return rt; } long TRadon::Density(RADON &t, std::vector<TVector3> &points) { long nhits = 0, index = 0; double density = 0.0; vector<TVector3>::iterator it; for(it = points.begin(); it != points.end(); it++, index++) { TVector3 point=*it; t.x = point.x(); t.y = point.y(); t.z = point.z(); double d = radon_hit_density(&t); density += d; t.density = density; if (d > 1.0) { t.index.push_back(index); nhits++; } } return nhits; } double TRadon::getEta_g(RADON *t) { double sp,cp,x2,y2; sp = sin(t->phi); cp = cos(t->phi); x2 = (t->kappa * t->x + sp) * (t->kappa * t->x + sp); y2 = (t->kappa * t->y - cp) * (t->kappa * t->y - cp); return sqrt(x2+y2); } double TRadon::getTau_i(RADON *t) { double sp,cp, nom, denom; sp = sin(t->phi); cp = cos(t->phi); nom = t->y * sp + t->x * cp; denom = (1.0 / t->kappa) + t->x * sp - t->y * cp; return (signum(t->kappa)) * atan(nom/denom); } double TRadon::getZ_g(RADON *t) { return ((t->gamma * getTau_i(t)) - t->z); } double TRadon::radon_hit_density(RADON *t) { double eta_g,gamma,kappa,error,z_g,k2,s2,g2,factor, kappafunction,efunction,radon; eta_g = getEta_g(t); gamma = t->gamma; kappa = t->kappa; error = t->sigma; z_g = getZ_g(t) ; k2 = kappa * kappa; s2 = error * error; g2 = gamma * gamma; factor = 1. / (2 * M_PI * s2 * TAUMAX); kappafunction = abs(kappa) / sqrt(eta_g + k2 * g2); efunction = -1.0 / (2 * s2) * (((eta_g - 1.0) * (eta_g - 1.0) / k2) + (eta_g * z_g * z_g / (eta_g + k2 * g2))); radon = factor * kappafunction * exp(efunction); return radon; } /* * Create a tuple with Track coordinates */ void TRadon::GenerateTrack(std::vector<TVector3> &points, int np, double delta, double radius, double phi, double gamma, double error) { default_random_engine generator; double tau = 0.025; for (int i=0; i<np; i++,tau+=delta) { float X,Y,Z; X = radius * ( sin(phi + (signum(radius)) * tau) - sin(phi)); Y = radius * (-cos(phi + (signum(radius)) * tau) + cos(phi)); Z = gamma * tau; if (error > 0.0) { normal_distribution<float> distribution0(X,error); X = distribution0(generator); normal_distribution<float> distribution1(Y,error); Y = distribution1(generator); normal_distribution<float> distribution2(Z,error); Z = distribution2(generator); } points.push_back(TVector3(X,Y,Z)); } } void TRadon::Draw(Option_t *option) { int n = 1; vector<RADON>::iterator radon; for(radon = rt.begin(); radon != rt.end(); radon++) { RADON t=*radon;; double radius = 1./t.kappa; printf("\nTrack candidate #%d r:%f k:%f p:%f g:%f : %f ",n++,radius,t.kappa,t.phi,t.gamma,t.density); printf("\nAssociated hits: "); for (unsigned long j = 0; j < t.index.size(); j++) { cout << t.index[j] << " "; } nt2->Fill(t.kappa,t.phi,t.gamma,t.sigma,t.density,t.x,t.y,t.z); // Store results as ROOT ntuple if (t.density > threshold) { printf("Density > %f", threshold); std::vector<TVector3> nt3; if (DRAWTRACK) GenerateTrack(nt3,25,0.025,radius,t.phi,t.gamma); else for (unsigned long i=0;i<t.index.size();i++) { long index = t.index[i]; float x = hits[index].x(); float y = hits[index].y(); float z = hits[index].z(); TVector3 p(x,y,z); nt3.push_back(p); } // Draw the track candidates TPolyMarker3D *hitmarker = new TPolyMarker3D(nt3.size()); TPolyLine3D *connector = new TPolyLine3D(nt3.size()); int j = 0; vector<TVector3>::iterator it; for(it = nt3.begin(); it != nt3.end(); it++, j++) { TVector3 point=*it; hitmarker->SetPoint(j,point.x(),point.y(),point.z()); hitmarker->SetMarkerSize(0.1); hitmarker->SetMarkerColor(kYellow); hitmarker->SetMarkerStyle(kFullDotLarge); hitmarker->Draw(option); connector->SetPoint(j, point.x(),point.y(),point.z()); connector->SetLineWidth(1); connector->SetLineColor(kYellow); connector->Draw(option); printf("\n%d: x:%f y:%f z:%f d:%f ",j,point.x(),point.y(),point.z(),point.Mag()); } } } }
30.184874
136
0.518235
marcelkunze
f88c8d94c3c043e07996124658bbc58ffe03bdc5
10,013
cpp
C++
waifu2x-converter-gls/src/convertRoutine.cpp
ymdymd/glsCV
fa89193d653767f11e01ec1bd13e2f3461a5b1b3
[ "BSD-3-Clause" ]
null
null
null
waifu2x-converter-gls/src/convertRoutine.cpp
ymdymd/glsCV
fa89193d653767f11e01ec1bd13e2f3461a5b1b3
[ "BSD-3-Clause" ]
31
2016-05-09T01:31:21.000Z
2016-08-11T11:34:39.000Z
waifu2x-converter-gls/src/convertRoutine.cpp
oasi-adamay/glsCV
fa89193d653767f11e01ec1bd13e2f3461a5b1b3
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2016, oasi-adamay All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of glsCV nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * convertRoutine.cpp * (ここにファイルの簡易説明を記入) * * Created on: 2015/05/31 * Author: wlamigo * changed : oasi-adamay * (ここにファイルの説明を記入) */ #include "convertRoutine.hpp" #include "glsCV.h" //#ifdef _DEBUG //#define _ENABLE_TMR_ #if defined(_ENABLE_TMR_) #include "Timer.h" #define _TMR_(...) Timer tmr(__VA_ARGS__) #else #define _TMR_(...) #endif namespace w2xc { // converting process inside program static bool convertWithModelsBasic(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models); static bool convertWithModelsBlockSplit(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models); bool convertWithModels(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models, bool blockSplitting) { cv::Size blockSize = modelUtility::getInstance().getBlockSize(); bool requireSplitting = (inputPlane.size().width * inputPlane.size().height) > blockSize.width * blockSize.height * 3 / 2; // requireSplitting = true; if (blockSplitting && requireSplitting) { return convertWithModelsBlockSplit(inputPlane, outputPlane, models); } else { //insert padding to inputPlane cv::Mat tempMat; int nModel = (int)models.size(); cv::Size outputSize = inputPlane.size(); cv::copyMakeBorder(inputPlane, tempMat, nModel, nModel, nModel, nModel, cv::BORDER_REPLICATE); bool ret = convertWithModelsBasic(tempMat, outputPlane, models); tempMat = outputPlane(cv::Range(nModel, outputSize.height + nModel), cv::Range(nModel, outputSize.width + nModel)); assert( tempMat.size().width == outputSize.width && tempMat.size().height == outputSize.height); tempMat.copyTo(outputPlane); return ret; } } #ifdef USE_GLS static bool convertWithModelsBasic(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models) { // padding is require before calling this function //std::unique_ptr<std::vector<cv::Mat> > inputPlanes = std::unique_ptr< // std::vector<cv::Mat> >(new std::vector<cv::Mat>()); //std::unique_ptr<std::vector<cv::Mat> > outputPlanes = std::unique_ptr< // std::vector<cv::Mat> >(new std::vector<cv::Mat>()); std::vector<gls::GlsMat> inputPlanes; std::vector<gls::GlsMat> outputPlanes; inputPlanes.clear(); inputPlanes.push_back((GlsMat)inputPlane); for (int index = 0; index < models.size(); index++) { std::cout << "Layer#" << (index) << " : " << models[index]->getNInputPlanes() << " > " << models[index]->getNOutputPlanes() << std::endl; if (!models[index]->filter(inputPlanes, outputPlanes)) { std::exit(-1); } if (index != models.size() - 1) { inputPlanes = outputPlanes; } } outputPlane = (Mat)outputPlanes[0]; return true; } #elif defined(USE_GLS_NEW) static bool convertWithModelsBasic(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models) { _TMR_("convertWithModelsBasic\t:"); // padding is require before calling this function CV_Assert(inputPlane.type() == CV_32FC1); CV_Assert(inputPlane.dims == 2); if (!inputPlane.isContinuous()){ inputPlane = inputPlane.clone(); // to be continuous } int _size[3] = { 1, inputPlane.size[0], inputPlane.size[1] }; // gls::GlsMat inputPlanes(cv::Mat(3, _size, CV_32FC1, inputPlane.data)); //upload gls::GlsMat inputPlanes; { _TMR_("upload \t\t:"); cv::Mat _inputPlanes = cv::Mat(3, _size, CV_32FC1, inputPlane.data); inputPlanes = (gls::GlsMat)_inputPlanes; } gls::GlsMat outputPlanes; for (int index = 0; index <= models.size(); index++) { #if !defined(_ENABLE_TMR_) { std::cout << "\r["; int progress = 0; for (; progress < index; progress++) std::cout << "="; for (; progress < (int)models.size(); progress++) std::cout << " "; std::cout << "]"; std::cout.flush(); } #endif if (index >= (int)models.size()) { break; } { // core processing std::string str = "Layer#" + to_string(index) + " ( " + to_string(models[index]->getNInputPlanes()) + " > " + to_string(models[index]->getNOutputPlanes()) + " )\t:"; _TMR_(str); if (!models[index]->filter(inputPlanes, outputPlanes)) { std::exit(-1); } } if (index != models.size() - 1) { inputPlanes = outputPlanes; } } { _TMR_("download\t\t:"); outputPlane = cv::Mat(inputPlane.size(), inputPlane.type()); cv::Mat _outputPlanes(3, _size, CV_32FC1, outputPlane.data); outputPlanes.download(_outputPlanes); } std::cout << " complete." << std::endl; return true; } #else static bool convertWithModelsBasic(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models) { // padding is require before calling this function CV_Assert(inputPlane.type() == CV_32FC1); int _size[3] = { 1, inputPlane.size[0], inputPlane.size[1] }; cv::Mat inputPlanes = cv::Mat(3, _size, CV_32FC1); cv::Mat outputPlanes; { cv::Mat roi(inputPlane.size(), CV_32FC1, inputPlanes.ptr<float>(0)); inputPlane.copyTo(roi); } for (int index = 0; index < models.size(); index++) { std::cout << "Layer#" << (index) << " : " << models[index]->getNInputPlanes() << " > " << models[index]->getNOutputPlanes() << std::endl; if (!models[index]->filter(inputPlanes, outputPlanes)) { std::exit(-1); } if (index != models.size() - 1) { inputPlanes = outputPlanes; } } { outputPlane = cv::Mat(inputPlane.size(), inputPlane.type()); cv::Mat roi(inputPlane.size(), CV_32FC1, outputPlanes.ptr<float>(0)); roi.copyTo(outputPlane); } return true; } #endif static bool convertWithModelsBlockSplit(cv::Mat &inputPlane, cv::Mat &outputPlane, std::vector<std::unique_ptr<Model> > &models) { _TMR_("convertWithModelsBlockSplit\t:"); // padding is not required before calling this function // initialize local variables cv::Size blockSize = modelUtility::getInstance().getBlockSize(); unsigned int nModel = (int)models.size(); //insert padding to inputPlane cv::Mat tempMat; cv::Size outputSize = inputPlane.size(); cv::copyMakeBorder(inputPlane, tempMat, nModel, nModel, nModel, nModel, cv::BORDER_REPLICATE); // calcurate split rows/cols unsigned int splitColumns = static_cast<unsigned int>(std::ceil( static_cast<float>(outputSize.width) / static_cast<float>(blockSize.width - 2 * nModel))); unsigned int splitRows = static_cast<unsigned int>(std::ceil( static_cast<float>(outputSize.height) / static_cast<float>(blockSize.height - 2 * nModel))); // start to convert cv::Mat processRow; cv::Mat processBlock; cv::Mat processBlockOutput; cv::Mat writeMatTo; cv::Mat writeMatFrom; outputPlane = cv::Mat::zeros(outputSize, CV_32FC1); for (unsigned int r = 0; r < splitRows; r++) { if (r == splitRows - 1) { processRow = tempMat.rowRange(r * (blockSize.height - 2 * nModel), tempMat.size().height); } else { processRow = tempMat.rowRange(r * (blockSize.height - 2 * nModel), r * (blockSize.height - 2 * nModel) + blockSize.height); } for (unsigned int c = 0; c < splitColumns; c++) { if (c == splitColumns - 1) { processBlock = processRow.colRange( c * (blockSize.width - 2 * nModel), tempMat.size().width); } else { processBlock = processRow.colRange( c * (blockSize.width - 2 * nModel), c * (blockSize.width - 2 * nModel) + blockSize.width); } std::cout << "start process block (" << c << "," << r << ") ..." << std::endl; if (!convertWithModelsBasic(processBlock, processBlockOutput, models)) { std::cerr << "w2xc::convertWithModelsBasic()\n" "in w2xc::convertWithModelsBlockSplit() : \n" "something error has occured. stop." << std::endl; return false; } writeMatFrom = processBlockOutput( cv::Range(nModel, processBlockOutput.size().height - nModel), cv::Range(nModel, processBlockOutput.size().width - nModel)); writeMatTo = outputPlane( cv::Range(r * (blockSize.height - 2 * nModel), r * (blockSize.height - 2 * nModel) + processBlockOutput.size().height - 2 * nModel), cv::Range(c * (blockSize.height - 2 * nModel), c * (blockSize.height - 2 * nModel) + processBlockOutput.size().width - 2 * nModel)); assert( writeMatTo.size().height == writeMatFrom.size().height && writeMatTo.size().width == writeMatFrom.size().width); writeMatFrom.copyTo(writeMatTo); } // end process 1 column } // end process all blocks return true; } }
30.159639
83
0.679317
ymdymd
f89358a42dc7aa82998f13cf7e020491653d8e00
1,637
cc
C++
src/block_diagonal_check.cc
jwlawson/ptope
2c664ac4fb7b036a298e7c6a1b2cf58d803f227a
[ "Apache-2.0" ]
1
2019-02-22T03:03:13.000Z
2019-02-22T03:03:13.000Z
src/block_diagonal_check.cc
jwlawson/ptope
2c664ac4fb7b036a298e7c6a1b2cf58d803f227a
[ "Apache-2.0" ]
9
2016-08-31T16:34:59.000Z
2016-09-12T16:29:55.000Z
src/block_diagonal_check.cc
jwlawson/ptope
2c664ac4fb7b036a298e7c6a1b2cf58d803f227a
[ "Apache-2.0" ]
null
null
null
/* * block_diagonal_check.h * Copyright 2015 John Lawson * * 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 "block_diagonal_check.h" namespace ptope { bool BlockDiagonalCheck::operator()(const arma::mat m) { _unvisited.clear(); _components.clear(); while(!_queue.empty()) { _queue.pop(); } for(arma::uword i = 0; i < m.n_cols; ++i) { _unvisited.push_back(i); } arma::uword current_component = 0; while(!_unvisited.empty()) { _components.push_back(std::vector<arma::uword>()); _queue.push(_unvisited.back()); _unvisited.pop_back(); while(!_queue.empty()) { arma::uword col = _queue.front(); _queue.pop(); for(auto unv_it = _unvisited.end(); unv_it > _unvisited.begin();) { /* Here we need a reverse iterator, wbut one which can be used to erase * elements. Hence this slightly hacky version. */ --unv_it; arma::uword row = *unv_it; if(m(row,col) != 0) { /* Vertex row is connected to vertex col */ _unvisited.erase(unv_it); _components[current_component].push_back(row); _queue.push(row); } } } } return _components.size() == 1; } }
29.763636
75
0.682957
jwlawson
f89f10e98f3397294caa6ae1ab1a6e559ac1ed94
1,184
cpp
C++
c++/reverse_string_ii.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/reverse_string_ii.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/reverse_string_ii.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
/* Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original. Example: Input: s = "abcdefg", k = 2 Output: "bacdfeg" Restrictions: The string consists of lower English letters only. Length of the given string and k will in the range [1, 10000] */ /* * */ #include "helper.h" class Solution { public: string reverseStr(string s, int k) { for (int i = 0; i < s.length(); i += 2 * k) { if (i + k >= s.length()) { reverse(s.begin() + i, s.end()); } else { reverse(s.begin() + i, s.begin() + i + k); } } return s; } }; int main() { Solution s; cout << s.reverseStr("abcdefg", 2) << endl; cout << s.reverseStr("abcdefg", 12) << endl; cout << s.reverseStr("hyzqyljrnigxvdtneasepfahmtyhlohwxmkqcdfehybknvdmfrfvtbsovjbdhevlfxpdaovjgunjqlimjkfnqcqnajmebeddqsgl", 39) << endl; return 0; }
31.157895
338
0.628378
SongZhao
f8a4350b740a31d57bb5677d091a93b605ce57be
1,334
cpp
C++
Source Code V2/TssInSphere/ApplyCurls.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
11
2020-09-27T07:35:22.000Z
2022-03-09T11:01:31.000Z
Source Code V2/TssInSphere/ApplyCurls.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
1
2020-10-28T13:14:58.000Z
2020-10-28T21:04:44.000Z
Source Code V2/TssInSphere/ApplyCurls.cpp
DavidGeUSA/TSS
e364e324948c68efc6362a0db3aa51696227fa60
[ "MIT" ]
7
2020-09-27T07:35:24.000Z
2022-01-02T13:53:21.000Z
/******************************************************************* Author: David Ge ([email protected], aka Wei Ge) Last modified: 03/31/2018 Allrights reserved by David Ge ********************************************************************/ #include "ApplyCurls.h" ApplyCurls::ApplyCurls() { } void ApplyCurls::SetFields(FieldPoint3D *fields, FieldPoint3D *curls, double *factorE, double *factorH) { _fields = fields; _curls = curls; _factorE = factorE; _factorH = factorH; index = 0; } void ApplyCurlsEven::handleData(int m, int n, int p) { _fields[index].E.x += *_factorE * _curls[index].E.x; _fields[index].E.y += *_factorE * _curls[index].E.y; _fields[index].E.z += *_factorE * _curls[index].E.z; _fields[index].H.x += *_factorH * _curls[index].H.x; _fields[index].H.y += *_factorH * _curls[index].H.y; _fields[index].H.z += *_factorH * _curls[index].H.z; // index++; } void ApplyCurlsOdd::handleData(int m, int n, int p) { _fields[index].E.x += *_factorH * _curls[index].H.x; _fields[index].E.y += *_factorH * _curls[index].H.y; _fields[index].E.z += *_factorH * _curls[index].H.z; _fields[index].H.x += *_factorE * _curls[index].E.x; _fields[index].H.y += *_factorE * _curls[index].E.y; _fields[index].H.z += *_factorE * _curls[index].E.z; // index++; }
30.318182
104
0.578711
DavidGeUSA
f8a53d0a87cd66006e38d180d29989125d21774c
1,313
cpp
C++
examples/login.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
5
2019-06-30T06:29:46.000Z
2021-12-17T12:41:23.000Z
examples/login.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
2
2018-01-09T17:14:45.000Z
2020-03-23T00:16:50.000Z
examples/login.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
7
2015-09-13T18:40:58.000Z
2020-01-24T10:57:56.000Z
#include <iostream> #include "greentop/ExchangeApi.h" using namespace greentop; int main(int argc, char* argv[]) { if (argc != 3 && argc != 4 && argc != 5) { std::cerr << "Usage: " << std::endl << argv[0] << " <application key> <username> <password>" << std::endl << " OR" << std::endl << argv[0] << " <username> <password> <certificate filename> <key filename>" << std::endl << " OR" << std::endl << argv[0] << " <application key> <SSO token>" << std::endl; return 1; } bool result = false; if (argc == 3) { // login has been performed by some other means eg using the "interactive login" described in the documentation. ExchangeApi exchangeApi(argv[1]); exchangeApi.setSsoid(argv[2]); // we don't know whether or not the token is valid, assume it is. result = true; } else if (argc == 4) { ExchangeApi exchangeApi(argv[1]); result = exchangeApi.login(argv[2], argv[3]); } else if (argc == 5) { ExchangeApi exchangeApi; result = exchangeApi.login(argv[1], argv[2], argv[3], argv[4]); } if (result) { std::cerr << "SUCCESS" << std::endl; } else { std::cerr << "FAILED" << std::endl; } return 0; }
32.02439
120
0.5377
Sherlock92
f8a57148fd7b220ab8f4df85c3196b2b642a64cf
212
hpp
C++
firmware/robot2015/src-ctrl/modules/task-signals.hpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
1
2018-09-25T20:28:58.000Z
2018-09-25T20:28:58.000Z
firmware/robot2015/src-ctrl/modules/task-signals.hpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
null
null
null
firmware/robot2015/src-ctrl/modules/task-signals.hpp
JNeiger/robocup-firmware
c1bfd4ba24070eaa4e012fdc88aa468aafcc2e4e
[ "Apache-2.0" ]
null
null
null
#pragma once // This is where the signals for different threads are defined for use across // mutliple files static const uint32_t MAIN_TASK_CONTINUE = 1 << 0; static const uint32_t SUB_TASK_CONTINUE = 1 << 1;
26.5
77
0.764151
JNeiger
f8ab1ef69e0673149c22f655a1e406346603a62a
1,936
ipp
C++
include/dracosha/validator/detail/member_helper.ipp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
27
2020-09-18T13:45:33.000Z
2022-03-16T21:14:37.000Z
include/dracosha/validator/detail/member_helper.ipp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
7
2020-08-07T21:48:14.000Z
2021-01-14T12:25:37.000Z
include/dracosha/validator/detail/member_helper.ipp
evgeniums/cpp-validator
e4feccdce19c249369ddb631571b60613926febd
[ "BSL-1.0" ]
1
2021-03-30T09:17:58.000Z
2021-03-30T09:17:58.000Z
/** @copyright Evgeny Sidorov 2020 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ /****************************************************************************/ /** @file validator/detail/member_helper.ipp * * Defines helpers to invoke member methods. * */ /****************************************************************************/ #ifndef DRACOSHA_VALIDATOR_MEMBER_HELPER_IPP #define DRACOSHA_VALIDATOR_MEMBER_HELPER_IPP #include <dracosha/validator/config.hpp> #include <dracosha/validator/member.hpp> #include <dracosha/validator/member_with_name.hpp> DRACOSHA_VALIDATOR_NAMESPACE_BEGIN namespace detail { template <typename T1> template <typename MemberT> auto member_helper_1arg_t<T1,hana::when< ( std::is_constructible<concrete_phrase,T1>::value && !hana::is_a<operator_tag,T1> ) >>::operator () ( MemberT&& member, T1&& name ) const { return make_member_with_name(std::forward<MemberT>(member),std::forward<T1>(name)); } template <typename T1, typename T2> template <typename MemberT> auto member_helper_2args_t<T1,T2,hana::when<std::is_enum<std::decay_t<T2>>::value>>::operator () ( MemberT&& member, T1&& name, T2&& grammar_category ) const { return make_member_with_name(std::forward<MemberT>(member),concrete_phrase(std::forward<T1>(name),std::forward<T2>(grammar_category))); } template <typename ... Args> template <typename MemberT> auto member_helper_t<Args...>::operator () ( MemberT&& member, Args&&... args ) const { return make_member_with_name(std::forward<MemberT>(member),concrete_phrase(std::forward<Args>(args)...)); } } DRACOSHA_VALIDATOR_NAMESPACE_END #endif // DRACOSHA_VALIDATOR_MEMBER_HELPER_IPP
25.473684
139
0.627066
evgeniums
f8abf6fa7f6156c5588988b2f3e8d6d0c56b2cfa
259
hpp
C++
Classes/Fish.hpp
1994/AvoidTuitle
6d9a37e2bf799efb299ae415afd2b22f6f9280be
[ "MIT" ]
null
null
null
Classes/Fish.hpp
1994/AvoidTuitle
6d9a37e2bf799efb299ae415afd2b22f6f9280be
[ "MIT" ]
null
null
null
Classes/Fish.hpp
1994/AvoidTuitle
6d9a37e2bf799efb299ae415afd2b22f6f9280be
[ "MIT" ]
null
null
null
// // Fish.hpp // seven // // Created by rimi on 15/6/12. // // #ifndef Fish_cpp #define Fish_cpp #include <stdio.h> #include "cocos2d.h" USING_NS_CC; class Fish:public Sprite { public: static Sprite * createFish(int type); }; #endif /* Fish_cpp */
12.333333
41
0.648649
1994
f8ac710dbc05ff317d36287456057ad5add0a544
448
cpp
C++
codeforces/edu94/str_sim.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codeforces/edu94/str_sim.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codeforces/edu94/str_sim.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
//#define _GLIBCXX_DEBUG #include <iostream> #include <cassert> #include <cstring> #include <vector> #include <algorithm> #include <string> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--){ int n; cin >> n; string s; cin >> s; for(int i=0 ; i<n ; i++) cout << s[n-1]; cout << "\n"; } return 0; }
16
37
0.513393
udayan14
f8acf57b80159041d0f4a9587836e99a603f06a5
4,567
cpp
C++
Client/AudioInterface.cpp
DylanWalseth/RTSLab8
d08049ef3bc876dfc16774f6f5d0e840e075be81
[ "MIT" ]
null
null
null
Client/AudioInterface.cpp
DylanWalseth/RTSLab8
d08049ef3bc876dfc16774f6f5d0e840e075be81
[ "MIT" ]
null
null
null
Client/AudioInterface.cpp
DylanWalseth/RTSLab8
d08049ef3bc876dfc16774f6f5d0e840e075be81
[ "MIT" ]
null
null
null
/* * AudioInterface.cpp * * Created on: Apr 18, 2015 * Author: Walter Schilling * This is the implementation of the audio Interface. It will manage the system. */ #include "AudioInterface.h" /** * This is the constructor for the class. It will instantiate a new instance of the class. * @param deviceName This is the name of the device. A typical name might be "plughw:1" * @param samplingRate This is the sampling rate for the audio sampls. Typical rates are 11000, 22050, and 44100. * @param channels This is the number of channels. Typically this is 1 or 2. * @param direction This is the direction. It is either SND_PCM_STREAM_CAPTURE or SND_PCM_STREAM_PLAYBACK */ AudioInterface::AudioInterface(char* deviceName, unsigned int samplingRate, int channels, snd_pcm_stream_t direction) { // Determine the length of the device name and allocate memory for it. int deviceLength = strlen(deviceName); this->deviceName = (char*) malloc(deviceLength + 1); // Initialize the buffer with the device name. strcpy(this->deviceName, deviceName); this->samplingRate = samplingRate; this->channels = channels; this->direction = direction; this->handle = NULL; this->params = NULL; frames = DEFAULT_FRAME_SIZE; } /** * This is the destructor. It will clear all allocated space. */ AudioInterface::~AudioInterface() { free(this->deviceName); } /** * This method will close the given device so it is no longer accessible. */ void AudioInterface::close() { // close the hardware we are connected to. snd_pcm_drain(handle); snd_pcm_close(handle); } /** * This method will open the given device so that it can be accessed. */ void AudioInterface::open() { int rc; // This variable is to be used to store the return code from various calls. int dir; /* Open PCM device. */ snd_pcm_open(&handle, this->deviceName, this->direction, 0); /* Allocate a hardware parameters object. */ snd_pcm_hw_params_alloca(&params); /* Fill it in with default values. */ snd_pcm_hw_params_any(handle, params); /* Set the desired hardware parameters. */ /* Interleaved mode */ snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED); /* Signed 16-bit little-endian format */ snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE); /* Two channels (stereo) */ snd_pcm_hw_params_set_channels(handle, params, this->channels); // Set the sampling rate appropriately. snd_pcm_hw_params_set_rate_near(handle, params, &(this->samplingRate), &dir); /* Set period size to the given number of frames. */ snd_pcm_hw_params_set_period_size_near(handle, params, &frames, &dir); /* Write the parameters to the driver */ rc = snd_pcm_hw_params(handle, params); if (rc < 0) { fprintf(stderr, "unable to set hw parameters: %s\n", snd_strerror(rc)); exit(1); } } /** * This method will determine, based upon the size of each frame and the number of frames between interrupts the required size of the buffer that is to store the data. * @return */ int AudioInterface::getRequiredBufferSize() { int dir; int size; snd_pcm_hw_params_get_period_size(params, &frames, &dir); size = frames * this->channels * 2; /* 2 bytes/sample */ return size; } /** * This method will read data from the given sound device into the buffer. * @param buffer This is a pointer to a buffer that is to be written into. The calee is responsible for providing this buffer. The buffer must be the isze calculated by the getRequiredBufferisze() method. * @return The return will be the number of bytes written into the buffer. */ int AudioInterface::read(char* buffer) { return snd_pcm_readi(handle, buffer, frames); } /** * This method will write data to the soundcard for playback. * @param buffer This is the buffer that is to be written. It must be of size getRequiredBufferisze(). * @param bufferLength This is the number of valid entries in the buffer. */ void AudioInterface::write(char* buffer, int bufferLength) { int rc; // This variable is to be used to store the return code from various calls. int frames = bufferLength / (2 * this->channels); if (bufferLength > 0) { // Write the data to the soundcard. rc = snd_pcm_writei(this->handle, buffer, frames); if (rc == -EPIPE) { /* EPIPE means underrun */ fprintf(stderr, "underrun occurred\n"); snd_pcm_prepare(this->handle); } else if (rc < 0) { fprintf(stderr, "error from writei: %s\n", snd_strerror(rc)); } else if (rc != (int) frames) { fprintf(stderr, "short write, write %d frames\n", rc); } } }
33.580882
206
0.722794
DylanWalseth
f8af877885d6c04d94b7f300a55536bbf663bb09
1,446
cpp
C++
HAPI_Start/TileMap.cpp
DamienHenderson/GEC-Engine
8d1e89c3dc35adaf65e84de2594c715c600e4681
[ "MIT" ]
null
null
null
HAPI_Start/TileMap.cpp
DamienHenderson/GEC-Engine
8d1e89c3dc35adaf65e84de2594c715c600e4681
[ "MIT" ]
null
null
null
HAPI_Start/TileMap.cpp
DamienHenderson/GEC-Engine
8d1e89c3dc35adaf65e84de2594c715c600e4681
[ "MIT" ]
null
null
null
#include "TileMap.hpp" TileMap::TileMap(const HAPISPACE::CHapiXMLNode& node) { } TileMap::~TileMap() { } void TileMap::Load(const HAPISPACE::CHapiXMLNode & node, Visualisation& vis) { int x_chunks{ 0 }, y_chunks{ 0 }; for (auto& attrib : node.GetAttributes()) { if (attrib.GetName() == "x_chunks") { x_chunks = attrib.AsInt(); } else if (attrib.GetName() == "y_chunks") { y_chunks = attrib.AsInt(); } } chunks_.resize(y_chunks); for (auto& row : chunks_) { row.resize(x_chunks); } for (auto& iter : node.GetChildren()) { if (iter->GetName() == "TileDefs") { // g_tile_defs.LoadDefinitions(*iter); } if (iter->GetName() == "Chunk") { s32 x{ 0 }, y{ 0 }; for (auto& attrib : iter->GetAttributes()) { if (attrib.GetName() == "x") { x = attrib.AsInt(); } if (attrib.GetName() == "y") { y = attrib.AsInt(); } } chunks_[y][x].Load(*iter); std::stringstream ss; ss << "Chunk_" << x << "_" << y; chunks_[y][x].GenerateChunkSprite(vis, ss.str()); } } } void TileMap::Render(Visualisation & vis) { for (auto& row : chunks_) { for (auto& column : row) { column.Render(vis); } } } TileDefinition TileMap::GetTileDefinition(const vec2<f32>& pos) const { for (auto& row : chunks_) { for (auto& column : row) { if (column.Contains(pos)) { return column.GetTileDefinition(pos); } } } return TileDefinition(); }
16.247191
76
0.582296
DamienHenderson
f8b65a0dbc3a2a7deb80efd896e132f219e3831a
1,809
cpp
C++
gfg-DSA/linear-recurrence.cpp
shashankkmciv18/dsa
6feba269292d95d36e84f1adb910fe2ed5467f71
[ "MIT" ]
54
2020-07-31T14:50:23.000Z
2022-03-14T11:03:02.000Z
gfg-DSA/linear-recurrence.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
null
null
null
gfg-DSA/linear-recurrence.cpp
SahilMund/dsa
a94151b953b399ea56ff50cf30dfe96100e8b9a7
[ "MIT" ]
30
2020-08-15T17:39:02.000Z
2022-03-10T06:50:18.000Z
// Linear Recurrence Method for calculating high order numbers like // F(100) in fibonacci series. // Steps to Proceed : // Step 1: Determine K, the number of terms F(i) depends. // Ex- K=2 for fibonacci series i.e F(i) = F(i-1) +F(i-2) // Step: 2 Determine initial values i.e F(1) and F(2) // Ex- In fibonacci series, F(1) = 1, F(2) = 1 // Define a column vector Fi as a K X 1 Matrix // Step: 3 Determine Transformation Matrix // Where T is a K x K matrix whose last row is a vector [Ck , Ck-1 .... c1] === F(1) , F(2) ... // Note: the ith row is a zero vector except that its (i+1)th element is 1! // Step: 4 Determine Fn i.e F2=F1*T ==> Fn = T^n-1 * F1 // Computing T^n-1 efficiently can be done in O(lgn) and Multyplying takes O(K^3) ==> O(K^3lgn) // #include <iostream> #include <vector> #define REP(i,n) for (int i = 0; i < n; i++) using namespace std; typedef long long ll; typedef vector < vector <int> > matrix; // Initializing 2D Array const ll MOD = 1000000007; const int K=2; // Computes A * B matrix mul(matrix A, matrix B) { matrix C(K+1, vector <ll> (K+1)); REP(i,K) REP(j,K) REP(k,K) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD; return C; } // Computes A^p matrix pow(matrix A, int p) { if( p==1) return A; if( p%2 ) { return mul(A, pow(A,p-1)); } matix X = pow(A, p/2); return mul(X,X); } int fib(n) { // Create Vector F1 vector <ll> F1(K+1); // Initialize F1 and F2 , if given F[1] = 1; F[2] = 1; // Create Matrix T matrix T(K+1, vector <ll> (K+1)); T[1][1] = 0, T[1][2] = 1; T[2][1] = 1, T[2][2] = 1; // Raise T to the power n-1 if( N == 1 ) { return 1; } T = pow(T,N-1); // result will the first row of T*F1 ll result = 0; REP(i,k) result = (result + T[1][i] * F1[i]) % MOD return result; }
24.780822
96
0.577114
shashankkmciv18
f8b7dd7896750564660235249a5471034fb074f5
811
hpp
C++
include/RED4ext/Types/generated/mesh/MeshImportedSnapPoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/mesh/MeshImportedSnapPoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/mesh/MeshImportedSnapPoint.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/ISerializable.hpp> #include <RED4ext/Types/generated/Matrix.hpp> #include <RED4ext/Types/generated/mesh/ImportedSnapTags.hpp> namespace RED4ext { namespace mesh { struct MeshImportedSnapPoint : ISerializable { static constexpr const char* NAME = "meshMeshImportedSnapPoint"; static constexpr const char* ALIAS = NAME; Matrix localToCloud; // 30 float range; // 70 uint8_t rotationAlignmentSteps; // 74 uint8_t unk75[0x78 - 0x75]; // 75 mesh::ImportedSnapTags snapTags; // 78 uint8_t unk98[0xA0 - 0x98]; // 98 }; RED4EXT_ASSERT_SIZE(MeshImportedSnapPoint, 0xA0); } // namespace mesh } // namespace RED4ext
27.033333
68
0.738594
Cyberpunk-Extended-Development-Team
f8b83a348229825a74972f8adf91c24a60e3b00c
9,914
cpp
C++
artifact/storm/src/storm/storage/memorystructure/MemoryStructure.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/storage/memorystructure/MemoryStructure.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/storage/memorystructure/MemoryStructure.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/storage/memorystructure/MemoryStructure.h" #include <iostream> #include "storm/logic/Formulas.h" #include "storm/utility/macros.h" #include "storm/storage/memorystructure/SparseModelMemoryProduct.h" #include "storm/exceptions/InvalidOperationException.h" namespace storm { namespace storage { MemoryStructure::MemoryStructure(TransitionMatrix const& transitionMatrix, storm::models::sparse::StateLabeling const& memoryStateLabeling, std::vector<uint_fast64_t> const& initialMemoryStates) : transitions(transitionMatrix), stateLabeling(memoryStateLabeling), initialMemoryStates(initialMemoryStates) { // intentionally left empty } MemoryStructure::MemoryStructure(TransitionMatrix&& transitionMatrix, storm::models::sparse::StateLabeling&& memoryStateLabeling, std::vector<uint_fast64_t>&& initialMemoryStates) : transitions(std::move(transitionMatrix)), stateLabeling(std::move(memoryStateLabeling)), initialMemoryStates(std::move(initialMemoryStates)) { // intentionally left empty } MemoryStructure::TransitionMatrix const& MemoryStructure::getTransitionMatrix() const { return transitions; } storm::models::sparse::StateLabeling const& MemoryStructure::getStateLabeling() const { return stateLabeling; } std::vector<uint_fast64_t> const& MemoryStructure::getInitialMemoryStates() const { return initialMemoryStates; } uint_fast64_t MemoryStructure::getNumberOfStates() const { return transitions.size(); } uint_fast64_t MemoryStructure::getSuccessorMemoryState(uint_fast64_t const& currentMemoryState, uint_fast64_t const& modelTransitionIndex) const { for (uint_fast64_t successorMemState = 0; successorMemState < getNumberOfStates(); ++successorMemState) { boost::optional<storm::storage::BitVector> const& matrixEntry = transitions[currentMemoryState][successorMemState]; if ((matrixEntry) && matrixEntry.get().get(modelTransitionIndex)) { return successorMemState; } } STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "The successor memorystate for the given transition could not be found."); return getNumberOfStates(); } MemoryStructure MemoryStructure::product(MemoryStructure const& rhs) const { uint_fast64_t lhsNumStates = this->getTransitionMatrix().size(); uint_fast64_t rhsNumStates = rhs.getTransitionMatrix().size(); uint_fast64_t resNumStates = lhsNumStates * rhsNumStates; // Transition matrix TransitionMatrix resultTransitions(resNumStates, std::vector<boost::optional<storm::storage::BitVector>>(resNumStates)); uint_fast64_t resState = 0; for (uint_fast64_t lhsState = 0; lhsState < lhsNumStates; ++lhsState) { for (uint_fast64_t rhsState = 0; rhsState < rhsNumStates; ++rhsState) { assert (resState == (lhsState * rhsNumStates) + rhsState); auto& resStateTransitions = resultTransitions[resState]; for (uint_fast64_t lhsTransitionTarget = 0; lhsTransitionTarget < lhsNumStates; ++lhsTransitionTarget) { auto& lhsTransition = this->getTransitionMatrix()[lhsState][lhsTransitionTarget]; if (lhsTransition) { for (uint_fast64_t rhsTransitionTarget = 0; rhsTransitionTarget < rhsNumStates; ++rhsTransitionTarget) { auto& rhsTransition = rhs.getTransitionMatrix()[rhsState][rhsTransitionTarget]; if (rhsTransition) { uint_fast64_t resTransitionTarget = (lhsTransitionTarget * rhsNumStates) + rhsTransitionTarget; resStateTransitions[resTransitionTarget] = rhsTransition.get() & lhsTransition.get(); // If it is not possible to take the considered transition w.r.t. the considered model, we can delete it. if (resStateTransitions[resTransitionTarget]->empty()) { resStateTransitions[resTransitionTarget] = boost::none; } } } } } ++resState; } } // State Labels storm::models::sparse::StateLabeling resultLabeling(resNumStates); for (std::string lhsLabel : this->getStateLabeling().getLabels()) { storm::storage::BitVector const& lhsLabeledStates = this->getStateLabeling().getStates(lhsLabel); storm::storage::BitVector resLabeledStates(resNumStates, false); for (auto const& lhsState : lhsLabeledStates) { for (uint_fast64_t rhsState = 0; rhsState < rhsNumStates; ++rhsState) { resState = (lhsState * rhsNumStates) + rhsState; resLabeledStates.set(resState, true); } } resultLabeling.addLabel(lhsLabel, std::move(resLabeledStates)); } for (std::string rhsLabel : rhs.getStateLabeling().getLabels()) { STORM_LOG_THROW(!resultLabeling.containsLabel(rhsLabel), storm::exceptions::InvalidOperationException, "Failed to build the product of two memory structures: State labelings are not disjoint as both structures contain the label " << rhsLabel << "."); storm::storage::BitVector const& rhsLabeledStates = rhs.getStateLabeling().getStates(rhsLabel); storm::storage::BitVector resLabeledStates(resNumStates, false); for (auto const& rhsState : rhsLabeledStates) { for (uint_fast64_t lhsState = 0; lhsState < lhsNumStates; ++lhsState) { resState = (lhsState * rhsNumStates) + rhsState; resLabeledStates.set(resState, true); } } resultLabeling.addLabel(rhsLabel, std::move(resLabeledStates)); } // Initial States std::vector<uint_fast64_t> resultInitialMemoryStates; STORM_LOG_THROW(this->getInitialMemoryStates().size() == rhs.getInitialMemoryStates().size(), storm::exceptions::InvalidOperationException, "Tried to build the product of two memory structures that consider a different number of initial model states."); resultInitialMemoryStates.reserve(this->getInitialMemoryStates().size()); auto lhsStateIt = this->getInitialMemoryStates().begin(); auto rhsStateIt = rhs.getInitialMemoryStates().begin(); for (; lhsStateIt != this->getInitialMemoryStates().end(); ++lhsStateIt, ++rhsStateIt) { resultInitialMemoryStates.push_back(*lhsStateIt * rhsNumStates + *rhsStateIt); } return MemoryStructure(std::move(resultTransitions), std::move(resultLabeling), std::move(resultInitialMemoryStates)); } template <typename ValueType, typename RewardModelType> SparseModelMemoryProduct<ValueType, RewardModelType> MemoryStructure::product(storm::models::sparse::Model<ValueType, RewardModelType> const& sparseModel) const { return SparseModelMemoryProduct<ValueType, RewardModelType>(sparseModel, *this); } std::string MemoryStructure::toString() const { std::stringstream stream; stream << "Memory Structure with " << getNumberOfStates() << " states: " << std::endl; for (uint_fast64_t state = 0; state < getNumberOfStates(); ++state) { stream << "State " << state << ": Labels = {"; bool firstLabel = true; for (auto const& label : getStateLabeling().getLabelsOfState(state)) { if (!firstLabel) { stream << ", "; } firstLabel = false; stream << label; } stream << "}, Transitions: " << std::endl; for (uint_fast64_t transitionTarget = 0; transitionTarget < getNumberOfStates(); ++transitionTarget) { stream << "\t From " << state << " to " << transitionTarget << ": \t"; auto const& transition = getTransitionMatrix()[state][transitionTarget]; if (transition) { stream << *transition; } else { stream << "false"; } stream << std::endl; } } return stream.str(); } template SparseModelMemoryProduct<double> MemoryStructure::product(storm::models::sparse::Model<double> const& sparseModel) const; template SparseModelMemoryProduct<double, storm::models::sparse::StandardRewardModel<storm::Interval>> MemoryStructure::product(storm::models::sparse::Model<double, storm::models::sparse::StandardRewardModel<storm::Interval>> const& sparseModel) const; template SparseModelMemoryProduct<storm::RationalNumber> MemoryStructure::product(storm::models::sparse::Model<storm::RationalNumber> const& sparseModel) const; template SparseModelMemoryProduct<storm::RationalFunction> MemoryStructure::product(storm::models::sparse::Model<storm::RationalFunction> const& sparseModel) const; } }
60.084848
332
0.608029
glatteis
f8b86f2c91c7f4bc5730030b44b8d4a30dc1daa6
10,121
cpp
C++
src/Kocmoc.cpp
SimonWallner/kocmoc-demo
a4f769b5ed7592ce50a18ab93c603d4371fbd291
[ "MIT", "Unlicense" ]
12
2015-01-21T07:02:23.000Z
2021-11-15T19:47:53.000Z
src/Kocmoc.cpp
SimonWallner/kocmoc-demo
a4f769b5ed7592ce50a18ab93c603d4371fbd291
[ "MIT", "Unlicense" ]
null
null
null
src/Kocmoc.cpp
SimonWallner/kocmoc-demo
a4f769b5ed7592ce50a18ab93c603d4371fbd291
[ "MIT", "Unlicense" ]
3
2017-03-04T08:50:46.000Z
2020-10-23T14:27:04.000Z
#include "Kocmoc.hpp" #include "Context.hpp" #include "Property.hpp" #include "Exception.hpp" #include "ImageLoader.hpp" #include "KocmocLoader.hpp" #include "utility.hpp" #include "ShaderManager.hpp" #include "AudioPlayer.hpp" #include "AnimationSystem.hpp" #include <gtx/spline.hpp> using namespace kocmoc; Kocmoc* Kocmoc::instance = NULL; Kocmoc& Kocmoc::getInstance(void) { if(!instance) instance = new Kocmoc(); return *instance; } void Kocmoc::Destroy() { // static delete instance; instance = NULL; } Kocmoc::Kocmoc() : useUserCamera(false) { glfwGetMousePos(&mouseOldX, &mouseOldY); showGizmos = util::Property("debugShowGizmo"); } Kocmoc::~Kocmoc() { delete scene; delete gamepad; } bool Kocmoc::isRunning(){ return running; } void Kocmoc::stop(){ running = false; } void Kocmoc::init() { // user camera camera = new FilmCamera(vec3(0.0f, 0.0f, 15.0f), //eye vec3(0, 0, 0), // target vec3(0, 1, 0)); // up float aspectRatio = (float)util::Property("aspectRatio") / ((float)Context::getInstance().width / (float)Context::getInstance().height); if (aspectRatio > 1) // horizontal letter box camera->setGateInPixel(Context::getInstance().width, (float)Context::getInstance().height / aspectRatio); else camera->setGateInPixel((float)Context::getInstance().width * aspectRatio, Context::getInstance().height); camera->setFocalLength(util::Property("cameraFocalLength35")); camera->setFilterMarginInPixel(util::Property("horizontalMargin"), util::Property("verticalMargin")); camera->setupGizmo(); camera->updateMatrixes(); // animation cameras --- cam 1 -------------------------------------------- cam1 = new FilmCamera(vec3(0.0f, 0.0f, 15.0f), //eye vec3(0, 0, 0), // target vec3(0, 1, 0)); // up if (aspectRatio > 1) // horizontal letter box cam1->setGateInPixel(Context::getInstance().width, (float)Context::getInstance().height / aspectRatio); else cam1->setGateInPixel((float)Context::getInstance().width * aspectRatio, Context::getInstance().height); cam1->setFocalLength(util::Property("cameraFocalLength35")); cam1->setFilterMarginInPixel(util::Property("horizontalMargin"), util::Property("verticalMargin")); cam1->updateMatrixes(); // animation cameras --- cam 2 -------------------------------------------- cam2 = new FilmCamera(vec3(0.0f, 0.0f, 15.0f), //eye vec3(0, 0, 0), // target vec3(0, 1, 0)); // up if (aspectRatio > 1) // horizontal letter box cam2->setGateInPixel(Context::getInstance().width, (float)Context::getInstance().height / aspectRatio); else cam2->setGateInPixel((float)Context::getInstance().width * aspectRatio, Context::getInstance().height); cam2->setFocalLength(util::Property("cameraFocalLength35")); cam2->setFilterMarginInPixel(util::Property("horizontalMargin"), util::Property("verticalMargin")); cam2->updateMatrixes(); // ortho cam orthoCam = new OrthoCam(vec3(0, 0, 0), vec3(-1, -1, -1), vec3(0, 1, 0)); orthoCam->updateMatrixes(); scene = new KocmocScene(); ship = KocmocLoader::getInstance().load(util::Property("modelName")); scene->add(ship); scene->add(util::generator::generateStars()); shadowShader = ShaderManager::getInstance().load("shadow.vert", "shadow.frag"); if (showGizmos) scene->add(util::generator::generateGizmo()); { /* inputs */ gamepad = new input::Gamepad(camera); useGamepad = gamepad->init(); useMouse = util::Property("enableMouse"); if (useMouse && util::Property("captureMouse")) glfwDisable(GLFW_MOUSE_CURSOR); } fbo = new FrameBuffer(camera->getFrameWidth(), camera->getFrameHeight(), camera->getGateWidth(), camera->getGateHeight()); fbo->setupShader(); shadowMap = new ShadowMap(util::Property("shadowMapWidth"), util::Property("shadowMapHeight")); AudioPlayer::getInstance().play("kocmoc.ogg"); clock = new Clock(); if (util::Property("useFixedFrameRate")) clock->start(1.0/(float)util::Property("fixedFrameRate")); else clock->start(); animationClock = new AnimationClock(clock); AnimationSystem::getInstance().parseAnimationFile(); overlayCam = new OverlayCam(Context::getInstance().width, Context::getInstance().height); overlayCam->updateMatrixes(); black = new ImageOverlay("black.png", Context::getInstance().width, Context::getInstance().height); title = new ImageOverlay("title.png", 800, 400); credits = new ImageOverlay("credits.png", 800, 400); credits2 = new ImageOverlay("credits2.png", 800, 400); credits3 = new ImageOverlay("credits3.png", 800, 400); running = true; animationClock->play(); } void Kocmoc::start() { while (running) { clock->awaitSchedule(); clock->tick(); timer.tic(); // Check if the window has been closed running = running && glfwGetWindowParam( GLFW_OPENED ); pollKeyboard(); if (useGamepad) gamepad->poll(); if (useMouse) pollMouse(); // update stuff ------------------ AnimationSystem &asi = AnimationSystem::getInstance(); mat4 transform = glm::gtx::transform::rotate(2.0f * asi.getScalar(animationClock->getTime(), "time"), 1.0f, 0.0f, 0.0f); transform = glm::gtx::transform::rotate(15.0f * asi.getScalar(animationClock->getTime(), "time"), 1.0f, 0.3f, 0.2f) * transform; transform = glm::gtx::transform::translate(vec3(1, 0, 0) * 3.0f * asi.getScalar(animationClock->getTime(), "time")) * transform; ship->setTransformation(transform); orthoCam->setFocus(vec3(1, 0, 0) * 3.0f * asi.getScalar(animationClock->getTime(), "time")); orthoCam->updateMatrixes(); black->setOpacity(asi.getScalar(animationClock->getTime(), "black_opacity")); title->setOpacity(asi.getScalar(animationClock->getTime(), "title_opacity")); credits->setOpacity(asi.getScalar(animationClock->getTime(), "credits_opacity")); credits2->setOpacity(asi.getScalar(animationClock->getTime(), "credits2_opacity")); credits3->setOpacity(asi.getScalar(animationClock->getTime(), "credits3_opacity")); cam1->setPosition(asi.getVec3(animationClock->getTime(), "cam1_position")); cam1->setTargetPosition(asi.getVec3(animationClock->getTime(), "cam1_target")); cam1->setUpVector(asi.getVec3(animationClock->getTime(), "cam1_up")); cam1->setFocalLength(asi.getScalar(animationClock->getTime(), "cam1_focalLength")); cam2->setPosition(asi.getVec3(animationClock->getTime(), "cam2_position")); cam2->setTargetPosition(asi.getVec3(animationClock->getTime(), "cam2_target")); cam2->setUpVector(asi.getVec3(animationClock->getTime(), "cam2_up")); cam2->setFocalLength(asi.getScalar(animationClock->getTime(), "cam2_focalLength")); camera->updateMatrixes(); cam1->updateMatrixes(); cam2->updateMatrixes(); // drawing stuff --------------- // shadow map glDisable(GL_FRAMEBUFFER_SRGB); glBindFramebuffer(GL_FRAMEBUFFER, shadowMap->getFBOHandle()); glViewport(0, 0, shadowMap->width, shadowMap->height); glClear(GL_DEPTH_BUFFER_BIT); ship->draw(orthoCam, shadowShader); glEnable(GL_FRAMEBUFFER_SRGB); glBindFramebuffer(GL_FRAMEBUFFER, fbo->getFBOHandle()); glViewport(0, 0, fbo->frameWidth, fbo->frameHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, shadowMap->getTextureHandle()); draw(); glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, Context::getInstance().width, Context::getInstance().height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (Context::getInstance().getWireframe()) { Context::getInstance().setWireframe(false); fbo->drawFBO(); Context::getInstance().setWireframe(true); } else fbo->drawFBO(); drawOverlays(); Context::getInstance().swapBuffers(); if (util::Property("recordSequence")) ImageLoader::getInstance().screenShot(true); } } void Kocmoc::draw() { if (useUserCamera) scene->draw(camera); else { if (AnimationSystem::getInstance().getScalar(animationClock->getTime(), "cam1_selector") > 0.0f) scene->draw(cam1); else scene->draw(cam2); } } void Kocmoc::drawOverlays() { //if (showGizmos) // camera->drawGizmo(); glDisable(GL_DEPTH_TEST); black->draw(); title->draw(); credits->draw(); credits2->draw(); credits3->draw(); glEnable(GL_DEPTH_TEST); } void Kocmoc::pollKeyboard(void) { running = running && !glfwGetKey( GLFW_KEY_ESC ); if (glfwGetKey(GLFW_KEY_F1)) std::cout << "---------------------------------------------------------" << std::endl << "\t F1: this help dialog" <<std::endl << "\t F3: toggle wireframe" << std::endl << "\t F4: print frametime/fps" << std::endl << "\t F5: toggle non-planar projection post" << std::endl << "\t F6: toggle vignetting post" << std::endl << "\t F7: toggle color correction post" << std::endl << "\t '.': take screenshot" << std::endl << "\t R: reload shaders/textures/etc..." << std::endl; if (glfwGetKey(GLFW_KEY_F3)) Context::getInstance().setWireframe(!Context::getInstance().getWireframe()); if (glfwGetKey(GLFW_KEY_F4)) timer.print(); if (glfwGetKey(GLFW_KEY_F5)) { fbo->toggleProjection(); reload(); } if (glfwGetKey(GLFW_KEY_F6)) { fbo->toggleVignetting(); reload(); } if (glfwGetKey(GLFW_KEY_F7)) { fbo->toggleColorCorrection(); reload(); } if (glfwGetKey('.')) ImageLoader::getInstance().screenShot(); if (glfwGetKey('R')) animationClock->setTime(0.0); if (glfwGetKey('W')) camera->dolly(vec3(0, 0, 4.0f) * (float)clock->lastFrameDuration()); if (glfwGetKey('S')) camera->dolly(vec3(0, 0, -4.0f) * (float)clock->lastFrameDuration()); if (glfwGetKey('A')) camera->dolly(vec3(-4.0f, 0, 0.0f) * (float)clock->lastFrameDuration()); if (glfwGetKey('D')) camera->dolly(vec3(4.0f, 0, 0.0f) * (float)clock->lastFrameDuration()); if (glfwGetKey(GLFW_KEY_SPACE)) useUserCamera = !useUserCamera; } void Kocmoc::pollMouse() { int newX, newY; glfwGetMousePos(&newX, &newY); camera->tumble((newX - mouseOldX) * (float)clock->lastFrameDuration() * 0.1f , (newY - mouseOldY) * -(float)clock->lastFrameDuration() * 0.1f); mouseOldX = newX; mouseOldY = newY; } void Kocmoc::reload() { fbo->setupShader(); title->setupShader(); black->setupShader(); }
28.27095
137
0.686691
SimonWallner
f8b8b475c29be7330f546a5b38ab661e443ef5a5
765
cc
C++
2004-class/day2/object-ret.cc
tibbetts/inside-c
a72f6d44f15343e81b35da8edadd0e9c63315d40
[ "MIT" ]
18
2015-01-19T04:18:49.000Z
2022-03-04T06:22:44.000Z
2004-class/day2/object-ret.cc
tibbetts/inside-c
a72f6d44f15343e81b35da8edadd0e9c63315d40
[ "MIT" ]
null
null
null
2004-class/day2/object-ret.cc
tibbetts/inside-c
a72f6d44f15343e81b35da8edadd0e9c63315d40
[ "MIT" ]
4
2020-02-19T22:29:23.000Z
2021-09-22T16:45:52.000Z
#include "stdio.h" class twofield { private: int field1, field2; public: explicit twofield(int f); // Copy constructor. twofield(const twofield &of); ~twofield(); void setField(int f); int getField() const; }; twofield fromint(int j) { twofield of(j); return of; } int main(int argc, char **argv) { int i = fromint(13).getField(); return i; } void twofield::setField(int f) { this->field1 = f; } int twofield::getField() const { return this->field1; } twofield::twofield(int f) { field1 = f; printf("initial value of field was %d.\n", field1); } twofield::twofield(const twofield &of) { field1 = of.field1; } twofield::~twofield() { printf("Last value of field was %d.\n", field1); }
16.630435
55
0.616993
tibbetts
f8bb1144ae4497943224251410733206e4be5bd4
2,233
cpp
C++
input/input_state.cpp
Ced2911/native
41fd5dcc905592a78017ffbb40eac39b1fdf994a
[ "MIT" ]
2
2016-01-22T20:58:08.000Z
2018-05-02T19:01:30.000Z
input/input_state.cpp
Ced2911/native
41fd5dcc905592a78017ffbb40eac39b1fdf994a
[ "MIT" ]
null
null
null
input/input_state.cpp
Ced2911/native
41fd5dcc905592a78017ffbb40eac39b1fdf994a
[ "MIT" ]
null
null
null
#include "input/input_state.h" #include "input/keycodes.h" const char *GetDeviceName(int deviceId) { switch (deviceId) { case DEVICE_ID_DEFAULT: return "built-in"; case DEVICE_ID_KEYBOARD: return "kbd"; case DEVICE_ID_PAD_0: return "pad"; case DEVICE_ID_X360_0: return "x360"; case DEVICE_ID_ACCELEROMETER: return "accelerometer"; default: return "unknown"; } } // Default pad mapping to button bits. Used for UI and stuff that doesn't use PPSSPP's key mapping system. int MapPadButtonFixed(int keycode) { switch (keycode) { case KEYCODE_BACK: return PAD_BUTTON_BACK; // Back case KEYCODE_MENU: return PAD_BUTTON_MENU; // Menu case KEYCODE_Z: case KEYCODE_SPACE: case KEYCODE_BUTTON_1: case KEYCODE_BUTTON_A: // same as KEYCODE_OUYA_BUTTON_O and KEYCODE_BUTTON_CROSS_PS3 return PAD_BUTTON_A; case KEYCODE_ESCAPE: case KEYCODE_BUTTON_2: case KEYCODE_BUTTON_B: // same as KEYCODE_OUYA_BUTTON_A and KEYCODE_BUTTON_CIRCLE_PS3: return PAD_BUTTON_B; case KEYCODE_DPAD_LEFT: return PAD_BUTTON_LEFT; case KEYCODE_DPAD_RIGHT: return PAD_BUTTON_RIGHT; case KEYCODE_DPAD_UP: return PAD_BUTTON_UP; case KEYCODE_DPAD_DOWN: return PAD_BUTTON_DOWN; default: return 0; } } uint32_t ButtonTracker::Update() { pad_buttons_ |= pad_buttons_async_set; pad_buttons_ &= ~pad_buttons_async_clear; return pad_buttons_; } void ButtonTracker::Process(const KeyInput &input) { int btn = MapPadButtonFixed(input.keyCode); if (btn == 0) return; // For now, use a fixed mapping. Good enough for the basics on most platforms. if (input.flags & KEY_DOWN) { pad_buttons_async_set |= btn; pad_buttons_async_clear &= ~btn; } if (input.flags & KEY_UP) { pad_buttons_async_set &= ~btn; pad_buttons_async_clear |= btn; } } ButtonTracker g_buttonTracker; void UpdateInputState(InputState *input, bool merge) { uint32_t btns = g_buttonTracker.Update(); input->pad_buttons = merge ? (input->pad_buttons | btns) : btns; input->pad_buttons_down = (input->pad_last_buttons ^ input->pad_buttons) & input->pad_buttons; input->pad_buttons_up = (input->pad_last_buttons ^ input->pad_buttons) & input->pad_last_buttons; } void EndInputState(InputState *input) { input->pad_last_buttons = input->pad_buttons; }
29.381579
106
0.765786
Ced2911
f8bc29486b5f537d77561fae8c45488df7e9dbbc
595
cpp
C++
ds18b20_ui.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
4
2021-01-11T13:50:25.000Z
2021-01-24T19:34:47.000Z
ds18b20_ui.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
1
2021-02-12T15:49:18.000Z
2021-02-12T16:50:55.000Z
ds18b20_ui.cpp
wintersteiger/wlmcd
7bdc184b875a0be652a0dd346fd9a598c14181d8
[ "MIT" ]
2
2021-01-11T13:53:18.000Z
2021-03-01T10:22:46.000Z
// Copyright (c) Christoph M. Wintersteiger // Licensed under the MIT License. #include "ds18b20_ui.h" DOUBLE_FIELD(UI::statusp, Temperature, "Temperature", DS18B20, "C", device.Temperature()); #define EMPTY() fields.push_back(new Empty(row++, col)); DS18B20UI::DS18B20UI(DS18B20 &ds18b20) { devices.insert(&ds18b20); size_t row = 1, col = 1; Add(new TimeField(statusp, row, col)); Add(new Label(UI::statusp, row++, col + 18, Name())); EMPTY(); fields.push_back(new Temperature(row, col, ds18b20)); } DS18B20UI::~DS18B20UI() { } void DS18B20UI::Layout() { UI::Layout(); }
19.193548
90
0.677311
wintersteiger
f8c6f4cd3c1e3104ca66f480bd5a5fc2e1af0046
589
cpp
C++
peg/bluebook/find_the_character.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
peg/bluebook/find_the_character.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
peg/bluebook/find_the_character.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <cctype> #include <iostream> #include <string> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); char wanted; cin >> wanted; cin.ignore(); string sentence; getline(cin, sentence, '.'); unsigned int occurrences {0}; for (auto symbol : sentence) { if (tolower(symbol) == tolower(wanted)) { ++occurrences; } } cout << sentence << '\n' << occurrences << '\n'; return 0; }
14.725
47
0.561969
Rkhoiwal
f8cb18e9c09a49bd20739273bcc05d9a1006a95e
1,819
cc
C++
ch3/send-more.cc
araya-andres/classic_computer_sci
3cb67563f10be75f586315d156506cf76e18f884
[ "Unlicense" ]
21
2017-10-12T05:03:09.000Z
2022-03-30T00:56:53.000Z
ch3/send-more.cc
araya-andres/classic_computer_sci
3cb67563f10be75f586315d156506cf76e18f884
[ "Unlicense" ]
1
2017-11-14T05:29:12.000Z
2017-11-14T17:28:48.000Z
ch3/send-more.cc
araya-andres/classic_computer_sci
3cb67563f10be75f586315d156506cf76e18f884
[ "Unlicense" ]
10
2018-03-30T14:37:48.000Z
2022-02-21T01:15:52.000Z
#include "common.h" #include "csp.h" #include "prettyprint.hpp" #include <iostream> #include <numeric> #include <string> #include <vector> std::vector<char> flatten(const std::vector<std::string>& v) { std::vector<char> flat; auto it = flat.begin(); for (const auto& s: v) it = flat.insert(it, s.cbegin(), s.cend()); return flat; } inline bool has_duplicate_values(const Assigment<char, int>& a) { return unique(map_values_to_vector(a)).size() < a.size(); } std::pair<int, bool> word_to_value(const std::string& w, const Assigment<char, int>& a) { int n = 0; for (auto ch : w) { auto it = a.find(ch); if (it == a.end()) return {0, false}; n = n * 10 + it->second; } return {n, true}; } struct SendMoreMoneyConstraint { bool contains(char c) const { return c == ch; } bool is_satisfied(const Assigment<char, int>& a) const { if (has_duplicate_values(a)) return false; if (a.size() < n) return true; std::vector<int> values; for (const auto& w: words) { const auto [value, ok] = word_to_value(w, a); if (!ok) return false; values.push_back(value); } auto sum = std::accumulate(values.cbegin(), values.cend() - 1, 0); return sum == values.back(); } char ch; size_t n; std::vector<std::string> words; }; int main() { std::vector<std::string> words{"send", "more", "money"}; Constraints<SendMoreMoneyConstraint> constraints; Domains<char, int> domains; auto variables = unique(flatten(words)); for (auto ch: variables) { constraints.push_back({ch, variables.size(), words}); domains.insert({ch, {0,1,2,3,4,5,6,7,8,9}}); } std::cout << backtracking_search(constraints, domains, variables) << '\n'; }
30.316667
89
0.598681
araya-andres
f8cf564ef2ef49d1b9c3391dff499ef55d9050bd
6,563
cpp
C++
2 course/EVM/lab_17/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
2 course/EVM/lab_17/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
2 course/EVM/lab_17/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
// -- системные либы -- // #include <windows.h> #include <vector> #include <algorithm> #include <random> #include <ctime> // Файлы заголовков C RunTime #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include "resource.h" // -- мои классы -- // #include "bitstring.h" #include "five.h" #define MAX_LOADSTRING 100 using namespace std; // Глобальные переменные: static HINSTANCE hInst; // -- текущий экземпляр приложения -- // static Five op1; // наши операнды static Five op2; static time_t seed = time(nullptr); static mt19937 mt(seed); // -- объявления функций, включенных в этот модуль кода -- // BOOL InitInstance(HINSTANCE, int); // -- инициализация главного окна -- // LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // -- обработчик сообщений для главного окна -- // LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM); // -- обработчик сообщений для диалогового окна "О программе" -- // void get_rand_op() // Генерируем операнды { uniform_int_distribution<int> dist_for_len(1, 5); uniform_int_distribution<int> dist_for_digit(0, 4); size_t len1 = dist_for_len(mt); size_t len2 = dist_for_len(mt); string op1_str = ""; for (size_t i = 0; i < len1; ++i) { op1_str += to_string(dist_for_digit(mt)); } string op2_str = ""; for (size_t i = 0; i < len2; ++i) { op2_str += to_string(dist_for_digit(mt)); } op1 = {op1_str}; op2 = {op2_str}; if (op1<op2) swap(op1,op2); } // -- главная функция -- // int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance) UNREFERENCED_PARAMETER(lpCmdLine) setlocale( LC_ALL, "rus" ); // Выполнить инициализацию приложения: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MAIN)); // -- для горячих клавиш -- // MSG msg; // Цикл основного сообщения: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return int(msg.wParam); } // -- создаем (инициализируем) главное окно программы -- // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // -- сохранить дескриптор экземпляра в глобальной переменной -- // HWND hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN),nullptr,DLGPROC(WndProc)); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // -- обрабатывает сообщения (сигналы, события) в главном окне -- // // WM_COMMAND - обработка меню приложения -- // // WM_DESTROY - ввести сообщение о выходе и вернуться -- // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId; static LOGFONTW lf; HFONT hFont1; Five res; switch (message) { case WM_INITDIALOG: // -- делаем шрифт побольше -- // lf.lfHeight = 24; lstrcpy(LPTSTR(&lf.lfFaceName), L"Microsoft Sans Serif"); hFont1 = CreateFontIndirect(&lf); // -- устанавливаем шрифт для текста -- // SendMessage(GetDlgItem(hWnd,IDC_OP1_TEXT), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDC_OP2_TEXT), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,ID_OP1), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,ID_OP2), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_ADD), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_SUB), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_MUL), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_DIV), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDC_RES_TEXT), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,ID_RES), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDB_FORWARD), WM_SETFONT, WPARAM(hFont1), TRUE ); SendMessage(GetDlgItem(hWnd,IDOK), WM_SETFONT, WPARAM(hFont1), TRUE ); get_rand_op(); SetDlgItemTextA(hWnd,ID_OP1,op1.toString().c_str()); SetDlgItemTextA(hWnd,ID_OP2,op2.toString().c_str()); return TRUE; case WM_COMMAND: wmId = LOWORD(wParam); // Разобрать выбор в меню: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, DLGPROC(About)); break; case IDM_EXIT: case IDCANCEL: case IDOK: DestroyWindow(hWnd); break; case IDB_FORWARD: get_rand_op(); SetDlgItemTextA(hWnd,ID_OP1,op1.toString().c_str()); SetDlgItemTextA(hWnd,ID_OP2,op2.toString().c_str()); SetDlgItemTextA(hWnd,ID_RES,""); break; case IDB_ADD: res = op1+op2; SetDlgItemTextA(hWnd,ID_RES,res.toString().c_str()); break; case IDB_SUB: res = op1-op2; SetDlgItemTextA(hWnd,ID_RES,res.toString().c_str()); break; case IDB_MUL: res = op1*op2; SetDlgItemTextA(hWnd,ID_RES,res.toString().c_str()); break; case IDB_DIV: if (size_t(std::count(op2.begin(),op2.end(),0)) != op2.get_size()) { res = op1/op2; SetDlgItemTextA(hWnd,ID_RES,res.toString().c_str()); } else { SetDlgItemTextA(hWnd,ID_RES,"zero divide"); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_DESTROY: PostQuitMessage(0); break; } return FALSE; } // Обработчик сообщений для окна "О программе". LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam) switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; }
30.668224
120
0.610544
SgAkErRu
f8d28173e818cf3982045871aab8aaadf5d44aa8
2,241
cpp
C++
GEngine/GRendererInfra/GRiRenderer.cpp
hegaoxiang/new---
1c65dce79fa292ff8d2f79fb4cf9d8e207a82be1
[ "Zlib" ]
null
null
null
GEngine/GRendererInfra/GRiRenderer.cpp
hegaoxiang/new---
1c65dce79fa292ff8d2f79fb4cf9d8e207a82be1
[ "Zlib" ]
null
null
null
GEngine/GRendererInfra/GRiRenderer.cpp
hegaoxiang/new---
1c65dce79fa292ff8d2f79fb4cf9d8e207a82be1
[ "Zlib" ]
null
null
null
#include "GRiRenderer.h" float GRiRenderer::AspectRatio() const { return static_cast<float>(mClientWidth) / mClientHeight; } HWND GRiRenderer::MainWnd()const { return mhMainWnd; } void GRiRenderer::SetClientWidth(int width) { mClientWidth = width; } void GRiRenderer::SetClientHeight(int height) { mClientHeight = height; } bool GRiRenderer::IsRunning() const { return mIsRunning; } void GRiRenderer::SetCamera(GRiCamera* cam) { pCamera = cam; } void GRiRenderer::SetScene(GScene* scene) { pScene = scene; } GRiRendererFactory* GRiRenderer::GetFactory() { return mFactory.get(); } void GRiRenderer::SyncTextures(std::unordered_map<std::string, std::unique_ptr<GRiTexture>>& mTextures) { pTextures.clear(); std::unordered_map<std::string, std::unique_ptr<GRiTexture>>::iterator i; for (i = mTextures.begin(); i != mTextures.end(); i++) { pTextures[i->first] = i->second.get(); } } void GRiRenderer::SyncMaterials(std::unordered_map<std::string, std::unique_ptr<GRiMaterial>>& mMaterials) { pMaterials.clear(); std::unordered_map<std::string, std::unique_ptr<GRiMaterial>>::iterator i; for (i = mMaterials.begin(); i != mMaterials.end(); i++) { pMaterials[i->first] = i->second.get(); } } void GRiRenderer::SyncMeshes(std::unordered_map<std::string, std::unique_ptr<GRiMesh>>& mMeshes) { pMeshes.clear(); std::unordered_map<std::string, std::unique_ptr<GRiMesh>>::iterator i; for (i = mMeshes.begin(); i != mMeshes.end(); i++) { pMeshes[i->first] = i->second.get(); } } void GRiRenderer::SyncSceneObjects(std::unordered_map<std::string, std::unique_ptr<GRiSceneObject>>& mSceneObjects, std::vector<GRiSceneObject*>* mSceneObjectLayer) { pSceneObjects.clear(); std::unordered_map<std::string, std::unique_ptr<GRiSceneObject>>::iterator i; for (i = mSceneObjects.begin(); i != mSceneObjects.end(); i++) { pSceneObjects[i->first] = i->second.get(); } for (size_t layer = 0; layer != (size_t)(RenderLayer::Count); layer++) { pSceneObjectLayer[layer].clear(); for (auto pSObj : mSceneObjectLayer[layer]) { pSceneObjectLayer[layer].push_back(pSObj); } } } int GRiRenderer::GetClientWidth()const { return mClientWidth; } int GRiRenderer::GetClientHeight()const { return mClientHeight; }
23.34375
164
0.714859
hegaoxiang
f8d59dc510fbd2e182e6d7397e856d11b14e869f
582
cpp
C++
algorithms/max-min/main.cpp
valentinvstoyanov/dsa-cpp
0d47377eff2df2888e7394b39203220e7aa82441
[ "MIT" ]
null
null
null
algorithms/max-min/main.cpp
valentinvstoyanov/dsa-cpp
0d47377eff2df2888e7394b39203220e7aa82441
[ "MIT" ]
null
null
null
algorithms/max-min/main.cpp
valentinvstoyanov/dsa-cpp
0d47377eff2df2888e7394b39203220e7aa82441
[ "MIT" ]
null
null
null
#include <iostream> #include "max_min.h" int main() { int arr[10] = {-199, 20, -200, 50, 1000, 1000, - 201, 1541, 0, 1}; auto mm = MaxMin(arr, 10); std::cout << "max = " << mm.first << ", min = " << mm.second << std::endl; std::cout << "max = " << Max(arr, 10) << std::endl; std::cout << "max = " << Max(arr, 0) << std::endl; std::cout << "max = " << Max<int>(nullptr, 1) << std::endl; std::cout << "min = " << Min(arr, 10) << std::endl; std::cout << "min = " << Min(arr, 0) << std::endl; std::cout << "min = " << Min<int>(nullptr, 10) << std::endl; return 0; }
38.8
76
0.501718
valentinvstoyanov
f8d87d10e11c2ceea2ea15f7130423e82793e1f0
1,676
cc
C++
test/quic/test_client_work.cc
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
6
2021-10-31T10:33:30.000Z
2022-03-25T20:54:58.000Z
test/quic/test_client_work.cc
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
test/quic/test_client_work.cc
cbodley/nexus
6e5b19b6c6c74007a0643c55eb0775eb86e38f9b
[ "BSL-1.0" ]
null
null
null
#include <nexus/quic/server.hpp> #include <gtest/gtest.h> #include <optional> #include <nexus/quic/client.hpp> #include <nexus/quic/connection.hpp> #include <nexus/global_init.hpp> #include "certificate.hpp" namespace nexus { // constuct a client and server on different io_contexts class Client : public testing::Test { protected: static constexpr const char* alpn = "\04quic"; global::context global = global::init_client_server(); ssl::context ssl = test::init_server_context(alpn); ssl::context sslc = test::init_client_context(alpn); boost::asio::io_context scontext; quic::server server = quic::server{scontext.get_executor()}; boost::asio::ip::address localhost = boost::asio::ip::make_address("127.0.0.1"); quic::acceptor acceptor{server, udp::endpoint{localhost, 0}, ssl}; boost::asio::io_context ccontext; quic::client client{ccontext.get_executor(), udp::endpoint{}, sslc}; }; TEST_F(Client, connection_work) { auto conn = quic::connection{client, acceptor.local_endpoint(), "host"}; ccontext.poll(); ASSERT_FALSE(ccontext.stopped()); // connection maintains work conn.close(); ccontext.poll(); ASSERT_TRUE(ccontext.stopped()); // close stops work } TEST_F(Client, two_connection_work) { auto conn1 = quic::connection{client, acceptor.local_endpoint(), "host"}; ccontext.poll(); ASSERT_FALSE(ccontext.stopped()); auto conn2 = quic::connection{client, acceptor.local_endpoint(), "host"}; ccontext.poll(); ASSERT_FALSE(ccontext.stopped()); conn1.close(); ccontext.poll(); ASSERT_FALSE(ccontext.stopped()); conn2.close(); ccontext.poll(); ASSERT_TRUE(ccontext.stopped()); } } // namespace nexus
26.1875
82
0.718974
cbodley
f8dc8baf6f425fde5cd36be06c4236aa54650252
3,070
cpp
C++
mof2oal/src/cimreference.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
13
2015-08-06T14:55:10.000Z
2021-12-26T04:41:54.000Z
mof2oal/src/cimreference.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
null
null
null
mof2oal/src/cimreference.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
1
2017-06-17T14:15:41.000Z
2017-06-17T14:15:41.000Z
/* * <AMD 3BSD notice header> * * Copyright (c) 2006, 2007, 2008 Advanced Micro Devices, Inc. * * All rights reserved. * * This file is subject to the license found in the LICENSE.AMD file which * states the following in part: * * Redistribution and use in any form of this material and any product * thereof including software in source or binary forms, along with any * related documentation, with or without modification ("this material"), * is permitted provided that the following conditions are met: * * * Redistributions of source code of any software must retain the above * copyright notice and all terms of this license as part of the code. * * * Redistributions in binary form of any software must reproduce the * above copyright notice and all terms of this license in any related * documentation and/or other materials. * * * Neither the names nor trademarks of Advanced Micro Devices, Inc. * or any copyright holders or contributors may be used to endorse or * promote products derived from this material without specific prior * written permission. */ #include "cimreference.h" #include "util.h" /* * Constructor */ CCIMReference::CCIMReference (string reference_object, string reference_name) : _reference_object (reference_object), _reference_name (reference_name) { } /* * generateCode */ string CCIMReference::generateCode (void) { string code; if (!g_oalcs && !g_oaldll) { code = "\t/**\r\n\t * "; code += _desc; code += "\r\n\t */\r\n"; /* Write the get function header */ code += "\tCCIMObjectPath get" + _reference_name + "(void)\r\n"; /* Write the get function body. */ code += "\t{\r\n\t\tCOALObject::checkUpdateCache (\"" + _reference_name + "\");\r\n"; code += "\r\n\t\tCCIMValue value = this->_ins.getProperty (\"" + _reference_name + "\").getValue ();\r\n"; code += " \r\n\t\tCCIMObjectPath " + _reference_name + " = to<CCIMObjectPath> (value);\r\n"; code += "\r\t\treturn " + _reference_name + ";\r\n"; code += "\t}\r\n"; } else { code = CSkeleton::instance ()->getContent ("REFERENCE"); code = ::replaceStr (code, "%REFERENCE_OBJ%", _reference_object); code = ::replaceStr (code, "%REFERENCE_DESC%", _desc); code = ::replaceStr (code, "%REFERENCE_NAME%", _reference_name); } return code; #if 0 /* Write the description */ ::writeString (fp, "/*\r\n"); ::writeString (fp, _desc); ::writeString (fp, "*/\r\n"); /* Write the get function header */ ::writeString (fp, "CCIMObjectPath get" + _reference_name + "(void) const\r\n"); /* Write the get function body. */ ::writeString (fp, "{\r\n\tcheckUpdateCache (\"" + _reference_name + "\");\r\n"); ::writeString (fp, "{\r\n\tCCIMObjectPath " + _reference_name + " = toCCIMObjectPath (_ins.getProperty (" + _reference_name + ").getValue ());\r\n"); ::writeString (fp, "return " + _reference_name + "\r\n"); ::writeString (fp, "}\r\n"); #endif return ""; }
32.659574
90
0.642997
juergh
f8e18e934c815584b42d24249fc25a873c31081c
140
cpp
C++
C语言程序设计基础/15.【图形】输出一行星号.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
63
2021-01-10T02:32:17.000Z
2022-03-30T04:08:38.000Z
C语言程序设计基础/15.【图形】输出一行星号.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
2
2021-06-09T05:38:58.000Z
2021-12-14T13:53:54.000Z
C语言程序设计基础/15.【图形】输出一行星号.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
20
2021-01-12T11:49:36.000Z
2022-03-26T11:04:58.000Z
#include <stdio.h> int main() { int n, i; scanf ("%d", &n); for (i = 1; i <= n; i++) { printf ("*"); } printf ("\n"); return 0; }
10.769231
25
0.428571
xiabee
f8e3c4478d822ef2a7afb75a556e32e84bf9387e
13,611
ipp
C++
src/cradle/imaging/sample.ipp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
null
null
null
src/cradle/imaging/sample.ipp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
3
2020-10-26T18:45:47.000Z
2020-10-26T18:46:06.000Z
src/cradle/imaging/sample.ipp
mghro/astroid-core
72736f64bed19ec3bb0e92ebee4d7cf09fc0399f
[ "MIT" ]
null
null
null
#include <cmath> #include <cradle/imaging/geometry.hpp> #include <cradle/imaging/iterator.hpp> namespace cradle { namespace impl { template<unsigned N, class T, class SP> optional<T> compute_raw_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { vector<N, double> image_p = transform_point(inverse(get_spatial_mapping(img)), p); vector<N, unsigned> index; for (unsigned i = 0; i < N; ++i) { index[i] = unsigned(std::floor(image_p[i])); if (index[i] >= img.size[i]) return optional<T>(); } return T(get_pixel_ref(img, index)); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_image_sample(image<N, T, SP> const& img, vector<N, double> const& p) { auto sample = compute_raw_image_sample(img, p); if (!sample) { return optional<typename replace_channel_type<T, double>::type>(); } return apply_linear_function(img.value_mapping, sample.get()); } template<unsigned N> struct point_sampler { vector<N, double> p; optional<double> result; template<class Pixel, class SP> void operator()(image<N, Pixel, SP> const& img) { optional<Pixel> x = raw_image_sample(img, p); if (x) result = double(get(x)); else result = none; } }; template<unsigned N, class SP> optional<double> compute_raw_image_sample( image<N, variant, SP> const& img, vector<N, double> const& p) { impl::point_sampler<N> sampler; sampler.p = p; apply_fn_to_gray_variant(sampler, img); return sampler.result; } template<unsigned N, class SP> optional<double> compute_image_sample( image<N, variant, SP> const& img, vector<N, double> const& p) { auto sample = compute_raw_image_sample(img, p); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } } // namespace impl template<unsigned N, class T, class SP> optional<T> raw_image_sample(image<N, T, SP> const& img, vector<N, double> const& p) { return impl::compute_raw_image_sample(img, p); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> image_sample(image<N, T, SP> const& img, vector<N, double> const& p) { return impl::compute_image_sample(img, p); } namespace impl { template<unsigned N, class T, class SP, unsigned Axis> struct raw_interpolated_sampler { static optional<typename replace_channel_type<T, double>::type> apply( image<N, T, SP> const& img, vector<N, double> const& p, vector<N, unsigned>& index) { typedef optional<typename replace_channel_type<T, double>::type> return_type; double v = p[Axis] - 0.5, floor_v = std::floor(v); index[Axis] = unsigned(floor_v); if (index[Axis] < img.size[Axis] && index[Axis] + 1 < img.size[Axis]) { double f = v - floor_v; return_type sample1 = raw_interpolated_sampler<N, T, SP, Axis - 1>::apply( img, p, index); ++index[Axis]; return_type sample2 = raw_interpolated_sampler<N, T, SP, Axis - 1>::apply( img, p, index); if (sample1 && sample2) return sample1.get() * (1 - f) + sample2.get() * f; } else { index[Axis] = unsigned(std::floor(p[Axis])); if (index[Axis] < img.size[Axis]) { return raw_interpolated_sampler<N, T, SP, Axis - 1>::apply( img, p, index); } } return return_type(); } }; template<unsigned N, class T, class SP> struct raw_interpolated_sampler<N, T, SP, 0> { static optional<typename replace_channel_type<T, double>::type> apply( image<N, T, SP> const& img, vector<N, double> const& p, vector<N, unsigned>& index) { typedef optional<typename replace_channel_type<T, double>::type> return_type; double v = p[0] - 0.5, floor_v = std::floor(v); index[0] = unsigned(floor_v); if (index[0] < img.size[0] && index[0] + 1 < img.size[0]) { double f = v - floor_v; typename replace_channel_type<T, double>::type sample1 = channel_convert<double>(get_pixel_ref(img, index)); ++index[0]; typename replace_channel_type<T, double>::type sample2 = channel_convert<double>(get_pixel_ref(img, index)); return sample1 * (1 - f) + sample2 * f; } else { index[0] = unsigned(std::floor(p[0])); if (index[0] < img.size[0]) { return channel_convert<double>(get_pixel_ref(img, index)); } } return return_type(); } }; template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_raw_interpolated_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { vector<N, double> image_p = transform_point(inverse(get_spatial_mapping(img)), p); vector<N, unsigned> index; return impl::raw_interpolated_sampler<N, T, SP, N - 1>::apply( img, image_p, index); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_interpolated_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { auto sample = compute_raw_interpolated_image_sample(img, p); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } template<unsigned N> struct interpolated_point_sampler { vector<N, double> p; optional<double> result; template<class Pixel, class SP> void operator()(image<N, Pixel, SP> const& img) { result = compute_raw_interpolated_image_sample(img, p); } }; template<unsigned N, class SP> optional<double> compute_raw_interpolated_image_sample( image<N, variant, SP> const& img, vector<N, double> const& p) { impl::interpolated_point_sampler<N> sampler; sampler.p = p; apply_fn_to_gray_variant(sampler, img); return sampler.result; } template<unsigned N, class SP> optional<double> compute_interpolated_image_sample( image<N, variant, SP> const& img, vector<N, double> const& p) { auto sample = raw_interpolated_image_sample(img, p); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } } // namespace impl template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> raw_interpolated_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { return impl::compute_raw_interpolated_image_sample(img, p); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> interpolated_image_sample( image<N, T, SP> const& img, vector<N, double> const& p) { return impl::compute_interpolated_image_sample(img, p); } namespace impl { // stores information about which pixels to sample along each axis struct raw_region_sample_axis_info { // the index of the first pixel to include unsigned i_begin; // # of pixels to include unsigned count; // w_first is the weight of the first pixel (if count >= 1) // w_last is the weight of the last pixel (if count >= 2) // w_mid is the weight of the pixels in the middle (if count >= 3) double w_first, w_mid, w_last; }; template<unsigned N, class T, class SP, unsigned Axis> struct raw_region_sample { static void apply( typename replace_channel_type<T, double>::type& result, image<N, T, SP> const& img, raw_region_sample_axis_info const* axis_info, vector<N, unsigned>& index, double weight) { raw_region_sample_axis_info const& info = axis_info[Axis]; index[Axis] = info.i_begin; raw_region_sample<N, T, SP, Axis - 1>::apply( result, img, axis_info, index, weight * info.w_first); unsigned count = info.count - 1; while (count > 1) { ++index[Axis]; raw_region_sample<N, T, SP, Axis - 1>::apply( result, img, axis_info, index, weight * info.w_mid); --count; } if (count > 0) { ++index[Axis]; raw_region_sample<N, T, SP, Axis - 1>::apply( result, img, axis_info, index, weight * info.w_last); } } }; template<unsigned N, class T, class SP> struct raw_region_sample<N, T, SP, 0> { static void apply( typename replace_channel_type<T, double>::type& result, image<N, T, SP> const& img, raw_region_sample_axis_info const* axis_info, vector<N, unsigned>& index, double weight) { raw_region_sample_axis_info const& info = axis_info[0]; index[0] = info.i_begin; span_iterator<N, T, SP> i = get_axis_iterator(img, 0, index); result += typename replace_channel_type<T, double>::type(*i) * weight * info.w_first; ++i; unsigned count = info.count - 1; while (count > 1) { result += typename replace_channel_type<T, double>::type(*i) * weight * info.w_mid; ++i; --count; } if (count > 0) { result += typename replace_channel_type<T, double>::type(*i) * weight * info.w_last; ++i; } } }; template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_raw_image_sample_over_box( image<N, T, SP> const& img, box<N, double> const& region) { matrix<N + 1, N + 1, double> inverse_spatial_mapping = inverse(get_spatial_mapping(img)); box<N, double> image_region; image_region.corner = transform_point(inverse_spatial_mapping, region.corner); image_region.size = transform_vector(inverse_spatial_mapping, region.size); impl::raw_region_sample_axis_info axis_info[N]; for (unsigned i = 0; i < N; ++i) { impl::raw_region_sample_axis_info& info = axis_info[i]; double low = double(std::floor(image_region.corner[i])); int i_begin = int(low); if (i_begin < 0) { i_begin = 0; info.w_first = 1; } else info.w_first = (low + 1) - double(image_region.corner[i]); double high = double(std::ceil(get_high_corner(image_region)[i])); int i_end = int(high); if (i_end > int(img.size[i])) { i_end = img.size[i]; info.w_last = 1; } else { info.w_last = double(get_high_corner(image_region)[i]) - (high - 1); } // region doesn't overlap the image along this axis if (i_begin >= i_end) { return optional<typename replace_channel_type<T, double>::type>(); } info.i_begin = i_begin; info.count = i_end - i_begin; double total_weight = info.w_first; if (info.count > 1) total_weight += info.w_last + (info.count - 2); double adjustment = 1 / total_weight; info.w_first *= adjustment; info.w_last *= adjustment; info.w_mid = adjustment; } typename replace_channel_type<T, double>::type result; fill_channels(result, 0); vector<N, unsigned> index; impl::raw_region_sample<N, T, SP, N - 1>::apply( result, img, axis_info, index, 1); return result; } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> compute_image_sample_over_box( image<N, T, SP> const& img, box<N, double> const& region) { auto sample = compute_raw_image_sample_over_box(img, region); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } template<unsigned N> struct region_sampler { box<N, double> region; optional<double> result; template<class Pixel, class SP> void operator()(image<N, Pixel, SP> const& img) { result = compute_raw_image_sample_over_box(img, region); } }; template<unsigned N, class SP> optional<double> compute_raw_image_sample_over_box( image<N, variant, SP> const& img, box<N, double> const& region) { impl::region_sampler<N> sampler; sampler.region = region; apply_fn_to_gray_variant(sampler, img); return sampler.result; } // template<unsigned N, class SP> optional<double> compute_image_sample_over_box( image<N, variant, SP> const& img, box<N, double> const& region) { auto sample = compute_raw_image_sample_over_box(img, region); if (!sample) return sample; return apply_linear_function(img.value_mapping, sample.get()); } } // namespace impl template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> raw_image_sample_over_box( image<N, T, SP> const& img, box<N, double> const& region) { return impl::compute_raw_image_sample_over_box(img, region); } template<unsigned N, class T, class SP> optional<typename replace_channel_type<T, double>::type> image_sample_over_box(image<N, T, SP> const& img, box<N, double> const& region) { return impl::compute_image_sample_over_box(img, region); } } // namespace cradle
28.594538
79
0.62163
mghro