text
stringlengths
54
60.6k
<commit_before>#include "main.hpp" #include "FinalComposite.hpp" void FinalComposite::create(const graphics::ScreenRectBuffer *rectangle) { this->rectangle = rectangle; static const char *vertexShaderSource = R"glsl( #version 330 core layout(location=0) in vec2 position; out vec2 screenCoord; out vec2 texcoord; void main() { screenCoord = position; texcoord = position * .5 + .5; gl_Position = vec4(position, 0., 1.); } )glsl"; static const char *fragmentShaderSource = R"glsl( #version 330 core uniform sampler2D source; uniform sampler2D background; uniform float backgroundVisibility; in vec2 screenCoord; in vec2 texcoord; out vec4 frag_color; float vignette(vec2 screenCoord) { float a = atan(screenCoord.y, screenCoord.x); // https://en.wikipedia.org/wiki/Squircle // https://thatsmaths.com/2016/07/14/squircles/ (Eq. 3) float s = sin(2 * a); float x = length(screenCoord) - s * s * .25; const float blendStart = 0.7; const float blendEnd = 0.95; // linear ramp from blend start to blend end float l = clamp((x - blendStart) * (1.0 / (blendEnd - blendStart)), 0.0, 1.0); return 1.0 - l*l; } void main() { //vec3 c = texture(source, texcoord).rgb; vec4 b = texelFetch(background, ivec2(gl_FragCoord.xy), 0); vec4 c = texelFetch(source, ivec2(gl_FragCoord.xy), 0); frag_color = vec4(mix(c.rgb, b.rgb, (1 - c.a) * backgroundVisibility) * vignette(screenCoord), 0.); } )glsl"; pipeline.create(vertexShaderSource, fragmentShaderSource, graphics::Pipeline::BlendMode::None); pipeline_source_location = pipeline.getUniformLocation("source"); pipeline_background_location = pipeline.getUniformLocation("background"); pipeline_backgroundVisibility_location = pipeline.getUniformLocation("backgroundVisibility"); } void FinalComposite::destroy() { pipeline.destroy(); } void FinalComposite::draw(graphics::Texture &source, graphics::Texture &background, float backgroundVisibility, uint32_t screen_width, uint32_t screen_height) { graphics::Framebuffer::unbind(); glViewport(0, 0, screen_width, screen_height); pipeline.bind(); source.bind(0u); glUniform1i(pipeline_source_location, 0u); background.bind(1u); glUniform1i(pipeline_background_location, 1u); glUniform1f(pipeline_backgroundVisibility_location, backgroundVisibility); rectangle->draw(); } <commit_msg>Disable vignette<commit_after>#include "main.hpp" #include "FinalComposite.hpp" void FinalComposite::create(const graphics::ScreenRectBuffer *rectangle) { this->rectangle = rectangle; static const char *vertexShaderSource = R"glsl( #version 330 core layout(location=0) in vec2 position; out vec2 screenCoord; out vec2 texcoord; void main() { screenCoord = position; texcoord = position * .5 + .5; gl_Position = vec4(position, 0., 1.); } )glsl"; static const char *fragmentShaderSource = R"glsl( #version 330 core uniform sampler2D source; uniform sampler2D background; uniform float backgroundVisibility; in vec2 screenCoord; in vec2 texcoord; out vec4 frag_color; float vignette(vec2 screenCoord) { float a = atan(screenCoord.y, screenCoord.x); // https://en.wikipedia.org/wiki/Squircle // https://thatsmaths.com/2016/07/14/squircles/ (Eq. 3) float s = sin(2 * a); float x = length(screenCoord) - s * s * .25; const float blendStart = 0.7; const float blendEnd = 0.95; // linear ramp from blend start to blend end float l = clamp((x - blendStart) * (1.0 / (blendEnd - blendStart)), 0.0, 1.0); return 1.0 - l*l; } void main() { //vec3 c = texture(source, texcoord).rgb; vec4 b = texelFetch(background, ivec2(gl_FragCoord.xy), 0); vec4 c = texelFetch(source, ivec2(gl_FragCoord.xy), 0); frag_color = vec4(mix(c.rgb, b.rgb, (1 - c.a) * backgroundVisibility) /* * vignette(screenCoord) */, 0.); } )glsl"; pipeline.create(vertexShaderSource, fragmentShaderSource, graphics::Pipeline::BlendMode::None); pipeline_source_location = pipeline.getUniformLocation("source"); pipeline_background_location = pipeline.getUniformLocation("background"); pipeline_backgroundVisibility_location = pipeline.getUniformLocation("backgroundVisibility"); } void FinalComposite::destroy() { pipeline.destroy(); } void FinalComposite::draw(graphics::Texture &source, graphics::Texture &background, float backgroundVisibility, uint32_t screen_width, uint32_t screen_height) { graphics::Framebuffer::unbind(); glViewport(0, 0, screen_width, screen_height); pipeline.bind(); source.bind(0u); glUniform1i(pipeline_source_location, 0u); background.bind(1u); glUniform1i(pipeline_background_location, 1u); glUniform1f(pipeline_backgroundVisibility_location, backgroundVisibility); rectangle->draw(); } <|endoftext|>
<commit_before>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkDevice.h" #include "SkPaint.h" #include "SkShader.h" static SkBitmap createBitmap(int n) { SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, n, n); bitmap.allocPixels(); bitmap.eraseColor(SK_ColorGREEN); SkCanvas canvas(bitmap); SkRect r; r.set(0, 0, SkIntToScalar(n), SkIntToScalar(n)); SkPaint paint; paint.setAntiAlias(true); paint.setColor(SK_ColorRED); canvas.drawOval(r, paint); paint.setColor(SK_ColorBLUE); paint.setStrokeWidth(SkIntToScalar(n)/15); paint.setStyle(SkPaint::kStroke_Style); canvas.drawLine(0, 0, r.fRight, r.fBottom, paint); canvas.drawLine(0, r.fBottom, r.fRight, 0, paint); return bitmap; } class AARectView : public SkView { SkBitmap fBitmap; enum { N = 64 }; public: AARectView() { fBitmap = createBitmap(N); fWidth = N; } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "AA Rects"); return true; } return this->INHERITED::onQuery(evt); } void drawBG(SkCanvas* canvas) { canvas->drawColor(SK_ColorWHITE); } virtual void onDraw(SkCanvas* canvas) { this->drawBG(canvas); canvas->translate(SkIntToScalar(10), SkIntToScalar(10)); SkPaint bluePaint; bluePaint.setARGB(0xff, 0x0, 0x0, 0xff); SkPaint bmpPaint; SkShader* bmpShader = SkShader::CreateBitmapShader(fBitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); bmpPaint.setShader(bmpShader); bmpShader->unref(); bluePaint.setStrokeWidth(3); bmpPaint.setStrokeWidth(3); SkPaint paints[] = { bluePaint, bmpPaint }; SkRect rect; SkScalar dx = SkIntToScalar(80); SkScalar dy = SkIntToScalar(100); SkMatrix matrix; for (int p = 0; p < SK_ARRAY_COUNT(paints); ++p) { for (int stroke = 0; stroke < 2; ++stroke) { paints[p].setStyle(stroke ? SkPaint::kStroke_Style : SkPaint::kFill_Style); for (int a = 0; a < 3; ++ a) { paints[p].setAntiAlias(a > 0); paints[p].setAlpha(a > 1 ? 0x80 : 0xff); canvas->save(); rect = SkRect::MakeLTRB(SkFloatToScalar(0.f), SkFloatToScalar(0.f), SkFloatToScalar(40.f), SkFloatToScalar(40.f)); canvas->drawRect(rect, paints[p]); canvas->translate(dx, 0); rect = SkRect::MakeLTRB(SkFloatToScalar(0.5f), SkFloatToScalar(0.5f), SkFloatToScalar(40.5f), SkFloatToScalar(40.5f)); canvas->drawRect(rect, paints[p]); canvas->translate(dx, 0); rect = SkRect::MakeLTRB(SkFloatToScalar(0.5f), SkFloatToScalar(0.5f), SkFloatToScalar(40.f), SkFloatToScalar(40.f)); canvas->drawRect(rect, paints[p]); canvas->translate(dx, 0); rect = SkRect::MakeLTRB(SkFloatToScalar(0.75f), SkFloatToScalar(0.75f), SkFloatToScalar(40.75f), SkFloatToScalar(40.75f)); canvas->drawRect(rect, paints[p]); canvas->translate(dx, 0); canvas->save(); canvas->translate(SkFloatToScalar(.33f), SkFloatToScalar(.67f)); rect = SkRect::MakeLTRB(SkFloatToScalar(0.0f), SkFloatToScalar(0.0f), SkFloatToScalar(40.0f), SkFloatToScalar(40.0f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); matrix.setRotate(SkFloatToScalar(45.f)); canvas->concat(matrix); canvas->translate(SkFloatToScalar(20.0f / sqrtf(2.f)), SkFloatToScalar(20.0f / sqrtf(2.f))); rect = SkRect::MakeLTRB(SkFloatToScalar(-20.0f), SkFloatToScalar(-20.0f), SkFloatToScalar(20.0f), SkFloatToScalar(20.0f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); canvas->rotate(SkFloatToScalar(90.f)); rect = SkRect::MakeLTRB(SkFloatToScalar(0.0f), SkFloatToScalar(0.0f), SkFloatToScalar(40.0f), SkFloatToScalar(-40.0f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); canvas->rotate(SkFloatToScalar(90.f)); rect = SkRect::MakeLTRB(SkFloatToScalar(0.5f), SkFloatToScalar(0.5f), SkFloatToScalar(40.5f), SkFloatToScalar(-40.5f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); matrix.setScale(SkFloatToScalar(-1.f), SkFloatToScalar(-1.f)); canvas->concat(matrix); rect = SkRect::MakeLTRB(SkFloatToScalar(0.5f), SkFloatToScalar(0.5f), SkFloatToScalar(-40.5f), SkFloatToScalar(-40.5f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); matrix.setScale(SkFloatToScalar(2.1f), SkFloatToScalar(4.1f)); canvas->concat(matrix); rect = SkRect::MakeLTRB(SkFloatToScalar(0.1f), SkFloatToScalar(0.1f), SkFloatToScalar(19.1f), SkFloatToScalar(9.1f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->restore(); canvas->translate(0, dy); } } } } private: int fWidth; typedef SkView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new AARectView; } static SkViewRegister reg(MyFactory); <commit_msg>inherit from SampleView<commit_after>#include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkDevice.h" #include "SkPaint.h" #include "SkShader.h" static SkBitmap createBitmap(int n) { SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, n, n); bitmap.allocPixels(); bitmap.eraseColor(SK_ColorGREEN); SkCanvas canvas(bitmap); SkRect r; r.set(0, 0, SkIntToScalar(n), SkIntToScalar(n)); SkPaint paint; paint.setAntiAlias(true); paint.setColor(SK_ColorRED); canvas.drawOval(r, paint); paint.setColor(SK_ColorBLUE); paint.setStrokeWidth(SkIntToScalar(n)/15); paint.setStyle(SkPaint::kStroke_Style); canvas.drawLine(0, 0, r.fRight, r.fBottom, paint); canvas.drawLine(0, r.fBottom, r.fRight, 0, paint); return bitmap; } class AARectView : public SampleView { SkBitmap fBitmap; enum { N = 64 }; public: AARectView() { fBitmap = createBitmap(N); fWidth = N; } protected: // overrides from SkEventSink virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "AA Rects"); return true; } return this->INHERITED::onQuery(evt); } virtual void onDrawContent(SkCanvas* canvas) { canvas->translate(SkIntToScalar(10), SkIntToScalar(10)); SkPaint bluePaint; bluePaint.setARGB(0xff, 0x0, 0x0, 0xff); SkPaint bmpPaint; SkShader* bmpShader = SkShader::CreateBitmapShader(fBitmap, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); bmpPaint.setShader(bmpShader); bmpShader->unref(); bluePaint.setStrokeWidth(3); bmpPaint.setStrokeWidth(3); SkPaint paints[] = { bluePaint, bmpPaint }; SkRect rect; SkScalar dx = SkIntToScalar(80); SkScalar dy = SkIntToScalar(100); SkMatrix matrix; for (int p = 0; p < SK_ARRAY_COUNT(paints); ++p) { for (int stroke = 0; stroke < 2; ++stroke) { paints[p].setStyle(stroke ? SkPaint::kStroke_Style : SkPaint::kFill_Style); for (int a = 0; a < 3; ++ a) { paints[p].setAntiAlias(a > 0); paints[p].setAlpha(a > 1 ? 0x80 : 0xff); canvas->save(); rect = SkRect::MakeLTRB(SkFloatToScalar(0.f), SkFloatToScalar(0.f), SkFloatToScalar(40.f), SkFloatToScalar(40.f)); canvas->drawRect(rect, paints[p]); canvas->translate(dx, 0); rect = SkRect::MakeLTRB(SkFloatToScalar(0.5f), SkFloatToScalar(0.5f), SkFloatToScalar(40.5f), SkFloatToScalar(40.5f)); canvas->drawRect(rect, paints[p]); canvas->translate(dx, 0); rect = SkRect::MakeLTRB(SkFloatToScalar(0.5f), SkFloatToScalar(0.5f), SkFloatToScalar(40.f), SkFloatToScalar(40.f)); canvas->drawRect(rect, paints[p]); canvas->translate(dx, 0); rect = SkRect::MakeLTRB(SkFloatToScalar(0.75f), SkFloatToScalar(0.75f), SkFloatToScalar(40.75f), SkFloatToScalar(40.75f)); canvas->drawRect(rect, paints[p]); canvas->translate(dx, 0); canvas->save(); canvas->translate(SkFloatToScalar(.33f), SkFloatToScalar(.67f)); rect = SkRect::MakeLTRB(SkFloatToScalar(0.0f), SkFloatToScalar(0.0f), SkFloatToScalar(40.0f), SkFloatToScalar(40.0f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); matrix.setRotate(SkFloatToScalar(45.f)); canvas->concat(matrix); canvas->translate(SkFloatToScalar(20.0f / sqrtf(2.f)), SkFloatToScalar(20.0f / sqrtf(2.f))); rect = SkRect::MakeLTRB(SkFloatToScalar(-20.0f), SkFloatToScalar(-20.0f), SkFloatToScalar(20.0f), SkFloatToScalar(20.0f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); canvas->rotate(SkFloatToScalar(90.f)); rect = SkRect::MakeLTRB(SkFloatToScalar(0.0f), SkFloatToScalar(0.0f), SkFloatToScalar(40.0f), SkFloatToScalar(-40.0f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); canvas->rotate(SkFloatToScalar(90.f)); rect = SkRect::MakeLTRB(SkFloatToScalar(0.5f), SkFloatToScalar(0.5f), SkFloatToScalar(40.5f), SkFloatToScalar(-40.5f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); matrix.setScale(SkFloatToScalar(-1.f), SkFloatToScalar(-1.f)); canvas->concat(matrix); rect = SkRect::MakeLTRB(SkFloatToScalar(0.5f), SkFloatToScalar(0.5f), SkFloatToScalar(-40.5f), SkFloatToScalar(-40.5f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->save(); matrix.setScale(SkFloatToScalar(2.1f), SkFloatToScalar(4.1f)); canvas->concat(matrix); rect = SkRect::MakeLTRB(SkFloatToScalar(0.1f), SkFloatToScalar(0.1f), SkFloatToScalar(19.1f), SkFloatToScalar(9.1f)); canvas->drawRect(rect, paints[p]); canvas->restore(); canvas->translate(dx, 0); canvas->restore(); canvas->translate(0, dy); } } } } private: int fWidth; typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new AARectView; } static SkViewRegister reg(MyFactory); <|endoftext|>
<commit_before>/* * DP * */ class NumArray { public: NumArray(vector<int> nums) { dp = nums; for (int i = 1; i < nums.size(); ++i) { dp[i] += dp[i - 1]; } } int sumRange(int i, int j) { return i == 0 ? dp[j] : dp[j] - dp[i - 1]; } private: vector<int> dp; }; // Conclusion: // Decrease the time complexity of the method that would be called frequntly. <commit_msg>Update 303.cpp<commit_after>/* * DP * */ //version 1: class NumArray { public: NumArray(vector<int> nums) { dp = nums; for (int i = 1; i < nums.size(); ++i) { dp[i] += dp[i - 1]; } } int sumRange(int i, int j) { return i == 0 ? dp[j] : dp[j] - dp[i - 1]; } private: vector<int> dp; }; // version 2: class NumArray { public: NumArray(vector<int> &nums) { dp.resize(nums.size() + 1, 0); for (int i = 1; i <= nums.size(); ++i) { dp[i] = dp[i - 1] + nums[i - 1]; } } int sumRange(int i, int j) { return dp[j + 1] - dp[i]; } private: vector<int> dp; }; // Conclusion: // Decrease the time complexity of the method that would be called frequntly. // In version 2, the add-on is to avoid zero check. <|endoftext|>
<commit_before>/// /// @file pi_deleglise_rivat_parallel3.cpp /// @brief Parallel implementation of the Deleglise-Rivat prime /// counting algorithm. This implementation is identical to /// pi_deleglise_rivat_parallel2(x) but uses 128-bit integers. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <FactorTable.hpp> #include <primecount.hpp> #include <primecount-internal.hpp> #include <generate.hpp> #include <min_max.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <int128.hpp> #include <S1.hpp> #include "S2.hpp" #include <stdint.h> #include <algorithm> #include <iostream> #include <vector> using namespace std; using namespace primecount; namespace { /// Calculate the contribution of the special leaves. /// @pre y > 0 && c > 1 /// template <typename P, typename F> int128_t S2(int128_t x, int64_t y, int64_t z, int64_t c, int128_t s2_approx, vector<P>& primes, FactorTable<F>& factors, int threads) { threads = validate_threads(threads, z); PiTable pi(y); int128_t s2_trivial = S2_trivial(x, y, z, c, pi, primes, threads); int128_t s2_easy = S2_easy(x, y, z, c, pi, primes, threads); int128_t s2_hard_approx = s2_approx - (s2_trivial + s2_easy); int128_t s2_hard = S2_hard(x, y, z, c, s2_hard_approx, pi, primes, factors, threads); int128_t s2 = s2_trivial + s2_easy + s2_hard; return s2; } /// alpha is a tuning factor which should grow like (log(x))^3 /// for the Deleglise-Rivat prime counting algorithm. /// double compute_alpha(int128_t x) { double d = (double) x; double alpha = log(d) * log(d) * log(d) / 1000; return in_between(1, alpha, iroot<6>(x)); } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat_parallel3(int128_t x, int threads) { if (x < 2) return 0; if (x > to_maxint(primecount::max())) throw primecount_error("pi(x): x must be <= " + max()); double alpha = compute_alpha(x); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = (int64_t) (x / y); int64_t pi_y; int64_t c; if (print_status()) { cout << endl; cout << "=== pi_deleglise_rivat_parallel3(x) ===" << endl; cout << "pi(x) = S1 + S2 + pi(y) - 1 - P2" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "c = " << PhiTiny::max_a() << endl; cout << "threads = " << validate_threads(threads) << endl; } int128_t p2 = P2(x, y, threads); int128_t s2_approx; int128_t s1, s2; if (y <= FactorTable<uint16_t>::max()) { // if y < 2^32 we can use 32-bit primes and a 16-bit FactorTable // which uses ~ (y / 2) bytes of memory vector<uint32_t> primes = generate_primes<uint32_t>(y); FactorTable<uint16_t> factors(y); pi_y = primes.size() - 1; c = min(pi_y, PhiTiny::max_a()); s1 = S1(x, y, c, primes[c], factors, threads); s2_approx = S2_approx(x, pi_y, p2, s1); s2 = S2(x, y, z, c, s2_approx, primes, factors, threads); } else { // if y >= 2^32 we need to use 64-bit primes and a 32-bit // FactorTable which uses ~ y bytes of memory vector<int64_t> primes = generate_primes<int64_t>(y); FactorTable<uint32_t> factors(y); pi_y = primes.size() - 1; c = min(pi_y, PhiTiny::max_a()); s1 = S1(x, y, c, primes[c], factors, threads); s2_approx = S2_approx(x, pi_y, p2, s1); s2 = S2(x, y, z, c, s2_approx, primes, factors, threads); } int128_t phi = s1 + s2; int128_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace <commit_msg>Tune S2_hard alpha factor<commit_after>/// /// @file pi_deleglise_rivat_parallel3.cpp /// @brief Parallel implementation of the Deleglise-Rivat prime /// counting algorithm. This implementation is identical to /// pi_deleglise_rivat_parallel2(x) but uses 128-bit integers. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <FactorTable.hpp> #include <primecount.hpp> #include <primecount-internal.hpp> #include <generate.hpp> #include <min_max.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <int128.hpp> #include <S1.hpp> #include "S2.hpp" #include <stdint.h> #include <algorithm> #include <iostream> #include <vector> using namespace std; using namespace primecount; namespace { /// Calculate the contribution of the special leaves. /// @pre y > 0 && c > 1 /// template <typename P, typename F> int128_t S2(int128_t x, int64_t y, int64_t z, int64_t c, int128_t s2_approx, vector<P>& primes, FactorTable<F>& factors, int threads) { threads = validate_threads(threads, z); PiTable pi(y); int128_t s2_trivial = S2_trivial(x, y, z, c, pi, primes, threads); int128_t s2_easy = S2_easy(x, y, z, c, pi, primes, threads); int128_t s2_hard_approx = s2_approx - (s2_trivial + s2_easy); int128_t s2_hard = S2_hard(x, y, z, c, s2_hard_approx, pi, primes, factors, threads); int128_t s2 = s2_trivial + s2_easy + s2_hard; return s2; } /// alpha is a tuning factor which should grow like (log(x))^3 /// for the Deleglise-Rivat prime counting algorithm. /// double compute_alpha(int128_t x) { double d = (double) x; double alpha = log(d) * log(d) * log(d) / 1200; return in_between(1, alpha, iroot<6>(x)); } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space. /// int128_t pi_deleglise_rivat_parallel3(int128_t x, int threads) { if (x < 2) return 0; if (x > to_maxint(primecount::max())) throw primecount_error("pi(x): x must be <= " + max()); double alpha = compute_alpha(x); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = (int64_t) (x / y); int64_t pi_y; int64_t c; if (print_status()) { cout << endl; cout << "=== pi_deleglise_rivat_parallel3(x) ===" << endl; cout << "pi(x) = S1 + S2 + pi(y) - 1 - P2" << endl; cout << "x = " << x << endl; cout << "y = " << y << endl; cout << "z = " << z << endl; cout << "c = " << PhiTiny::max_a() << endl; cout << "threads = " << validate_threads(threads) << endl; } int128_t p2 = P2(x, y, threads); int128_t s2_approx; int128_t s1, s2; if (y <= FactorTable<uint16_t>::max()) { // if y < 2^32 we can use 32-bit primes and a 16-bit FactorTable // which uses ~ (y / 2) bytes of memory vector<uint32_t> primes = generate_primes<uint32_t>(y); FactorTable<uint16_t> factors(y); pi_y = primes.size() - 1; c = min(pi_y, PhiTiny::max_a()); s1 = S1(x, y, c, primes[c], factors, threads); s2_approx = S2_approx(x, pi_y, p2, s1); s2 = S2(x, y, z, c, s2_approx, primes, factors, threads); } else { // if y >= 2^32 we need to use 64-bit primes and a 32-bit // FactorTable which uses ~ y bytes of memory vector<int64_t> primes = generate_primes<int64_t>(y); FactorTable<uint32_t> factors(y); pi_y = primes.size() - 1; c = min(pi_y, PhiTiny::max_a()); s1 = S1(x, y, c, primes[c], factors, threads); s2_approx = S2_approx(x, pi_y, p2, s1); s2 = S2(x, y, z, c, s2_approx, primes, factors, threads); } int128_t phi = s1 + s2; int128_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace <|endoftext|>
<commit_before>#define BX_IN_CPU_METHOD 1 #include "bochs.h" #include <assert.h> BX_CPU_C *apic_index[APIC_MAX_ID]; bx_apic_c::bx_apic_c(BX_CPU_C *mycpu) { id = APIC_UNKNOWN_ID; cpu = mycpu; // default address for a local APIC, can be moved apic_base_msr = 0xfee00000; err_status = 0; } bx_apic_c::~bx_apic_c(void) { // nothing for now } Bit32u bx_apic_c::get_base (void) { return apic_base_msr; } void bx_apic_c::set_id (Bit8u newid) { // update apic_index if (id != APIC_UNKNOWN_ID) { bx_assert (id < APIC_MAX_ID); if (apic_index[id] != cpu) bx_panic ("inconsistent APIC id table"); apic_index[id] = NULL; } id = newid; if (apic_index[id] != NULL) bx_panic ("duplicate APIC id assigned"); apic_index[id] = cpu; sprintf (cpu->name, "CPU apicid=%02x", (Bit32u)id); } void bx_apic_c::set_base (Bit32u newbase) { bx_printf ("relocate APIC to %8x\n", newbase); apic_base_msr = newbase; } void bx_apic_c::write_handler (Bit32u addr, Bit32u *data, unsigned len) { assert (len == 4); bx_printf ("write %08x to APIC address %08x\n", *data, addr); //assert (!(addr & 0xf)); switch (addr & 0xff0) { case 0x20: // local APIC id id = ((*data)>>24) & 0xf; break; case 0x30: // local APIC version bx_printf ("warning: write to read-only APIC register\n"); break; case 0x80: // task priority case 0x90: // arbitration priority case 0xa0: // processor priority case 0xb0: // EOI case 0xd0: // logical destination case 0xe0: // destination format case 0xf0: // spurious interrupt vector break; case 0x280: // error status reg // Here's what the IA-devguide-3 says on p.7-45: // The ESR is a read/write register and is reset after being written to by // the processor. A write to the ESR must be done just prior to reading the // ESR to allow the register to be updated. // This doesn't seem clear. If the write clears the register, then // wouldn't you always read zero? Otherwise, what does the write do? // In my model, the write will do nothing. break; case 0x300: // interrupt command reg 0-31 { icr_low = *data & ~(1<<12); // force delivery status bit = 0 (idle) // and trigger an interrupt to be sent int dest_shorthand = (icr_low >> 18) & 3; char *dests[4] = {NULL, "self", "all including self", "all except self" }; char buf[32]; sprintf (buf, "APIC 0x%02x\n", icr_high >> 24); bx_printf ("APIC 0x%02x sending interrupt to destination %s", id, (dest_shorthand==0) ? buf : dests[dest_shorthand]); bx_printf ("low word of APIC 0x%02x ICR = 0x%04x\n", id, icr_low & 0xffff); } break; case 0x310: // interrupt command reg 31-63 icr_high = *data & 0xff000000; break; case 0x320: // LVT Timer Reg case 0x330: // LVT Thermal Monitor case 0x340: // LVT Performance Counter case 0x350: // LVT LINT0 Reg case 0x360: // LVT Lint1 Reg case 0x370: // LVT Error Reg case 0x380: // initial count for timer case 0x390: // current count for timer case 0x3e0: // timer divide configuration default: bx_printf ("APIC register %08x not implemented\n", addr); } } void bx_apic_c::read_handler (Bit32u addr, Bit32u *data, unsigned len) { assert (len == 4); *data = 0; // default value for unimplemented registers switch (addr & 0xff0) { case 0x20: // local APIC id *data = (id) << 24; break; case 0x30: // local APIC version *data = 0x00170011; break; case 0x80: // task priority case 0x90: // arbitration priority case 0xa0: // processor priority case 0xb0: // EOI case 0xd0: // logical destination case 0xe0: // destination format case 0xf0: // spurious interrupt vector break; case 0x280: // error status reg *data = err_status; break; case 0x300: // interrupt command reg 0-31 *data = icr_low; break; case 0x310: // interrupt command reg 31-63 *data = icr_high; break; case 0x320: // LVT Timer Reg case 0x330: // LVT Thermal Monitor case 0x340: // LVT Performance Counter case 0x350: // LVT LINT0 Reg case 0x360: // LVT Lint1 Reg case 0x370: // LVT Error Reg case 0x380: // initial count for timer case 0x390: // current count for timer case 0x3e0: // timer divide configuration default: bx_printf ("APIC register %08x not implemented\n", addr); } bx_printf ("read from APIC address %08x = %08x\n", addr, *data); } BX_CPU_C bx_apic_c::*get_cpu (Bit8u id) { bx_assert (id >= 0 && id < APIC_MAX_ID); } <commit_msg>- added code that really starts up a remote CPU<commit_after>#define BX_IN_CPU_METHOD 1 #include "bochs.h" #include <assert.h> BX_CPU_C *apic_index[APIC_MAX_ID]; bx_apic_c::bx_apic_c(BX_CPU_C *mycpu) { id = APIC_UNKNOWN_ID; cpu = mycpu; // default address for a local APIC, can be moved apic_base_msr = 0xfee00000; err_status = 0; } bx_apic_c::~bx_apic_c(void) { // nothing for now } Bit32u bx_apic_c::get_base (void) { return apic_base_msr; } void bx_apic_c::set_id (Bit8u newid) { // update apic_index if (id != APIC_UNKNOWN_ID) { bx_assert (id < APIC_MAX_ID); if (apic_index[id] != cpu) bx_panic ("inconsistent APIC id table"); apic_index[id] = NULL; } id = newid; if (apic_index[id] != NULL) bx_panic ("duplicate APIC id assigned"); apic_index[id] = cpu; sprintf (cpu->name, "CPU apicid=%02x", (Bit32u)id); } void bx_apic_c::set_base (Bit32u newbase) { bx_printf ("relocate APIC to %8x\n", newbase); apic_base_msr = newbase; } void bx_apic_c::write_handler (Bit32u addr, Bit32u *data, unsigned len) { assert (len == 4); bx_printf ("write %08x to APIC address %08x\n", *data, addr); //assert (!(addr & 0xf)); switch (addr & 0xff0) { case 0x20: // local APIC id id = ((*data)>>24) & 0xf; break; case 0x30: // local APIC version bx_printf ("warning: write to read-only APIC register\n"); break; case 0x80: // task priority case 0x90: // arbitration priority case 0xa0: // processor priority case 0xb0: // EOI case 0xd0: // logical destination case 0xe0: // destination format case 0xf0: // spurious interrupt vector break; case 0x280: // error status reg // Here's what the IA-devguide-3 says on p.7-45: // The ESR is a read/write register and is reset after being written to by // the processor. A write to the ESR must be done just prior to reading the // ESR to allow the register to be updated. // This doesn't seem clear. If the write clears the register, then // wouldn't you always read zero? Otherwise, what does the write do? // In my model, the write will do nothing. break; case 0x300: // interrupt command reg 0-31 { icr_low = *data & ~(1<<12); // force delivery status bit = 0 (idle) // and trigger an interrupt to be sent int dest_shorthand = (icr_low >> 18) & 3; char *dests[4] = {NULL, "self", "all including self", "all except self" }; char buf[32]; unsigned int target_id = (icr_high >> 24); sprintf (buf, "APIC 0x%02x\n", target_id); bx_printf ("APIC 0x%02x sending interrupt to destination %s", id, (dest_shorthand==0) ? buf : dests[dest_shorthand]); bx_printf ("low word of APIC 0x%02x ICR = 0x%04x\n", id, icr_low & 0xffff); int delivery_mode = (icr_low >> 8) & 7; int vector = (icr_low & 0xff); if (delivery_mode == 6 && dest_shorthand == 0) { // tell target to start up if (target_id > APIC_MAX_ID) bx_panic ("target apic id out of range"); BX_CPU_C *target = apic_index[target_id]; if (target == NULL) bx_panic ("apic target id not found"); target->local_apic.startup_msg (vector); } else { bx_printf ("APIC operation not supported"); } } break; case 0x310: // interrupt command reg 31-63 icr_high = *data & 0xff000000; break; case 0x320: // LVT Timer Reg case 0x330: // LVT Thermal Monitor case 0x340: // LVT Performance Counter case 0x350: // LVT LINT0 Reg case 0x360: // LVT Lint1 Reg case 0x370: // LVT Error Reg case 0x380: // initial count for timer case 0x390: // current count for timer case 0x3e0: // timer divide configuration default: bx_printf ("APIC register %08x not implemented\n", addr); } } void bx_apic_c::startup_msg (Bit32u vector) { if (cpu->debug_trap & 0x80000000) { cpu->debug_trap &= ~0x80000000; cpu->eip = 0; cpu->load_seg_reg (&cpu->sregs[BX_SEG_REG_CS], vector*0x100); bx_printf ("%s started up at 0x%x by APIC\n", cpu->name, cpu->eip); } else { bx_printf ("%s started up by APIC, but was not halted at the time\n", cpu->name); } } void bx_apic_c::read_handler (Bit32u addr, Bit32u *data, unsigned len) { assert (len == 4); *data = 0; // default value for unimplemented registers switch (addr & 0xff0) { case 0x20: // local APIC id *data = (id) << 24; break; case 0x30: // local APIC version *data = 0x00170011; break; case 0x80: // task priority case 0x90: // arbitration priority case 0xa0: // processor priority case 0xb0: // EOI case 0xd0: // logical destination case 0xe0: // destination format case 0xf0: // spurious interrupt vector break; case 0x280: // error status reg *data = err_status; break; case 0x300: // interrupt command reg 0-31 *data = icr_low; break; case 0x310: // interrupt command reg 31-63 *data = icr_high; break; case 0x320: // LVT Timer Reg case 0x330: // LVT Thermal Monitor case 0x340: // LVT Performance Counter case 0x350: // LVT LINT0 Reg case 0x360: // LVT Lint1 Reg case 0x370: // LVT Error Reg case 0x380: // initial count for timer case 0x390: // current count for timer case 0x3e0: // timer divide configuration default: bx_printf ("APIC register %08x not implemented\n", addr); } bx_printf ("read from APIC address %08x = %08x\n", addr, *data); } BX_CPU_C bx_apic_c::*get_cpu (Bit8u id) { bx_assert (id < APIC_MAX_ID); } <|endoftext|>
<commit_before>#ifndef DICE_IOPERATION_H #define DICE_IOPERATION_H #include "../stdafx.hpp" #include "DiceRoll/Operations/RollResult.h" //Base for a Decorator Pattern /** * \brief An interface for the Operation classes. * * It is a base for the Decorator Pattern. */ class IOperation { protected: // DELETE THIS std::vector<int> _elements; int _count; //END OF DELETE /** * \brief Suboperation that will be evaluated before current. * * Stores an object that is a child of IOperation interface. * By default, _componentOp.evaluate() is called before * this->execute() and results are merged together. */ IOperation * const _componentOp; /** * \brief Executes current operation. * * This is a method that does all the heavy lifting for an operation. * * \return * Returns unique pointer to RollResult which stores current operation result. * Don't mistake it with evaluate()! */ virtual std::unique_ptr<RollResult> execute() = 0; public: IOperation(IOperation* op) : _componentOp(op) {} // Executes all operations. // By default, merges _componentOp's RollResult with its. /** * \brief Evaluates all suboperations and executes itself. * * By default it calls evaluate() on it's suboperation (_componentOp) * and then merges the result with its own. * * \return Unique pointer to the result of executing current operation * and all suboperations. */ virtual inline std::unique_ptr<RollResult> evaluate() { std::unique_ptr<RollResult> result = _componentOp->evaluate(); result->append(execute().get()); return result; } //DELETE THIS virtual std::string toString() const { std::string result = ""; for (auto& element : _elements) result += std::to_string(element) + " "; return result; } inline int getCount() const { return _count; } inline const std::vector<int> &getElements() const { return _elements; } //END OF DELETE }; #endif //DICE_IOPERATION_H <commit_msg>Moved _componentOp and execute() from protected to private.<commit_after>#ifndef DICE_IOPERATION_H #define DICE_IOPERATION_H #include "../stdafx.hpp" #include "DiceRoll/Operations/RollResult.h" //Base for a Decorator Pattern /** * \brief An interface for the Operation classes. * * It is a base for the Decorator Pattern. */ class IOperation { protected: // DELETE THIS std::vector<int> _elements; int _count; //END OF DELETE private: /** * \brief Suboperation that will be evaluated before current. * * Stores an object that is a child of IOperation interface. * By default, _componentOp.evaluate() is called before * this->execute() and results are merged together. */ IOperation * const _componentOp; /** * \brief Executes current operation. * * This is a method that does all the heavy lifting for an operation. * * \return * Returns unique pointer to RollResult which stores current operation result. * Don't mistake it with evaluate()! */ virtual std::unique_ptr<RollResult> execute() = 0; public: IOperation(IOperation* op) : _componentOp(op) {} // Executes all operations. // By default, merges _componentOp's RollResult with its. /** * \brief Evaluates all suboperations and executes itself. * * By default it calls evaluate() on it's suboperation (_componentOp) * and then merges the result with its own. * * \return Unique pointer to the result of executing current operation * and all suboperations. */ virtual inline std::unique_ptr<RollResult> evaluate() { std::unique_ptr<RollResult> result = _componentOp->evaluate(); result->append(execute().get()); return result; } //DELETE THIS virtual std::string toString() const { std::string result = ""; for (auto& element : _elements) result += std::to_string(element) + " "; return result; } inline int getCount() const { return _count; } inline const std::vector<int> &getElements() const { return _elements; } //END OF DELETE }; #endif //DICE_IOPERATION_H <|endoftext|>
<commit_before>#include <kdl_codyco/utils.hpp> #include <kdl_codyco/undirectedtree.hpp> #include "kdl_codyco/rnea_loops.hpp" #include <kdl_codyco/regressor_utils.hpp> #include <kdl/rigidbodyinertia.hpp> #include <kdl/frames_io.hpp> #include <kdl_codyco/treeidsolver_recursive_newton_euler.hpp> #include <kdl_codyco/treedynparam.hpp> #include <kdl_codyco/floatingjntspaceinertiamatrix.hpp> #include <kdl_codyco/rnea_loops.hpp> #include "test_models.hpp" #include <ctime> #include <boost/concept_check.hpp> using namespace KDL; using namespace KDL::CoDyCo; double random_double() { return ((double)rand()-RAND_MAX/2)/((double)RAND_MAX); } int main() { JntArray q, dq, ddq, torques_slv; Wrenches f_slv,f_ext; Wrench base_force_slv; Twist base_vel, base_acc; JntArray torques_loop_one; Wrenches f_loop_one; Wrench base_force_loop_one; std::vector<Twist> v_loop_one,a_loop_one; JntArray torques_loop_two; Wrenches f_loop_two, f_gi_loop_two; Wrench base_force_loop_two(Vector(1,2,3),Vector(4,5,6)); std::vector<Twist> v_loop_two,a_loop_two; srand(time(NULL)); Tree test_tree = TestHumanoid(); UndirectedTree test_undirected_tree(test_tree); Traversal test_traversal; test_undirected_tree.compute_traversal(test_traversal); //Creating several solvers: //one for proper floating base inverse dynamics TreeIdSolver_RNE rne_idsolver(test_tree); //one by manually manipulating loops //Create the variables q= dq = ddq = torques_slv = torques_loop_one = torques_loop_two = JntArray(test_tree.getNrOfJoints()); f_ext = f_slv = f_loop_one = f_loop_two = f_gi_loop_two = std::vector<Wrench>(test_tree.getNrOfSegments(),KDL::Wrench::Zero()); v_loop_one = a_loop_one = v_loop_two = a_loop_two = std::vector<Twist>(test_undirected_tree.getNrOfLinks(),KDL::Twist::Zero()); for(int i=0; i < (int)test_tree.getNrOfJoints(); i++ ) { q(i) = random_double(); dq(i) = random_double(); ddq(i) = random_double(); } base_vel = Twist(Vector(random_double(),random_double(),random_double()),Vector(random_double(),random_double(),random_double())); base_acc = Twist(Vector(random_double(),random_double(),random_double()),Vector(random_double(),random_double(),random_double())); //Inserting the random input data in both solvers, while checking all went well if( rne_idsolver.CartToJnt(q,dq,ddq,base_vel,base_acc,f_ext,torques_slv,base_force_slv) != 0 ) return -1; //Tryng the same with the normal loops bool ret = true; ret = ret && rneaKinematicLoop(test_undirected_tree,q,dq,ddq,test_traversal,base_vel,base_acc,v_loop_one,a_loop_one) == 0; ret = ret && rneaDynamicLoop(test_undirected_tree,q,test_traversal,v_loop_one,a_loop_one,f_ext,f_loop_one,torques_loop_one,base_force_loop_one) == 0; //Tryng the same with the modified loops ret = ret && rneaKinematicLoop(test_undirected_tree,q,dq,ddq,test_traversal,base_vel,base_acc,v_loop_two,a_loop_two,f_gi_loop_two) == 0; ret = ret && rneaDynamicLoop(test_undirected_tree,q,test_traversal,f_gi_loop_two,f_ext,f_loop_two,torques_loop_two,base_force_loop_two) == 0; assert(ret); //Build generalized_torques Eigen::VectorXd generalized_tau_slv = toEigen(base_force_slv,torques_slv); Eigen::VectorXd generalized_tau_loop_one = toEigen(base_force_loop_one,torques_loop_one); Eigen::VectorXd generalized_tau_loop_two = toEigen(base_force_loop_two,torques_loop_two); std::cout << "Generalized Torques obtained with RNE" << std::endl << generalized_tau_slv << std::endl; std::cout << "Generalized Torques obtained with original loop" << std::endl << generalized_tau_loop_one << std::endl; std::cout << "Generalized Torques obtained with modified loop" << std::endl << generalized_tau_loop_two << std::endl; std::cout << "Generalized Torques obtained with RNE - original loop" << std::endl << generalized_tau_slv-generalized_tau_loop_one << std::endl; std::cout << "Generalized Torques obtained with RNE - modified loop" << std::endl << generalized_tau_slv-generalized_tau_loop_two << std::endl; for(int i=0; i < (int)test_traversal.getNrOfVisitedLinks(); i++) { LinkMap::const_iterator link_it = test_traversal.getOrderedLink(i); int link_nmbr = link_it->getLinkIndex(); std::cout << "Link " << link_nmbr << std::endl; std::cout << "F_ext " << f_ext[link_nmbr] << std::endl; std::cout << "f_loop_one " << f_loop_one[link_nmbr] << std::endl; std::cout << "f_loop_two " << f_loop_two[link_nmbr] << std::endl; std::cout << "f_loop_one-f_loop_two " << f_loop_one[link_nmbr]-f_loop_two[link_nmbr] << std::endl; std::cout << "f_gi_loop_two " << f_gi_loop_two[link_nmbr] << std::endl; } if( (generalized_tau_slv-generalized_tau_loop_one).norm() > 1e-10 ) return -1; if( (generalized_tau_slv-generalized_tau_loop_two).norm() > 1e-10 ) return -1; return 0; } <commit_msg>removed spurious headers<commit_after>#include <kdl_codyco/utils.hpp> #include <kdl_codyco/undirectedtree.hpp> #include "kdl_codyco/rnea_loops.hpp" #include <kdl_codyco/regressor_utils.hpp> #include <kdl/rigidbodyinertia.hpp> #include <kdl/frames_io.hpp> #include <kdl_codyco/treeidsolver_recursive_newton_euler.hpp> #include <kdl_codyco/treedynparam.hpp> #include <kdl_codyco/floatingjntspaceinertiamatrix.hpp> #include <kdl_codyco/rnea_loops.hpp> #include "test_models.hpp" #include <ctime> using namespace KDL; using namespace KDL::CoDyCo; double random_double() { return ((double)rand()-RAND_MAX/2)/((double)RAND_MAX); } int main() { JntArray q, dq, ddq, torques_slv; Wrenches f_slv,f_ext; Wrench base_force_slv; Twist base_vel, base_acc; JntArray torques_loop_one; Wrenches f_loop_one; Wrench base_force_loop_one; std::vector<Twist> v_loop_one,a_loop_one; JntArray torques_loop_two; Wrenches f_loop_two, f_gi_loop_two; Wrench base_force_loop_two(Vector(1,2,3),Vector(4,5,6)); std::vector<Twist> v_loop_two,a_loop_two; srand(time(NULL)); Tree test_tree = TestHumanoid(); UndirectedTree test_undirected_tree(test_tree); Traversal test_traversal; test_undirected_tree.compute_traversal(test_traversal); //Creating several solvers: //one for proper floating base inverse dynamics TreeIdSolver_RNE rne_idsolver(test_tree); //one by manually manipulating loops //Create the variables q= dq = ddq = torques_slv = torques_loop_one = torques_loop_two = JntArray(test_tree.getNrOfJoints()); f_ext = f_slv = f_loop_one = f_loop_two = f_gi_loop_two = std::vector<Wrench>(test_tree.getNrOfSegments(),KDL::Wrench::Zero()); v_loop_one = a_loop_one = v_loop_two = a_loop_two = std::vector<Twist>(test_undirected_tree.getNrOfLinks(),KDL::Twist::Zero()); for(int i=0; i < (int)test_tree.getNrOfJoints(); i++ ) { q(i) = random_double(); dq(i) = random_double(); ddq(i) = random_double(); } base_vel = Twist(Vector(random_double(),random_double(),random_double()),Vector(random_double(),random_double(),random_double())); base_acc = Twist(Vector(random_double(),random_double(),random_double()),Vector(random_double(),random_double(),random_double())); //Inserting the random input data in both solvers, while checking all went well if( rne_idsolver.CartToJnt(q,dq,ddq,base_vel,base_acc,f_ext,torques_slv,base_force_slv) != 0 ) return -1; //Tryng the same with the normal loops bool ret = true; ret = ret && rneaKinematicLoop(test_undirected_tree,q,dq,ddq,test_traversal,base_vel,base_acc,v_loop_one,a_loop_one) == 0; ret = ret && rneaDynamicLoop(test_undirected_tree,q,test_traversal,v_loop_one,a_loop_one,f_ext,f_loop_one,torques_loop_one,base_force_loop_one) == 0; //Tryng the same with the modified loops ret = ret && rneaKinematicLoop(test_undirected_tree,q,dq,ddq,test_traversal,base_vel,base_acc,v_loop_two,a_loop_two,f_gi_loop_two) == 0; ret = ret && rneaDynamicLoop(test_undirected_tree,q,test_traversal,f_gi_loop_two,f_ext,f_loop_two,torques_loop_two,base_force_loop_two) == 0; assert(ret); //Build generalized_torques Eigen::VectorXd generalized_tau_slv = toEigen(base_force_slv,torques_slv); Eigen::VectorXd generalized_tau_loop_one = toEigen(base_force_loop_one,torques_loop_one); Eigen::VectorXd generalized_tau_loop_two = toEigen(base_force_loop_two,torques_loop_two); std::cout << "Generalized Torques obtained with RNE" << std::endl << generalized_tau_slv << std::endl; std::cout << "Generalized Torques obtained with original loop" << std::endl << generalized_tau_loop_one << std::endl; std::cout << "Generalized Torques obtained with modified loop" << std::endl << generalized_tau_loop_two << std::endl; std::cout << "Generalized Torques obtained with RNE - original loop" << std::endl << generalized_tau_slv-generalized_tau_loop_one << std::endl; std::cout << "Generalized Torques obtained with RNE - modified loop" << std::endl << generalized_tau_slv-generalized_tau_loop_two << std::endl; for(int i=0; i < (int)test_traversal.getNrOfVisitedLinks(); i++) { LinkMap::const_iterator link_it = test_traversal.getOrderedLink(i); int link_nmbr = link_it->getLinkIndex(); std::cout << "Link " << link_nmbr << std::endl; std::cout << "F_ext " << f_ext[link_nmbr] << std::endl; std::cout << "f_loop_one " << f_loop_one[link_nmbr] << std::endl; std::cout << "f_loop_two " << f_loop_two[link_nmbr] << std::endl; std::cout << "f_loop_one-f_loop_two " << f_loop_one[link_nmbr]-f_loop_two[link_nmbr] << std::endl; std::cout << "f_gi_loop_two " << f_gi_loop_two[link_nmbr] << std::endl; } if( (generalized_tau_slv-generalized_tau_loop_one).norm() > 1e-10 ) return -1; if( (generalized_tau_slv-generalized_tau_loop_two).norm() > 1e-10 ) return -1; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FilterContainer.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-16 17:53:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" #include <stdexcept> #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _FILTER_CONTAINER_HXX_ #include "FilterContainer.hxx" #endif #include <utility> #include <windows.h> //------------------------------------------------------------------- // namespace directives //------------------------------------------------------------------- using ::rtl::OUString; //------------------------------------------------------------------------------------- // ctor //------------------------------------------------------------------------------------- CFilterContainer::CFilterContainer( sal_Int32 initSize ) : m_vFilters( initSize ), m_bIterInitialized( sal_False ) { } //----------------------------------------------------------------------------------------- // add a name/filter pair //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::addFilter( const OUString& aName, const OUString& aFilter, sal_Bool bAllowDuplicates ) { // check if the filter is already in the container sal_Int32 pos = -1; if ( !bAllowDuplicates ) { pos = getFilterTagPos( aName ); if ( pos < 0 ) // if not there, append { m_vFilters.push_back( std::make_pair( aName, aFilter ) ); m_bIterInitialized = sal_False; } } else { m_vFilters.push_back( std::make_pair( aName, aFilter ) ); m_bIterInitialized = sal_False; } return ( pos < 0 ) ? sal_True : sal_False; } //----------------------------------------------------------------------------------------- // delete a filter // Precondition: the container is not empty // there is a filter identified by the given name //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::delFilter( const OUString& aName ) { OSL_ASSERT( m_vFilters.size() > 0 ); sal_Int32 pos = getFilterTagPos( aName ); if ( pos > -1 ) { m_vFilters.erase( ( m_vFilters.begin() + pos ) ); m_bIterInitialized = sal_False; } return ( pos > -1 ) ? sal_True : sal_False; } //----------------------------------------------------------------------------------------- // return the number of filters currently in the container //----------------------------------------------------------------------------------------- sal_Int32 SAL_CALL CFilterContainer::numFilter( ) { return m_vFilters.size( ); } //----------------------------------------------------------------------------------------- // clear all entries //----------------------------------------------------------------------------------------- void SAL_CALL CFilterContainer::empty() { m_vFilters.clear( ); } //----------------------------------------------------------------------------------------- // get a filter by name // Precondition: the container is not empty // there is a filter identified by the name //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::getFilter( const OUString& aName, OUString& theFilter ) const { OSL_PRECOND( m_vFilters.size() > 0, "Empty filter container" ); sal_Int32 pos = getFilterTagPos( aName ); try { if ( pos > -1 ) theFilter = m_vFilters.at( pos ).second; } catch( std::out_of_range& ) { OSL_ENSURE( sal_False, "Filter not in filter container" ); pos = -1; } return (pos > -1 ) ? sal_True : sal_False; } //----------------------------------------------------------------------------------------- // //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::getFilter( sal_Int32 aIndex, OUString& theFilter ) const { sal_Bool bRet = sal_True; try { theFilter = m_vFilters.at( aIndex ).first; } catch( std::out_of_range& ) { OSL_ENSURE( sal_False, "Filter index out of range" ); bRet = sal_False; } return bRet; } //----------------------------------------------------------------------------------------- // //----------------------------------------------------------------------------------------- sal_Int32 SAL_CALL CFilterContainer::getFilterPos( const OUString& aName ) const { return getFilterTagPos( aName ); } //----------------------------------------------------------------------------------------- // returns the index of the filter identified by name //----------------------------------------------------------------------------------------- sal_Int32 SAL_CALL CFilterContainer::getFilterTagPos( const OUString& aName ) const { if ( m_vFilters.size( ) > 0 ) { sal_Int32 i = 0; FILTER_VECTOR_T::const_iterator iter; FILTER_VECTOR_T::const_iterator iter_end = m_vFilters.end( ); for ( iter = m_vFilters.begin( ); iter != iter_end; ++iter, ++i ) if ( ( *iter ).first.equalsIgnoreAsciiCase( aName ) ) return i; } return -1; } //----------------------------------------------------------------------------------------- // starts enumerating the filter in the container //----------------------------------------------------------------------------------------- void SAL_CALL CFilterContainer::beginEnumFilter( ) { m_iter = m_vFilters.begin( ); m_bIterInitialized = sal_True; } //----------------------------------------------------------------------------------------- // returns true if another filter has been retrieved //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::getNextFilter( FILTER_ENTRY_T& nextFilterEntry ) { OSL_ASSERT( m_bIterInitialized ); sal_Bool bRet = ( m_iter != m_vFilters.end( ) ); if ( bRet ) nextFilterEntry = *m_iter++; else m_bIterInitialized = sal_False; return bRet; } //################################################################### //------------------------------------------------------------------- // calculates the length of a '\0' separated filter, that means // length of the name + '\0' + length of the filter string + // a trailing '\0' //------------------------------------------------------------------- static sal_uInt32 _getLengthFilter( CFilterContainer::FILTER_ENTRY_T aFilterEntry ) { return ( aFilterEntry.first.getLength( ) + 1 + aFilterEntry.second.getLength( ) + 1 ); } //------------------------------------------------------------------- // calculates the length of all filters currently in the container //------------------------------------------------------------------- static sal_uInt32 _getTotalFilterLength( CFilterContainer& aFilterContainer ) { CFilterContainer::FILTER_ENTRY_T nextFilter; aFilterContainer.beginEnumFilter( ); sal_uInt32 totalLength = 0; while( aFilterContainer.getNextFilter( nextFilter ) ) totalLength += _getLengthFilter( nextFilter ); return ( totalLength > 0 ) ? totalLength + 1 : totalLength; } //------------------------------------------------------------------- // //------------------------------------------------------------------- inline void _wcsmemcpy( sal_Unicode* pDest, const sal_Unicode* pSrc, sal_uInt32 nLength ) { memcpy( pDest, pSrc, nLength * sizeof( sal_Unicode ) ); } //------------------------------------------------------------------- // a helper trivial helper function to create a filter buffer in the // format the Win32 API requires, // e.g. "Text\0*.txt\0Doc\0*.doc;*xls\0\0" //------------------------------------------------------------------- rtl::OUString SAL_CALL makeWinFilterBuffer( CFilterContainer& aFilterContainer ) { // calculate the required buffer size sal_uInt32 reqBuffSize = _getTotalFilterLength( aFilterContainer ); sal_Unicode* pBuff; // return if there are no filters or the buffer could not // be allocated if ( !reqBuffSize || !( pBuff = new sal_Unicode[reqBuffSize] ) ) return OUString( ); // initialize the buffer with 0 ZeroMemory( pBuff, sizeof( sal_Unicode ) * reqBuffSize ); OUString winFilterBuff; CFilterContainer::FILTER_ENTRY_T nextFilter; sal_uInt32 memPos = 0; aFilterContainer.beginEnumFilter( ); while( aFilterContainer.getNextFilter( nextFilter ) ) { _wcsmemcpy( pBuff + memPos, nextFilter.first.getStr( ), nextFilter.first.getLength( ) ); memPos += nextFilter.first.getLength( ) + 1; _wcsmemcpy( pBuff + memPos, nextFilter.second.getStr( ), nextFilter.second.getLength( ) ); memPos += nextFilter.second.getLength( ) + 1 ; } winFilterBuff = OUString( pBuff, reqBuffSize ); // remove the allocated buffer delete [] pBuff; return winFilterBuff; } <commit_msg>INTEGRATION: CWS sb59 (1.3.100); FILE MERGED 2006/08/10 12:04:48 sb 1.3.100.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FilterContainer.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-10-12 10:48:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" #include <stdexcept> #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _FILTER_CONTAINER_HXX_ #include "FilterContainer.hxx" #endif #include <utility> #if defined _MSC_VER #pragma warning(push, 1) #endif #include <windows.h> #if defined _MSC_VER #pragma warning(pop) #endif //------------------------------------------------------------------- // namespace directives //------------------------------------------------------------------- using ::rtl::OUString; //------------------------------------------------------------------------------------- // ctor //------------------------------------------------------------------------------------- CFilterContainer::CFilterContainer( sal_Int32 initSize ) : m_vFilters( initSize ), m_bIterInitialized( sal_False ) { } //----------------------------------------------------------------------------------------- // add a name/filter pair //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::addFilter( const OUString& aName, const OUString& aFilter, sal_Bool bAllowDuplicates ) { // check if the filter is already in the container sal_Int32 pos = -1; if ( !bAllowDuplicates ) { pos = getFilterTagPos( aName ); if ( pos < 0 ) // if not there, append { m_vFilters.push_back( std::make_pair( aName, aFilter ) ); m_bIterInitialized = sal_False; } } else { m_vFilters.push_back( std::make_pair( aName, aFilter ) ); m_bIterInitialized = sal_False; } return ( pos < 0 ) ? sal_True : sal_False; } //----------------------------------------------------------------------------------------- // delete a filter // Precondition: the container is not empty // there is a filter identified by the given name //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::delFilter( const OUString& aName ) { OSL_ASSERT( m_vFilters.size() > 0 ); sal_Int32 pos = getFilterTagPos( aName ); if ( pos > -1 ) { m_vFilters.erase( ( m_vFilters.begin() + pos ) ); m_bIterInitialized = sal_False; } return ( pos > -1 ) ? sal_True : sal_False; } //----------------------------------------------------------------------------------------- // return the number of filters currently in the container //----------------------------------------------------------------------------------------- sal_Int32 SAL_CALL CFilterContainer::numFilter( ) { return m_vFilters.size( ); } //----------------------------------------------------------------------------------------- // clear all entries //----------------------------------------------------------------------------------------- void SAL_CALL CFilterContainer::empty() { m_vFilters.clear( ); } //----------------------------------------------------------------------------------------- // get a filter by name // Precondition: the container is not empty // there is a filter identified by the name //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::getFilter( const OUString& aName, OUString& theFilter ) const { OSL_PRECOND( m_vFilters.size() > 0, "Empty filter container" ); sal_Int32 pos = getFilterTagPos( aName ); try { if ( pos > -1 ) theFilter = m_vFilters.at( pos ).second; } catch( std::out_of_range& ) { OSL_ENSURE( sal_False, "Filter not in filter container" ); pos = -1; } return (pos > -1 ) ? sal_True : sal_False; } //----------------------------------------------------------------------------------------- // //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::getFilter( sal_Int32 aIndex, OUString& theFilter ) const { sal_Bool bRet = sal_True; try { theFilter = m_vFilters.at( aIndex ).first; } catch( std::out_of_range& ) { OSL_ENSURE( sal_False, "Filter index out of range" ); bRet = sal_False; } return bRet; } //----------------------------------------------------------------------------------------- // //----------------------------------------------------------------------------------------- sal_Int32 SAL_CALL CFilterContainer::getFilterPos( const OUString& aName ) const { return getFilterTagPos( aName ); } //----------------------------------------------------------------------------------------- // returns the index of the filter identified by name //----------------------------------------------------------------------------------------- sal_Int32 SAL_CALL CFilterContainer::getFilterTagPos( const OUString& aName ) const { if ( m_vFilters.size( ) > 0 ) { sal_Int32 i = 0; FILTER_VECTOR_T::const_iterator iter; FILTER_VECTOR_T::const_iterator iter_end = m_vFilters.end( ); for ( iter = m_vFilters.begin( ); iter != iter_end; ++iter, ++i ) if ( ( *iter ).first.equalsIgnoreAsciiCase( aName ) ) return i; } return -1; } //----------------------------------------------------------------------------------------- // starts enumerating the filter in the container //----------------------------------------------------------------------------------------- void SAL_CALL CFilterContainer::beginEnumFilter( ) { m_iter = m_vFilters.begin( ); m_bIterInitialized = sal_True; } //----------------------------------------------------------------------------------------- // returns true if another filter has been retrieved //----------------------------------------------------------------------------------------- sal_Bool SAL_CALL CFilterContainer::getNextFilter( FILTER_ENTRY_T& nextFilterEntry ) { OSL_ASSERT( m_bIterInitialized ); sal_Bool bRet = ( m_iter != m_vFilters.end( ) ); if ( bRet ) nextFilterEntry = *m_iter++; else m_bIterInitialized = sal_False; return bRet; } //################################################################### //------------------------------------------------------------------- // calculates the length of a '\0' separated filter, that means // length of the name + '\0' + length of the filter string + // a trailing '\0' //------------------------------------------------------------------- static sal_uInt32 _getLengthFilter( CFilterContainer::FILTER_ENTRY_T aFilterEntry ) { return ( aFilterEntry.first.getLength( ) + 1 + aFilterEntry.second.getLength( ) + 1 ); } //------------------------------------------------------------------- // calculates the length of all filters currently in the container //------------------------------------------------------------------- static sal_uInt32 _getTotalFilterLength( CFilterContainer& aFilterContainer ) { CFilterContainer::FILTER_ENTRY_T nextFilter; aFilterContainer.beginEnumFilter( ); sal_uInt32 totalLength = 0; while( aFilterContainer.getNextFilter( nextFilter ) ) totalLength += _getLengthFilter( nextFilter ); return ( totalLength > 0 ) ? totalLength + 1 : totalLength; } //------------------------------------------------------------------- // //------------------------------------------------------------------- inline void _wcsmemcpy( sal_Unicode* pDest, const sal_Unicode* pSrc, sal_uInt32 nLength ) { memcpy( pDest, pSrc, nLength * sizeof( sal_Unicode ) ); } //------------------------------------------------------------------- // a helper trivial helper function to create a filter buffer in the // format the Win32 API requires, // e.g. "Text\0*.txt\0Doc\0*.doc;*xls\0\0" //------------------------------------------------------------------- rtl::OUString SAL_CALL makeWinFilterBuffer( CFilterContainer& aFilterContainer ) { // calculate the required buffer size sal_uInt32 reqBuffSize = _getTotalFilterLength( aFilterContainer ); // return if there are no filters if ( !reqBuffSize ) return OUString( ); sal_Unicode* pBuff = new sal_Unicode[reqBuffSize]; // initialize the buffer with 0 ZeroMemory( pBuff, sizeof( sal_Unicode ) * reqBuffSize ); OUString winFilterBuff; CFilterContainer::FILTER_ENTRY_T nextFilter; sal_uInt32 memPos = 0; aFilterContainer.beginEnumFilter( ); while( aFilterContainer.getNextFilter( nextFilter ) ) { _wcsmemcpy( pBuff + memPos, nextFilter.first.getStr( ), nextFilter.first.getLength( ) ); memPos += nextFilter.first.getLength( ) + 1; _wcsmemcpy( pBuff + memPos, nextFilter.second.getStr( ), nextFilter.second.getLength( ) ); memPos += nextFilter.second.getLength( ) + 1 ; } winFilterBuff = OUString( pBuff, reqBuffSize ); // remove the allocated buffer delete [] pBuff; return winFilterBuff; } <|endoftext|>
<commit_before>// Overload.cpp /* * Copyright (C) 2013 Spencer T. Parkin * * This software has been released under the MIT License. * See the "License.txt" file in the project root directory * for more information about this license. * */ #include "lua.hpp" #include "Overload.h" #include "Operation.h" #include "String.h" #include "UserData.h" #include "Index.h" //========================================================================================= static const char* userDataMetaTableName = "__galua_userdata_metatable__"; //========================================================================================= // 1 is returned on success. 0 on failure. // This is really a count of how many items we pushed. int l_push_userdata_metatable( lua_State* L ) { // Ultimately we will find the meta-table at global scope. lua_pushglobaltable( L ); // This should never take more than 2 tries. for( int tryCount = 0; tryCount < 2; tryCount++ ) { // Return the cached meta-table if it already exists. lua_getfield( L, -1, userDataMetaTableName ); if( !lua_isnil( L, -1 ) ) { // We push only the desired return value on the stack. lua_remove( L, -2 ); return 1; } // Remove the nil value. lua_pop( L, 1 ); // Start a meta-table for the user-data value we'll hand back. lua_newtable( L ); // Register this function so that when the value is garbage collected, we free the user-data memory. lua_pushcfunction( L, &DeleteGALuaUserData ); lua_setfield( L, -2, "__gc" ); // Register useful overloads. lua_pushcfunction( L, &l_sum ); lua_setfield( L, -2, "__add" ); lua_pushcfunction( L, &l_dif ); lua_setfield( L, -2, "__sub" ); lua_pushcfunction( L, &l_gp ); lua_setfield( L, -2, "__mul" ); lua_pushcfunction( L, &l_ip ); lua_setfield( L, -2, "__mod" ); lua_pushcfunction( L, &l_op ); lua_setfield( L, -2, "__pow" ); // Provide compatibility with the built-in "tostring" function. lua_pushcfunction( L, &l_to_string ); lua_setfield( L, -2, "__tostring" ); // These meta-methods will provide a convenient way to get and set the // grade parts of a multi-vector if given an integer key. Otherwise, // we will use the given string key to look-up a desired user-data method. lua_pushcfunction( L, &l_index ); lua_setfield( L, -2, "__index" ); lua_pushcfunction( L, &l_newindex ); lua_setfield( L, -2, "__newindex" ); // Provide a convenient way to take the magnitude of and negate a multi-vector. lua_pushcfunction( L, &l_mag ); lua_setfield( L, -2, "__len" ); lua_pushcfunction( L, &l_neg ); lua_setfield( L, -2, "__unm" ); // Cache off the table for future use. This also pops the table we just created. lua_setfield( L, -2, userDataMetaTableName ); } // If we get here, then something went wrong! lua_pop( L, 1 ); return 0; } // Overload.cpp<commit_msg>make code a little cleaner<commit_after>// Overload.cpp /* * Copyright (C) 2013 Spencer T. Parkin * * This software has been released under the MIT License. * See the "License.txt" file in the project root directory * for more information about this license. * */ #include "lua.hpp" #include "Overload.h" #include "Operation.h" #include "String.h" #include "UserData.h" #include "Index.h" //========================================================================================= static const char* userDataMetaTableName = "__galua_userdata_metatable__"; //========================================================================================= // 1 is returned on success. 0 on failure. // This is really a count of how many items we pushed. int l_push_userdata_metatable( lua_State* L ) { // Ultimately we will find the meta-table at global scope. lua_pushglobaltable( L ); // This should never take more than 2 tries. int tryCount = 0; while( true ) { // Return the cached meta-table if it already exists. lua_getfield( L, -1, userDataMetaTableName ); if( !lua_isnil( L, -1 ) ) { // We push only the desired return value on the stack. lua_remove( L, -2 ); return 1; } // Remove the nil value. lua_pop( L, 1 ); // It should never take more than two tries. if( ++tryCount >= 2 ) break; // Start a meta-table for the user-data value we'll hand back. lua_newtable( L ); // Register this function so that when the value is garbage collected, we free the user-data memory. lua_pushcfunction( L, &DeleteGALuaUserData ); lua_setfield( L, -2, "__gc" ); // Register useful overloads. lua_pushcfunction( L, &l_sum ); lua_setfield( L, -2, "__add" ); lua_pushcfunction( L, &l_dif ); lua_setfield( L, -2, "__sub" ); lua_pushcfunction( L, &l_gp ); lua_setfield( L, -2, "__mul" ); lua_pushcfunction( L, &l_ip ); lua_setfield( L, -2, "__mod" ); lua_pushcfunction( L, &l_op ); lua_setfield( L, -2, "__pow" ); // Provide compatibility with the built-in "tostring" function. lua_pushcfunction( L, &l_to_string ); lua_setfield( L, -2, "__tostring" ); // These meta-methods will provide a convenient way to get and set the // grade parts of a multi-vector if given an integer key. Otherwise, // we will use the given string key to look-up a desired user-data method. lua_pushcfunction( L, &l_index ); lua_setfield( L, -2, "__index" ); lua_pushcfunction( L, &l_newindex ); lua_setfield( L, -2, "__newindex" ); // Provide a convenient way to take the magnitude of and negate a multi-vector. lua_pushcfunction( L, &l_mag ); lua_setfield( L, -2, "__len" ); lua_pushcfunction( L, &l_neg ); lua_setfield( L, -2, "__unm" ); // Cache off the table for future use. This also pops the table we just created. lua_setfield( L, -2, userDataMetaTableName ); } // If we get here, then something went wrong! lua_pop( L, 1 ); return 0; } // Overload.cpp<|endoftext|>
<commit_before><commit_msg>Forgot to adjust GCF computation after FFT api change.<commit_after><|endoftext|>
<commit_before>// --------------------------------------------------------------------- // // Copyright (C) 2016 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/python.hpp> #include <deal.II/grid/tria.h> #include <deal.II/grid/grid_generator.h> #include <fstream> char const *pydealii_docstring = " \n" "PyDealII \n" "======== \n" "Some interesting doc. \n" ; unsigned int n_active_cells(const dealii::Triangulation<2> &triangulation) { return triangulation.n_active_cells(); } void generate_cube(dealii::Triangulation<2> &triangulation) { dealii::GridGenerator::hyper_cube(triangulation); } void save(const dealii::Triangulation<2> &triangulation, const std::string filename) { std::ofstream ofs(filename); boost::archive::text_oarchive oa(ofs); oa << triangulation; } void load(dealii::Triangulation<2> &triangulation, const std::string filename) { std::ifstream ifs(filename); boost::archive::text_iarchive ia(ifs); ia >> triangulation; } BOOST_PYTHON_MODULE(PyDealII) { boost::python::scope().attr("__doc__") = pydealii_docstring; boost::python::docstring_options doc_options; doc_options.enable_user_defined(); doc_options.enable_py_signatures(); doc_options.disable_cpp_signatures(); boost::python::class_<dealii::Triangulation<2>> ("Triangulation") .def("n_active_cells", &n_active_cells, "Return the number of active cells", boost::python::args("self")) .def("generate_cube", &generate_cube, "Generate a hypercube", boost::python::args("self")) .def("refine_global", &dealii::Triangulation<2>::refine_global, "Refine the mesh uniformly", boost::python::args("self", "times")) .def("save", &save, "Serialize and save the triangulation", boost::python::args("self", "filename")) .def("load", &load, "Load and deserialize a triangulation", boost::python::args("self", "filename")); } <commit_msg>Add default arguments for GridGenerator::hyper_cube.<commit_after>// --------------------------------------------------------------------- // // Copyright (C) 2016 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/python.hpp> #include <deal.II/grid/tria.h> #include <deal.II/grid/grid_generator.h> #include <fstream> char const *pydealii_docstring = " \n" "PyDealII \n" "======== \n" "Some interesting doc. \n" ; unsigned int n_active_cells(const dealii::Triangulation<2> &triangulation) { return triangulation.n_active_cells(); } void generate_hyper_cube(dealii::Triangulation<2> &triangulation, const double left=0., const double right=0., const bool colorize=false) { dealii::GridGenerator::hyper_cube(triangulation); } void save(const dealii::Triangulation<2> &triangulation, const std::string filename) { std::ofstream ofs(filename); boost::archive::text_oarchive oa(ofs); oa << triangulation; } void load(dealii::Triangulation<2> &triangulation, const std::string filename) { std::ifstream ifs(filename); boost::archive::text_iarchive ia(ifs); ia >> triangulation; } // Macro to enable default arguments BOOST_PYTHON_FUNCTION_OVERLOADS(generate_hyper_cube_overloads, generate_hyper_cube, 1, 4) BOOST_PYTHON_MODULE(PyDealII) { boost::python::scope().attr("__doc__") = pydealii_docstring; boost::python::docstring_options doc_options; doc_options.enable_user_defined(); doc_options.enable_py_signatures(); doc_options.disable_cpp_signatures(); boost::python::class_<dealii::Triangulation<2>> ("Triangulation") .def("n_active_cells", n_active_cells, "Return the number of active cells", boost::python::args("self")) .def("generate_hyper_cube", generate_hyper_cube, generate_hyper_cube_overloads( boost::python::args("self", "left", "right", "colorize"), "Generate a hyper_cube.")) .def("refine_global", &dealii::Triangulation<2>::refine_global, "Refine the mesh uniformly", boost::python::args("self", "times")) .def("save", save, "Serialize and save the triangulation", boost::python::args("self", "filename")) .def("load", load, "Load and deserialize a triangulation", boost::python::args("self", "filename")); } <|endoftext|>
<commit_before>/* ** Copyright 2014-2016 The Earlham Institute ** ** 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. */ /* * drmaa_args_processor.cpp * * Created on: 27 Oct 2016 * Author: billy */ #include "drmaa_tool_args_processor.hpp" #include "string_utils.h" #include "streams.h" DrmaaToolArgsProcessor :: DrmaaToolArgsProcessor (DrmaaTool *drmaa_p) : dtap_drmaa_p (drmaa_p) { } DrmaaToolArgsProcessor :: ~DrmaaToolArgsProcessor () { } bool DrmaaToolArgsProcessor :: AddArg (const char *arg_s, const bool hyphen_flag) { bool success_flag = AddDrmaaToolArgument (dtap_drmaa_p, arg_s); if (hyphen_flag) { char *value_s = ConcatenateStrings ("-", arg_s); if (value_s) { success_flag = AddDrmaaToolArgument (dtap_drmaa_p, value_s); FreeCopiedString (value_s); } else { PrintErrors (STM_LEVEL_WARNING, __FILE__, __LINE__, "Failed to concatenate \"-\" and \"%s\"", arg_s); } } else { success_flag = AddDrmaaToolArgument (dtap_drmaa_p, arg_s); } return success_flag; } <commit_msg>fixed compile errors<commit_after>/* ** Copyright 2014-2016 The Earlham Institute ** ** 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. */ /* * drmaa_args_processor.cpp * * Created on: 27 Oct 2016 * Author: billy */ #include "drmaa_tool_args_processor.hpp" #include "string_utils.h" #include "streams.h" DrmaaToolArgsProcessor :: DrmaaToolArgsProcessor (DrmaaTool *drmaa_p) : dtap_drmaa_p (drmaa_p) { } DrmaaToolArgsProcessor :: ~DrmaaToolArgsProcessor () { } bool DrmaaToolArgsProcessor :: AddArg (const char *arg_s, const bool hyphen_flag) { bool success_flag = false; if (hyphen_flag) { char *value_s = ConcatenateStrings ("-", arg_s); if (value_s) { success_flag = AddDrmaaToolArgument (dtap_drmaa_p, value_s); FreeCopiedString (value_s); } else { PrintErrors (STM_LEVEL_WARNING, __FILE__, __LINE__, "Failed to concatenate \"-\" and \"%s\"", arg_s); } } else { success_flag = AddDrmaaToolArgument (dtap_drmaa_p, arg_s); } return success_flag; } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "Binding_Base.h" #include "Binding_Data.h" #include "Binding_Link.h" #include <sofa/helper/vector.h> #include <sofa/core/objectmodel/Base.h> #include <sofa/core/objectmodel/BaseData.h> using namespace sofa::core::objectmodel; #include <sofa/helper/logging/Messaging.h> #include "PythonFactory.h" extern "C" PyObject * Base_findData(PyObject *self, PyObject *args ) { Base* obj=((PySPtr<Base>*)self)->object.get(); char *dataName; if (!PyArg_ParseTuple(args, "s",&dataName)) { msg_error("Base_findData") <<"Base_findData_impl not a string\n"; Py_RETURN_NONE; } BaseData * data = obj->findData(dataName); if (!data) { if( obj->hasField(dataName) ) msg_error("Base_findData")<<"object '"<<obj->getName()<<"' has a field '"<<dataName<<"' but it is not a Data"; else { msg_error("Base_findData")<<"object '"<<obj->getName()<<"' does no have a field '"<<dataName<<"'"; std::stringstream s; obj->writeDatas(s,";"); msg_error("Base_findData")<<s.str(); } PyErr_BadArgument(); return NULL; } // special cases... from factory (e.g DisplayFlags, OptionsGroup) { PyObject* res = sofa::PythonFactory::toPython(data); if( res ) return res; } return SP_BUILD_PYPTR(Data,BaseData,data,false); } extern "C" PyObject * Base_findLink(PyObject *self, PyObject *args) { Base* obj=((PySPtr<Base>*)self)->object.get(); char *linkName; if (!PyArg_ParseTuple(args, "s",&linkName)) Py_RETURN_NONE; BaseLink * link = obj->findLink(linkName); if (!link) { if( obj->hasField(linkName) ) msg_error("Base_findLink")<<"object '"<<obj->getName()<<"' has a field '"<<linkName<<"' but it is not a Link"; else { msg_error("Base_findLink")<<"object '"<<obj->getName()<<"' does no have a field '"<<linkName<<"'"; std::stringstream s; obj->writeDatas(s,";"); msg_error("Base_findLink")<<s.str(); } PyErr_BadArgument(); return NULL; } return SP_BUILD_PYPTR(Link,BaseLink,link,false); } // Generic accessor to Data fields (in python native type) extern "C" PyObject* Base_GetAttr(PyObject *o, PyObject *attr_name) { Base* obj=down_cast<Base>(((PySPtr<Base>*)o)->object.get()); char *attrName = PyString_AsString(attr_name); // printf("Base_GetAttr type=%s name=%s attrName=%s\n",obj->getClassName().c_str(),obj->getName().c_str(),attrName); // see if a Data field has this name... if( BaseData * data = obj->findData(attrName) ) { // special cases... from factory (e.g DisplayFlags, OptionsGroup) if( PyObject* res = sofa::PythonFactory::toPython(data) ) return res; else // the data type is not known by the factory, let's create the right Python type.... return GetDataValuePython(data); } // see if a Link has this name... if( BaseLink * link = obj->findLink(attrName) ) return GetLinkValuePython(link); // we have our link... let's create the right Python type.... // printf("Base_GetAttr ERROR data not found - type=%s name=%s attrName=%s\n",obj->getClassName().c_str(),obj->getName().c_str(),attrName); return PyObject_GenericGetAttr(o,attr_name); } extern "C" int Base_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) { // attribute does not exist: see if a Data field has this name... Base* obj=down_cast<Base>(((PySPtr<Base>*)o)->object.get()); char *attrName = PyString_AsString(attr_name); // printf("Base_SetAttr name=%s\n",attrName); if (BaseData * data = obj->findData(attrName)) { // data types in Factory can have a specific setter if( PyObject* pyData = sofa::PythonFactory::toPython(data) ) return PyObject_SetAttrString( pyData, "value", v ); else // the data type is not known by the factory, let's use the default implementation return SetDataValuePython(data,v); } if (BaseLink * link = obj->findLink(attrName)) return SetLinkValuePython(link,v); return PyObject_GenericSetAttr(o,attr_name,v); } extern "C" PyObject * Base_getClassName(PyObject * self, PyObject * /*args*/) { // BaseNode is not bound in SofaPython, so getPathName is bound in Node instead Base* node = ((PySPtr<Base>*)self)->object.get(); return PyString_FromString(node->getClassName().c_str()); } extern "C" PyObject * Base_getTemplateName(PyObject * self, PyObject * /*args*/) { // BaseNode is not bound in SofaPython, so getPathName is bound in Node instead Base* node = ((PySPtr<Base>*)self)->object.get(); return PyString_FromString(node->getTemplateName().c_str()); } extern "C" PyObject * Base_getName(PyObject * self, PyObject * /*args*/) { // BaseNode is not bound in SofaPython, so getPathName is bound in Node instead Base* node = ((PySPtr<Base>*)self)->object.get(); return PyString_FromString(node->getName().c_str()); } extern "C" PyObject * Base_getDataFields(PyObject *self, PyObject * /*args*/) { Base * component = ((PySPtr<Base>*)self)->object.get(); if(!component) { PyErr_BadArgument(); return NULL; } const sofa::helper::vector<BaseData*> dataFields = component->getDataFields(); PyObject * pyDict = PyDict_New(); for (size_t i=0; i<dataFields.size(); i++) PyDict_SetItem(pyDict, PyString_FromString(dataFields[i]->getName().c_str()), GetDataValuePython(dataFields[i])); return pyDict; } // down cast to the lower type known by the factory // there is maybe a more pythonish way to do so? :) extern "C" PyObject * Base_downCast(PyObject *self, PyObject * /*args*/) { Base* component = ((PySPtr<Base>*)self)->object.get(); return sofa::PythonFactory::toPython(component); } SP_CLASS_METHODS_BEGIN(Base) SP_CLASS_METHOD(Base,findData) SP_CLASS_METHOD(Base,findLink) SP_CLASS_METHOD(Base,getClassName) SP_CLASS_METHOD(Base,getTemplateName) SP_CLASS_METHOD(Base,getName) SP_CLASS_METHOD(Base,getDataFields) SP_CLASS_METHOD(Base,downCast) SP_CLASS_METHODS_END //SP_CLASS_DATA_ATTRIBUTE(Base,name) SP_CLASS_ATTRS_BEGIN(Base) //SP_CLASS_ATTR(Base,name) SP_CLASS_ATTRS_END SP_CLASS_TYPE_BASE_SPTR_ATTR_GETATTR(Base,Base) <commit_msg>[SofaPython] minor comment fix<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "Binding_Base.h" #include "Binding_Data.h" #include "Binding_Link.h" #include <sofa/helper/vector.h> #include <sofa/core/objectmodel/Base.h> #include <sofa/core/objectmodel/BaseData.h> using namespace sofa::core::objectmodel; #include <sofa/helper/logging/Messaging.h> #include "PythonFactory.h" extern "C" PyObject * Base_findData(PyObject *self, PyObject *args ) { Base* obj=((PySPtr<Base>*)self)->object.get(); char *dataName; if (!PyArg_ParseTuple(args, "s",&dataName)) { msg_error("Base_findData") <<"Base_findData_impl not a string\n"; Py_RETURN_NONE; } BaseData * data = obj->findData(dataName); if (!data) { if( obj->hasField(dataName) ) msg_error("Base_findData")<<"object '"<<obj->getName()<<"' has a field '"<<dataName<<"' but it is not a Data"; else { msg_error("Base_findData")<<"object '"<<obj->getName()<<"' does no have a field '"<<dataName<<"'"; std::stringstream s; obj->writeDatas(s,";"); msg_error("Base_findData")<<s.str(); } PyErr_BadArgument(); return NULL; } // special cases... from factory (e.g DisplayFlags, OptionsGroup) { PyObject* res = sofa::PythonFactory::toPython(data); if( res ) return res; } return SP_BUILD_PYPTR(Data,BaseData,data,false); } extern "C" PyObject * Base_findLink(PyObject *self, PyObject *args) { Base* obj=((PySPtr<Base>*)self)->object.get(); char *linkName; if (!PyArg_ParseTuple(args, "s",&linkName)) Py_RETURN_NONE; BaseLink * link = obj->findLink(linkName); if (!link) { if( obj->hasField(linkName) ) msg_error("Base_findLink")<<"object '"<<obj->getName()<<"' has a field '"<<linkName<<"' but it is not a Link"; else { msg_error("Base_findLink")<<"object '"<<obj->getName()<<"' does no have a field '"<<linkName<<"'"; std::stringstream s; obj->writeDatas(s,";"); msg_error("Base_findLink")<<s.str(); } PyErr_BadArgument(); return NULL; } return SP_BUILD_PYPTR(Link,BaseLink,link,false); } // Generic accessor to Data fields (in python native type) extern "C" PyObject* Base_GetAttr(PyObject *o, PyObject *attr_name) { Base* obj=down_cast<Base>(((PySPtr<Base>*)o)->object.get()); char *attrName = PyString_AsString(attr_name); // printf("Base_GetAttr type=%s name=%s attrName=%s\n",obj->getClassName().c_str(),obj->getName().c_str(),attrName); // see if a Data field has this name... if( BaseData * data = obj->findData(attrName) ) { // special cases... from factory (e.g DisplayFlags, OptionsGroup) if( PyObject* res = sofa::PythonFactory::toPython(data) ) return res; else // the data type is not known by the factory, let's create the right Python type.... return GetDataValuePython(data); } // see if a Link has this name... if( BaseLink * link = obj->findLink(attrName) ) return GetLinkValuePython(link); // we have our link... let's create the right Python type.... // printf("Base_GetAttr ERROR data not found - type=%s name=%s attrName=%s\n",obj->getClassName().c_str(),obj->getName().c_str(),attrName); return PyObject_GenericGetAttr(o,attr_name); } extern "C" int Base_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) { // attribute does not exist: see if a Data field has this name... Base* obj=down_cast<Base>(((PySPtr<Base>*)o)->object.get()); char *attrName = PyString_AsString(attr_name); // printf("Base_SetAttr name=%s\n",attrName); if (BaseData * data = obj->findData(attrName)) { // data types in Factory can have a specific setter if( PyObject* pyData = sofa::PythonFactory::toPython(data) ) return PyObject_SetAttrString( pyData, "value", v ); else // the data type is not known by the factory, let's use the default implementation return SetDataValuePython(data,v); } if (BaseLink * link = obj->findLink(attrName)) return SetLinkValuePython(link,v); return PyObject_GenericSetAttr(o,attr_name,v); } extern "C" PyObject * Base_getClassName(PyObject * self, PyObject * /*args*/) { // BaseNode is not bound in SofaPython, so getPathName is bound in Node instead Base* node = ((PySPtr<Base>*)self)->object.get(); return PyString_FromString(node->getClassName().c_str()); } extern "C" PyObject * Base_getTemplateName(PyObject * self, PyObject * /*args*/) { // BaseNode is not bound in SofaPython, so getPathName is bound in Node instead Base* node = ((PySPtr<Base>*)self)->object.get(); return PyString_FromString(node->getTemplateName().c_str()); } extern "C" PyObject * Base_getName(PyObject * self, PyObject * /*args*/) { // BaseNode is not bound in SofaPython, so getPathName is bound in Node instead Base* node = ((PySPtr<Base>*)self)->object.get(); return PyString_FromString(node->getName().c_str()); } extern "C" PyObject * Base_getDataFields(PyObject *self, PyObject * /*args*/) { Base * component = ((PySPtr<Base>*)self)->object.get(); if(!component) { PyErr_BadArgument(); return NULL; } const sofa::helper::vector<BaseData*> dataFields = component->getDataFields(); PyObject * pyDict = PyDict_New(); for (size_t i=0; i<dataFields.size(); i++) PyDict_SetItem(pyDict, PyString_FromString(dataFields[i]->getName().c_str()), GetDataValuePython(dataFields[i])); return pyDict; } // down cast to the lowest type known by the factory // there is maybe a more pythonish way to do so? :) extern "C" PyObject * Base_downCast(PyObject *self, PyObject * /*args*/) { Base* component = ((PySPtr<Base>*)self)->object.get(); return sofa::PythonFactory::toPython(component); } SP_CLASS_METHODS_BEGIN(Base) SP_CLASS_METHOD(Base,findData) SP_CLASS_METHOD(Base,findLink) SP_CLASS_METHOD(Base,getClassName) SP_CLASS_METHOD(Base,getTemplateName) SP_CLASS_METHOD(Base,getName) SP_CLASS_METHOD(Base,getDataFields) SP_CLASS_METHOD(Base,downCast) SP_CLASS_METHODS_END //SP_CLASS_DATA_ATTRIBUTE(Base,name) SP_CLASS_ATTRS_BEGIN(Base) //SP_CLASS_ATTR(Base,name) SP_CLASS_ATTRS_END SP_CLASS_TYPE_BASE_SPTR_ATTR_GETATTR(Base,Base) <|endoftext|>
<commit_before>#include "../../testing/testing.hpp" #include "../feature_bucketer.hpp" #include "../../indexer/feature.hpp" #include "../../indexer/mercator.hpp" #include "../../indexer/cell_id.hpp" #include "../../indexer/classificator_loader.hpp" #include "../../platform/platform.hpp" #include "../../indexer/indexer_tests/feature_routine.hpp" #include "../../base/stl_add.hpp" namespace { class PushBackFeatureDebugStringOutput { public: typedef map<string, vector<string> > * InitDataType; PushBackFeatureDebugStringOutput(string const & name, InitDataType const & initData) : m_pContainer(&((*initData)[name])) { } void operator() (FeatureBuilder1 const & fb) { FeatureType f; FeatureBuilder2Feature( static_cast<FeatureBuilder2 &>(const_cast<FeatureBuilder1 &>(fb)), f); m_pContainer->push_back(f.DebugString(0)); } private: vector<string> * m_pContainer; }; typedef feature::CellFeatureBucketer< PushBackFeatureDebugStringOutput, feature::SimpleFeatureClipper, MercatorBounds, RectId > FeatureBucketer; } UNIT_TEST(FeatureBucketerSmokeTest) { Platform & pl = GetPlatform(); // classificator is needed because inside bucketer we're use it in WorldMapGenerator // @TODO clean up or remove cell bucketer and replace with world countries bucketer classificator::Read(pl.GetReader("drawing_rules.bin"), pl.GetReader("classificator.txt"), pl.GetReader("visibility.txt"), pl.GetReader("types.txt")); map<string, vector<string> > out, expectedOut; FeatureBucketer bucketer(1, &out); uint32_t const defType = classificator::GetTestDefaultType(); FeatureBuilder2 fb; fb.AddPoint(m2::PointD(10, 10)); fb.AddPoint(m2::PointD(20, 20)); fb.AddType(defType); fb.SetLinear(); bucketer(fb); FeatureType f; FeatureBuilder2Feature(fb, f); expectedOut["3"].push_back(f.DebugString(0)); TEST_EQUAL(out, expectedOut, ()); vector<string> bucketNames; bucketer.GetBucketNames(MakeBackInsertFunctor(bucketNames)); TEST_EQUAL(bucketNames, vector<string>(1, "3"), ()); } <commit_msg>Remove unused file.<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_getecid.C /// /// @brief Get ECID string from target using SCOM //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com> // *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com> // *HWP FW Owner : sunil kumar <skumar8j@in.ibm.com> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #include "p9_getecid.H" #include <p9_misc_scom_addresses.H> #include <p9_misc_scom_addresses_fld.H> #include <p9_const_common.H> // The bit locations in ecid_part02 where the DD Level is found. These correspond to ECID bits 173:175 constexpr uint64_t DD_LEVEL(45); constexpr uint64_t DD_LEVEL_LEN(3); static fapi2::ReturnCode setup_pcie_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); { // Workarounds for DD1.00 modulues fapi2::ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR_Type l_ec_feature_pcie_lock_phase_rotator = 0; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR, i_target, l_ec_feature_pcie_lock_phase_rotator), "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR)"); if (l_ec_feature_pcie_lock_phase_rotator && (l_version < ddLevelPciePart)) { FAPI_DBG("seeing version 1.00 (0x%x) setting attributes", l_version); uint8_t l_value = 1; for (auto& l_pec_trgt : i_target.getChildren<fapi2::TARGET_TYPE_PEC>(fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_PCIE_PCS_RX_ROT_EXTEL, l_pec_trgt, l_value), "Error from FAPI_ATTR_SET (ATTR_PROC_PCIE_PCS_RX_ROT_EXTEL)"); } } } { // Workarounds for DD1.01/DD1.02 modules fapi2::ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC_Type l_ec_feature_pcie_disable_fddc = 0; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC, i_target, l_ec_feature_pcie_disable_fddc), "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC)"); if (l_ec_feature_pcie_disable_fddc && (l_version >= ddLevelPciePart)) { FAPI_DBG("seeing version >= 1.01 (0x%x) setting attributes", l_version); uint8_t l_value = 0; for (auto& l_pec_trgt : i_target.getChildren<fapi2::TARGET_TYPE_PEC>(fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_PCIE_PCS_RX_DFE_FDDC, l_pec_trgt, l_value), "Error from FAPI_ATTR_SET (ATTR_PROC_PCIE_PCS_RX_DFE_FDDC)"); } } } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } static fapi2::ReturnCode setup_memory_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); // Workarounds for modules which are before 1.02 (memory part 1) if (l_version < ddLevelMemoryPart1) { FAPI_DBG("seeing version < 1.02 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_WR_VREF, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_VREF_DAC, i_target, l_value) ); } // Workarounds for modules which are before 1.03 (memory part 2) if (l_version < ddLevelMemoryPart2) { FAPI_DBG("seeing version < 1.03 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_TRAINING_BAD_BITS, i_target, l_value) ); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, fapi2::variable_buffer& o_fuseString) { uint64_t attr_data[2]; fapi2::buffer<uint64_t> l_ecid_part0_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part1_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part2_data64 = 0; fapi2::variable_buffer l_fuseString(fuseString_len); FAPI_INF("Entering ..."); FAPI_DBG("extract and manipulate ECID data"); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART0_REGISTER, l_ecid_part0_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART1_REGISTER, l_ecid_part1_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART2_REGISTER, l_ecid_part2_data64)); l_ecid_part0_data64.reverse(); l_ecid_part1_data64.reverse(); l_ecid_part2_data64.reverse(); attr_data[0] = l_ecid_part0_data64(); attr_data[1] = l_ecid_part1_data64(); FAPI_TRY(l_fuseString.insert(l_ecid_part0_data64(), 0, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part1_data64(), 64, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part2_data64(), 128, 48)); o_fuseString = l_fuseString; FAPI_DBG("push fuse string into attribute"); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ECID, i_target_chip, attr_data)); // Set some attributes memory can used to make work-around decisions. FAPI_TRY( setup_memory_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_TRY( setup_pcie_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_INF("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <commit_msg>Added periodic cal fix - fixes bad delays<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_getecid.C /// /// @brief Get ECID string from target using SCOM //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com> // *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com> // *HWP FW Owner : sunil kumar <skumar8j@in.ibm.com> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #include "p9_getecid.H" #include <p9_misc_scom_addresses.H> #include <p9_misc_scom_addresses_fld.H> #include <p9_const_common.H> // The bit locations in ecid_part02 where the DD Level is found. These correspond to ECID bits 173:175 constexpr uint64_t DD_LEVEL(45); constexpr uint64_t DD_LEVEL_LEN(3); static fapi2::ReturnCode setup_pcie_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); { // Workarounds for DD1.00 modulues fapi2::ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR_Type l_ec_feature_pcie_lock_phase_rotator = 0; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR, i_target, l_ec_feature_pcie_lock_phase_rotator), "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_PCIE_LOCK_PHASE_ROTATOR)"); if (l_ec_feature_pcie_lock_phase_rotator && (l_version < ddLevelPciePart)) { FAPI_DBG("seeing version 1.00 (0x%x) setting attributes", l_version); uint8_t l_value = 1; for (auto& l_pec_trgt : i_target.getChildren<fapi2::TARGET_TYPE_PEC>(fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_PCIE_PCS_RX_ROT_EXTEL, l_pec_trgt, l_value), "Error from FAPI_ATTR_SET (ATTR_PROC_PCIE_PCS_RX_ROT_EXTEL)"); } } } { // Workarounds for DD1.01/DD1.02 modules fapi2::ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC_Type l_ec_feature_pcie_disable_fddc = 0; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC, i_target, l_ec_feature_pcie_disable_fddc), "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_PCIE_DISABLE_FDDC)"); if (l_ec_feature_pcie_disable_fddc && (l_version >= ddLevelPciePart)) { FAPI_DBG("seeing version >= 1.01 (0x%x) setting attributes", l_version); uint8_t l_value = 0; for (auto& l_pec_trgt : i_target.getChildren<fapi2::TARGET_TYPE_PEC>(fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PROC_PCIE_PCS_RX_DFE_FDDC, l_pec_trgt, l_value), "Error from FAPI_ATTR_SET (ATTR_PROC_PCIE_PCS_RX_DFE_FDDC)"); } } } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } static fapi2::ReturnCode setup_memory_work_around_attributes( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const fapi2::buffer<uint64_t>& i_ecid_part) { uint8_t l_version = 0; i_ecid_part.extractToRight<DD_LEVEL, DD_LEVEL_LEN>(l_version); // Workarounds for modules which are before 1.02 (memory part 1) if (l_version < ddLevelMemoryPart1) { FAPI_DBG("seeing version < 1.02 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_WR_VREF, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_VREF_DAC, i_target, l_value) ); } // Workarounds for modules which are before 1.03 (memory part 2) if (l_version < ddLevelMemoryPart2) { FAPI_DBG("seeing version < 1.03 (0x%x) setting attributes", l_version); // All these attributes have 1 as their 'YES' enum value uint8_t l_value = 1; FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_MSS_TRAINING_BAD_BITS, i_target, l_value) ); FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_DO_BLUE_WATERFALL_ADJUST, i_target, l_value) ); } return fapi2::FAPI2_RC_SUCCESS; fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, fapi2::variable_buffer& o_fuseString) { uint64_t attr_data[2]; fapi2::buffer<uint64_t> l_ecid_part0_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part1_data64 = 0; fapi2::buffer<uint64_t> l_ecid_part2_data64 = 0; fapi2::variable_buffer l_fuseString(fuseString_len); FAPI_INF("Entering ..."); FAPI_DBG("extract and manipulate ECID data"); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART0_REGISTER, l_ecid_part0_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART1_REGISTER, l_ecid_part1_data64)); FAPI_TRY(fapi2::getScom(i_target_chip, PU_OTPROM0_ECID_PART2_REGISTER, l_ecid_part2_data64)); l_ecid_part0_data64.reverse(); l_ecid_part1_data64.reverse(); l_ecid_part2_data64.reverse(); attr_data[0] = l_ecid_part0_data64(); attr_data[1] = l_ecid_part1_data64(); FAPI_TRY(l_fuseString.insert(l_ecid_part0_data64(), 0, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part1_data64(), 64, 64)); FAPI_TRY(l_fuseString.insert(l_ecid_part2_data64(), 128, 48)); o_fuseString = l_fuseString; FAPI_DBG("push fuse string into attribute"); FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_ECID, i_target_chip, attr_data)); // Set some attributes memory can used to make work-around decisions. FAPI_TRY( setup_memory_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_TRY( setup_pcie_work_around_attributes(i_target_chip, l_ecid_part2_data64) ); FAPI_INF("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_getecid.H /// /// @brief Get ECID string from target using SCOM //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com> // *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com> // *HWP FW Owner : sunil kumar <skumar8j@in.ibm.com> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #ifndef _GETECID_H_ #define _GETECID_H_ #include <fapi2.H> enum P9_GETECID_Private_Constants { fuseString_len = 192, // fuse string length ddLevelPciePart = 0b100, // bit field in ecid buffer representing DD1.01 ddLevelMemoryPart1 = 0b110, // bit field in ecid buffer representing DD1.02 ddLevelMemoryPart2 = 0b111, // bit field in ecid buffer representing DD1.03 }; typedef fapi2::ReturnCode (*p9_getecid_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&, fapi2::variable_buffer& fuseString); /// @brief Get ECID string from target using SCOM /// /// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target /// @return FAPI2_RC_SUCCESS if success, else error code. extern "C" { fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, fapi2::variable_buffer& o_fuseString); } #endif <commit_msg>Set ATTR_MINI_EC for Firmware use<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_getecid.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p9_getecid.H /// /// @brief Get ECID string from target using SCOM //------------------------------------------------------------------------------ // *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com> // *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com> // *HWP FW Owner : sunil kumar <skumar8j@in.ibm.com> // *HWP Team : Perv // *HWP Level : 2 // *HWP Consumed by : SBE //------------------------------------------------------------------------------ #ifndef _GETECID_H_ #define _GETECID_H_ #include <fapi2.H> enum P9_GETECID_Public_Constants { p9_getecid_fuseString_len = 192, // fuse string length }; typedef fapi2::ReturnCode (*p9_getecid_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&, fapi2::variable_buffer& fuseString); /// @brief Get ECID string from target using SCOM /// /// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target /// @return FAPI2_RC_SUCCESS if success, else error code. extern "C" { fapi2::ReturnCode p9_getecid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip, fapi2::variable_buffer& o_fuseString); } #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> #include <mapnik/memory_datasource.hpp> #ifdef MAPNIK_DEBUG //#include <mapnik/wall_clock_timer.hpp> #endif // boost #include <boost/foreach.hpp> //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { /** Calls the renderer's process function, * \param output Renderer * \param f Feature to process * \param prj_trans Projection * \param sym Symbolizer object */ struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0) : m_(m), scale_factor_(scale_factor) {} void apply() { #ifdef MAPNIK_DEBUG //mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: "); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); Map::const_metawriter_iterator metaItr = m_.begin_metawriters(); Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->start(); } try { projection proj(m_.srs()); // map projection double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); scale_denom *= scale_factor_; #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif BOOST_FOREACH ( layer const& lyr, m_.layers() ) { if (lyr.isVisible(scale_denom)) { apply_to_layer(lyr, p, proj, scale_denom); } } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } metaItr = m_.begin_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->stop(); } p.end_map_processing(m_); } private: void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom) { #ifdef MAPNIK_DEBUG //wall_clock_progress_timer timer(clog, "end layer rendering: "); #endif boost::shared_ptr<datasource> ds = lay.datasource(); if (!ds) { std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n"; return; } p.start_layer_processing(lay); if (ds) { box2d<double> ext = m_.get_buffered_extent(); projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); box2d<double> layer_ext = lay.envelope(); double lx0 = layer_ext.minx(); double ly0 = layer_ext.miny(); double lz0 = 0.0; double lx1 = layer_ext.maxx(); double ly1 = layer_ext.maxy(); double lz1 = 0.0; // back project layers extent into main map projection prj_trans.backward(lx0,ly0,lz0); prj_trans.backward(lx1,ly1,lz1); // if no intersection then nothing to do for layer if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() ) { return; } // clip query bbox lx0 = std::max(ext.minx(),lx0); ly0 = std::max(ext.miny(),ly0); lx1 = std::min(ext.maxx(),lx1); ly1 = std::min(ext.maxy(),ly1); prj_trans.forward(lx0,ly0,lz0); prj_trans.forward(lx1,ly1,lz1); box2d<double> bbox(lx0,ly0,lx1,ly1); query::resolution_type res(m_.width()/m_.get_current_extent().width(),m_.height()/m_.get_current_extent().height()); query q(bbox,res,scale_denom); //BBOX query std::vector<feature_type_style*> active_styles; std::set<std::string> names; attribute_collector collector(names); std::vector<std::string> const& style_names = lay.styles(); // iterate through all named styles collecting active styles and attribute names BOOST_FOREACH(std::string const& style_name, style_names) { boost::optional<feature_type_style const&> style=m_.find_style(style_name); if (!style) { std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n"; continue; } const std::vector<rule_type>& rules=(*style).get_rules(); bool active_rules=false; BOOST_FOREACH(rule_type const& rule, rules) { if (rule.active(scale_denom)) { active_rules = true; if (ds->type() == datasource::Vector) { collector(rule); } // TODO - in the future rasters should be able to be filtered. } } if (active_rules) { active_styles.push_back(const_cast<feature_type_style*>(&(*style))); } } // push all property names BOOST_FOREACH(std::string const& name, names) { q.add_property_name(name); } memory_datasource cache; bool cache_features = style_names.size()>1?true:false; bool first = true; BOOST_FOREACH (feature_type_style * style, active_styles) { std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; std::vector<rule_type> const& rules=style->get_rules(); BOOST_FOREACH(rule_type const& rule, rules) { if (rule.active(scale_denom)) { if (rule.has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&rule)); } else { if_rules.push_back(const_cast<rule_type*>(&rule)); } if (ds->type() == datasource::Raster) { if (ds->params().get<double>("filter_factor",0.0) == 0.0) { rule_type::symbolizers const& symbols = rule.get_symbolizers(); rule_type::symbolizers::const_iterator symIter = symbols.begin(); rule_type::symbolizers::const_iterator symEnd = symbols.end(); for (;symIter != symEnd;++symIter) { try { raster_symbolizer const& sym = boost::get<raster_symbolizer>(*symIter); std::string const& scaling = sym.get_scaling(); if (scaling == "bilinear" || scaling == "bilinear8" ) { // todo - allow setting custom value in symbolizer property? q.filter_factor(2.0); } } catch (const boost::bad_get &v) { // case where useless symbolizer is attached to raster layer //throw config_error("Invalid Symbolizer type supplied, only RasterSymbolizer is supported"); } } } } } } // process features featureset_ptr fs; if (first) { first = false; fs = ds->features(q); } else { fs = cache.features(q); } if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; if (cache_features) { cache.push(feature); } BOOST_FOREACH(rule_type * rule, if_rules ) { expression_ptr const& expr=rule->get_filter(); value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr); if (result.to_bool()) { do_else=false; rule_type::symbolizers const& symbols = rule->get_symbolizers(); BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),sym); } } } if (do_else) { BOOST_FOREACH( rule_type * rule, else_rules ) { rule_type::symbolizers const& symbols = rule->get_symbolizers(); BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),sym); } } } } cache_features = false; } } } p.end_layer_processing(lay); } Map const& m_; double scale_factor_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <commit_msg>only using cache-first logic if caching features<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> #include <mapnik/memory_datasource.hpp> #ifdef MAPNIK_DEBUG //#include <mapnik/wall_clock_timer.hpp> #endif // boost #include <boost/foreach.hpp> //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { /** Calls the renderer's process function, * \param output Renderer * \param f Feature to process * \param prj_trans Projection * \param sym Symbolizer object */ struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0) : m_(m), scale_factor_(scale_factor) {} void apply() { #ifdef MAPNIK_DEBUG //mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: "); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); Map::const_metawriter_iterator metaItr = m_.begin_metawriters(); Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->start(); } try { projection proj(m_.srs()); // map projection double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); scale_denom *= scale_factor_; #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif BOOST_FOREACH ( layer const& lyr, m_.layers() ) { if (lyr.isVisible(scale_denom)) { apply_to_layer(lyr, p, proj, scale_denom); } } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } metaItr = m_.begin_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->stop(); } p.end_map_processing(m_); } private: void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom) { #ifdef MAPNIK_DEBUG //wall_clock_progress_timer timer(clog, "end layer rendering: "); #endif boost::shared_ptr<datasource> ds = lay.datasource(); if (!ds) { std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n"; return; } p.start_layer_processing(lay); if (ds) { box2d<double> ext = m_.get_buffered_extent(); projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); box2d<double> layer_ext = lay.envelope(); double lx0 = layer_ext.minx(); double ly0 = layer_ext.miny(); double lz0 = 0.0; double lx1 = layer_ext.maxx(); double ly1 = layer_ext.maxy(); double lz1 = 0.0; // back project layers extent into main map projection prj_trans.backward(lx0,ly0,lz0); prj_trans.backward(lx1,ly1,lz1); // if no intersection then nothing to do for layer if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() ) { return; } // clip query bbox lx0 = std::max(ext.minx(),lx0); ly0 = std::max(ext.miny(),ly0); lx1 = std::min(ext.maxx(),lx1); ly1 = std::min(ext.maxy(),ly1); prj_trans.forward(lx0,ly0,lz0); prj_trans.forward(lx1,ly1,lz1); box2d<double> bbox(lx0,ly0,lx1,ly1); query::resolution_type res(m_.width()/m_.get_current_extent().width(),m_.height()/m_.get_current_extent().height()); query q(bbox,res,scale_denom); //BBOX query std::vector<feature_type_style*> active_styles; std::set<std::string> names; attribute_collector collector(names); std::vector<std::string> const& style_names = lay.styles(); // iterate through all named styles collecting active styles and attribute names BOOST_FOREACH(std::string const& style_name, style_names) { boost::optional<feature_type_style const&> style=m_.find_style(style_name); if (!style) { std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n"; continue; } const std::vector<rule_type>& rules=(*style).get_rules(); bool active_rules=false; BOOST_FOREACH(rule_type const& rule, rules) { if (rule.active(scale_denom)) { active_rules = true; if (ds->type() == datasource::Vector) { collector(rule); } // TODO - in the future rasters should be able to be filtered. } } if (active_rules) { active_styles.push_back(const_cast<feature_type_style*>(&(*style))); } } // push all property names BOOST_FOREACH(std::string const& name, names) { q.add_property_name(name); } memory_datasource cache; bool cache_features = style_names.size()>1?true:false; bool first = true; BOOST_FOREACH (feature_type_style * style, active_styles) { std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; std::vector<rule_type> const& rules=style->get_rules(); BOOST_FOREACH(rule_type const& rule, rules) { if (rule.active(scale_denom)) { if (rule.has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&rule)); } else { if_rules.push_back(const_cast<rule_type*>(&rule)); } if (ds->type() == datasource::Raster) { if (ds->params().get<double>("filter_factor",0.0) == 0.0) { rule_type::symbolizers const& symbols = rule.get_symbolizers(); rule_type::symbolizers::const_iterator symIter = symbols.begin(); rule_type::symbolizers::const_iterator symEnd = symbols.end(); for (;symIter != symEnd;++symIter) { try { raster_symbolizer const& sym = boost::get<raster_symbolizer>(*symIter); std::string const& scaling = sym.get_scaling(); if (scaling == "bilinear" || scaling == "bilinear8" ) { // todo - allow setting custom value in symbolizer property? q.filter_factor(2.0); } } catch (const boost::bad_get &v) { // case where useless symbolizer is attached to raster layer //throw config_error("Invalid Symbolizer type supplied, only RasterSymbolizer is supported"); } } } } } } // process features featureset_ptr fs; if (cache_features) { if (first) { first = false; fs = ds->features(q); } else { fs = cache.features(q); } } else { fs = ds->features(q); } if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; if (cache_features) { cache.push(feature); } BOOST_FOREACH(rule_type * rule, if_rules ) { expression_ptr const& expr=rule->get_filter(); value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr); if (result.to_bool()) { do_else=false; rule_type::symbolizers const& symbols = rule->get_symbolizers(); BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),sym); } } } if (do_else) { BOOST_FOREACH( rule_type * rule, else_rules ) { rule_type::symbolizers const& symbols = rule->get_symbolizers(); BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor (symbol_dispatch(p,*feature,prj_trans),sym); } } } } cache_features = false; } } } p.end_layer_processing(lay); } Map const& m_; double scale_factor_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <|endoftext|>
<commit_before><commit_msg>Update Ngen.Content.File.cpp<commit_after> #include <Ngen.hpp> namespace Ngen { namespace Content { class Path { public: static const string& SystemPathChar() const; static string GetLastNode(const string& node=const_string("/\|")); }; class FileInfo { public: const string& FileName() const { string result = string::Empty(); return result; } protected: string mFullPath; }; class File : public virtual Stream { }; } } <|endoftext|>
<commit_before>//This program created by love by Hadi - Copyright(c) by Hadi Abdi Khojasteh - Summer 2017. All right reserved. / Email: hkhojasteh@iasbs.ac.ir, info@hadiabdikhojasteh.ir / Website: iasbs.ac.ir/~hkhojasteh, hadiabdikhojasteh.ir #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/xfeatures2d.hpp> #include <opencv2/ml/ml.hpp> #include <iostream> #include <vector> #include <algorithm> #include <random> #include <math.h> #include <time.h> using namespace std; using namespace cv; using namespace cv::ml; typedef tuple<char, uint32_t> enumerate; struct IncGenerator { uint32_t current_; IncGenerator(uint32_t start) : current_(start) {} uint32_t operator() () { return current_++; } }; vector<uint32_t> sample(Mat1d, uint32_t, uint32_t); void lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev); uint32_t data_size, vocab_size; Mat1d Wxh, Whh, Why, bh, by; //model parameters uint32_t main() { srand(time(NULL)); vector<char> data; vector<char> chars; vector<enumerate> charenum; FILE* inputfile; string fileName = "input.txt"; inputfile = fopen(fileName.c_str(), "r"); uint32_t i = 0; while (!feof(inputfile)) { char inchar[1] = { 0 }; fscanf(inputfile, "%c", inchar); data.push_back(inchar[0]); auto it = find_if(chars.begin(), chars.end(), [&](const char element) { return element == inchar[0]; }); //If this is not in the char set if (it == end(chars)) { chars.push_back(inchar[0]); charenum.push_back(make_tuple(inchar[0], i)); i++; } } fclose(inputfile); data_size = data.size(); vocab_size = chars.size(); printf("data has %d characters, %d unique.\n", data_size, vocab_size); vector<enumerate> char_to_ix = charenum; reverse(charenum.begin(), charenum.end()); vector<enumerate> ix_to_char = charenum; //hyperparameters uint32_t hidden_size = 100; //size of hidden layer of neurons uint32_t seq_length = 25; //number of steps to unroll the RNN for double learning_rate = 1e-1; Wxh.create(hidden_size, vocab_size); //Or: Mat mat(2, 4, CV_64FC1); Whh.create(hidden_size, hidden_size); Why.create(vocab_size, hidden_size); double mean = 0.0, stddev = 1.0 / 3.0; //99.7% of values will be inside [-1, +1] interval randn(Wxh, Scalar(mean), Scalar(stddev)); //input to hidden randn(Whh, Scalar(mean), Scalar(stddev)); //hidden to hidden randn(Why, Scalar(mean), Scalar(stddev)); //hidden to output bh = Mat::zeros(hidden_size, 1, CV_32F); //hidden bias by = Mat::zeros(vocab_size, 1, CV_32F); //output bias uint32_t n = 0, p = 0; //Make an array of zeros with the same shape and type as a Ws array. Mat1d mWxh = Mat::zeros(Wxh.size(), Wxh.type()); Mat1d mWhh = Mat::zeros(Whh.size(), Whh.type()); Mat1d mWhy = Mat::zeros(Why.size(), Why.type()); Mat1d mbh = Mat::zeros(bh.size(), bh.type()); //memory variables for Adagrad Mat1d mby = Mat::zeros(by.size(), by.type()); //memory variables for Adagrad //loss at iteration 0 double smooth_loss = -log(1.0 / vocab_size) * seq_length; Mat1d loss, dWxh, dWhh, dWhy, dbh, dby, hprev; vector<enumerate> inputs, targets; for (uint32_t i = 0; i < 1000; i++) { //Prepare inputs (we're sweeping from left to right in steps seq_length long) if (p + seq_length + 1 >= data.size() || n == 0) { hprev = Mat::zeros(hidden_size, 1, CV_32F); //reset RNN memory p = 0; //go from start of data } inputs.clear(); targets.clear(); for (uint32_t i = 0; i < seq_length && p + i < char_to_ix.size(); i++) { inputs.push_back(char_to_ix[p + i]); targets.push_back(char_to_ix[p + 1 + i]); } //Sample from the model now and then if (n % 100 == 0) { vector<uint32_t> sampWords = sample(hprev, p + i, 200); for (uint32_t i = 0; i < sampWords.size(); i++) { printf("%c", get<0>(ix_to_char[sampWords[i]])); } printf("\n"); } lossFun(inputs, targets, hprev); p += seq_length; //move data pointer n += 1; //iteration counter } return 0; } vector<uint32_t> sample(Mat1d h, uint32_t seed_ix, uint32_t n) { //sample a sequence of integers from the model h is memory state, // seed_ix is seed letter for first time step Mat1d x = Mat::zeros(vocab_size, 1, CV_32F); x[seed_ix][0] = 1.0; vector<uint32_t> ixes; for (uint32_t i = 0; i < n; i++) { Mat1d t = (Wxh * x) + (Whh * h) + bh; Mat1d h = Mat::zeros(t.size(), t.type()); for (uint32_t i = 0; i < t.rows; i++) { h[i][0] = tanh(t[i][0]); } Mat1d y = (Why * h) + by; Mat1d expy; exp(y, expy); Mat1d p = expy / sum(expy)[0]; p = p.reshape(1, 1); //Generates a random sample from a given 1-D array default_random_engine generator; discrete_distribution<int> distribution(p.begin(), p.end()); vector<double> indices(p.size().width); generate(indices.begin(), indices.end(), [&generator, &distribution]() { return distribution(generator); }); vector<int> incNumbers(p.size().width); IncGenerator gi(0); generate(incNumbers.begin(), incNumbers.end(), gi); Mat1d x = Mat::zeros(vocab_size, 1, CV_32F); int randSelect = (uint32_t)rand() % vocab_size; x[randSelect][0] = 1.0; ixes.push_back(randSelect); } return ixes; } void lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev) { //inputs, targets are both list of integers. // hprev is Hx1 array of initial hidden state // returns the loss, gradients on model parameters, and last hidden state Mat1d hs = hprev; double loss = 0.0; //forward pass for (uint32_t t = 0; t < inputs.size(); t++) { //encode in 1-of-k Mat1d xs = Mat::zeros(inputs.size(), vocab_size, CV_32F); xs[t][get<1>(inputs[t])] = 1; Mat1d val = (Wxh * xs.row(t).t()); for (uint32_t i = 0; i < val.rows; i++) { hs[i][0] = tanh(val[i][0]); Mat1d temp = (Whh * hs[i - 1][0]); hs[i][0] += temp[i][0] + bh[i][0]; //hidden state } Mat1d ys = (Why * hs[t][0]) + by[t][0]; //unnormalized log probabilities for next chars //probabilities for next chars Mat1d ps = Mat::zeros(ys.size(), ys.type()); double sum = 0.0; for (uint32_t i = 0; i < ys.rows; i++) { sum += ps[t][i]; ps[t][i] = exp(ys[t][i]); } for (uint32_t i = 0; i < ys.rows; i++) { ps[t][0] = ps[t][0] / sum; } loss += -log(ps[t][get<1>(targets[t])]); //softmax (cross-entropy loss) } } <commit_msg>backward pass: compute gradients going backwards<commit_after>//This program created by love by Hadi - Copyright(c) by Hadi Abdi Khojasteh - Summer 2017. All right reserved. / Email: hkhojasteh@iasbs.ac.ir, info@hadiabdikhojasteh.ir / Website: iasbs.ac.ir/~hkhojasteh, hadiabdikhojasteh.ir #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/xfeatures2d.hpp> #include <opencv2/ml/ml.hpp> #include <iostream> #include <vector> #include <algorithm> #include <random> #include <math.h> #include <time.h> using namespace std; using namespace cv; using namespace cv::ml; typedef tuple<char, uint32_t> enumerate; struct IncGenerator { uint32_t current_; IncGenerator(uint32_t start) : current_(start) {} uint32_t operator() () { return current_++; } }; vector<uint32_t> sample(Mat1d, uint32_t, uint32_t); void lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev); uint32_t data_size, vocab_size; Mat1d Wxh, Whh, Why, bh, by; //model parameters uint32_t main() { srand(time(NULL)); vector<char> data; vector<char> chars; vector<enumerate> charenum; FILE* inputfile; string fileName = "input.txt"; inputfile = fopen(fileName.c_str(), "r"); uint32_t i = 0; while (!feof(inputfile)) { char inchar[1] = { 0 }; fscanf(inputfile, "%c", inchar); data.push_back(inchar[0]); auto it = find_if(chars.begin(), chars.end(), [&](const char element) { return element == inchar[0]; }); //If this is not in the char set if (it == end(chars)) { chars.push_back(inchar[0]); charenum.push_back(make_tuple(inchar[0], i)); i++; } } fclose(inputfile); data_size = data.size(); vocab_size = chars.size(); printf("data has %d characters, %d unique.\n", data_size, vocab_size); vector<enumerate> char_to_ix = charenum; reverse(charenum.begin(), charenum.end()); vector<enumerate> ix_to_char = charenum; //hyperparameters uint32_t hidden_size = 100; //size of hidden layer of neurons uint32_t seq_length = 25; //number of steps to unroll the RNN for double learning_rate = 1e-1; Wxh.create(hidden_size, vocab_size); //Or: Mat mat(2, 4, CV_64FC1); Whh.create(hidden_size, hidden_size); Why.create(vocab_size, hidden_size); double mean = 0.0, stddev = 1.0 / 3.0; //99.7% of values will be inside [-1, +1] interval randn(Wxh, Scalar(mean), Scalar(stddev)); //input to hidden randn(Whh, Scalar(mean), Scalar(stddev)); //hidden to hidden randn(Why, Scalar(mean), Scalar(stddev)); //hidden to output bh = Mat::zeros(hidden_size, 1, CV_32F); //hidden bias by = Mat::zeros(vocab_size, 1, CV_32F); //output bias uint32_t n = 0, p = 0; //Make an array of zeros with the same shape and type as a Ws array. Mat1d mWxh = Mat::zeros(Wxh.size(), Wxh.type()); Mat1d mWhh = Mat::zeros(Whh.size(), Whh.type()); Mat1d mWhy = Mat::zeros(Why.size(), Why.type()); Mat1d mbh = Mat::zeros(bh.size(), bh.type()); //memory variables for Adagrad Mat1d mby = Mat::zeros(by.size(), by.type()); //memory variables for Adagrad //loss at iteration 0 double smooth_loss = -log(1.0 / vocab_size) * seq_length; Mat1d loss, dWxh, dWhh, dWhy, dbh, dby, hprev; vector<enumerate> inputs, targets; for (uint32_t i = 0; i < 1000; i++) { //Prepare inputs (we're sweeping from left to right in steps seq_length long) if (p + seq_length + 1 >= data.size() || n == 0) { hprev = Mat::zeros(hidden_size, 1, CV_32F); //reset RNN memory p = 0; //go from start of data } inputs.clear(); targets.clear(); for (uint32_t i = 0; i < seq_length && p + i < char_to_ix.size(); i++) { inputs.push_back(char_to_ix[p + i]); targets.push_back(char_to_ix[p + 1 + i]); } //Sample from the model now and then if (n % 100 == 0) { vector<uint32_t> sampWords = sample(hprev, p + i, 200); for (uint32_t i = 0; i < sampWords.size(); i++) { printf("%c", get<0>(ix_to_char[sampWords[i]])); } printf("\n"); } lossFun(inputs, targets, hprev); p += seq_length; //move data pointer n += 1; //iteration counter } return 0; } vector<uint32_t> sample(Mat1d h, uint32_t seed_ix, uint32_t n) { //sample a sequence of integers from the model h is memory state, // seed_ix is seed letter for first time step Mat1d x = Mat::zeros(vocab_size, 1, CV_32F); x[seed_ix][0] = 1.0; vector<uint32_t> ixes; for (uint32_t i = 0; i < n; i++) { Mat1d t = (Wxh * x) + (Whh * h) + bh; Mat1d h = Mat::zeros(t.size(), t.type()); for (uint32_t i = 0; i < t.rows; i++) { h[i][0] = tanh(t[i][0]); } Mat1d y = (Why * h) + by; Mat1d expy; exp(y, expy); Mat1d p = expy / sum(expy)[0]; p = p.reshape(1, 1); //Generates a random sample from a given 1-D array default_random_engine generator; discrete_distribution<int> distribution(p.begin(), p.end()); vector<double> indices(p.size().width); generate(indices.begin(), indices.end(), [&generator, &distribution]() { return distribution(generator); }); vector<int> incNumbers(p.size().width); IncGenerator gi(0); generate(incNumbers.begin(), incNumbers.end(), gi); Mat1d x = Mat::zeros(vocab_size, 1, CV_32F); int randSelect = (uint32_t)rand() % vocab_size; x[randSelect][0] = 1.0; ixes.push_back(randSelect); } return ixes; } void lossFun(vector<enumerate> inputs, vector<enumerate> targets, Mat1d hprev) { //inputs, targets are both list of integers. // hprev is Hx1 array of initial hidden state // returns the loss, gradients on model parameters, and last hidden state Mat1d hs = hprev; double loss = 0.0; Mat1d ps; //forward pass for (uint32_t t = 0; t < inputs.size(); t++) { //encode in 1-of-k Mat1d xs = Mat::zeros(inputs.size(), vocab_size, CV_32F); xs[t][get<1>(inputs[t])] = 1; Mat1d val = (Wxh * xs.row(t).t()); for (uint32_t i = 0; i < val.rows; i++) { hs[i][0] = tanh(val[i][0]); Mat1d temp = (Whh * hs[i - 1][0]); hs[i][0] += temp[i][0] + bh[i][0]; //hidden state } Mat1d ys = (Why * hs[t][0]) + by[t][0]; //unnormalized log probabilities for next chars //probabilities for next chars ps = Mat::zeros(ys.size(), ys.type()); double sum = 0.0; for (uint32_t i = 0; i < ys.rows; i++) { sum += ps[t][i]; ps[t][i] = exp(ys[t][i]); } for (uint32_t i = 0; i < ys.rows; i++) { ps[t][0] = ps[t][0] / sum; } loss += -log(ps[t][get<1>(targets[t])]); //softmax (cross-entropy loss) } //backward pass: compute gradients going backwards Mat1d dWxh = Mat::zeros(Wxh.size(), Wxh.type()); Mat1d dWhh = Mat::zeros(Whh.size(), Whh.type()); Mat1d dWhy = Mat::zeros(Why.size(), Why.type()); Mat1d dbh = Mat::zeros(bh.size(), bh.type()); Mat1d dby = Mat::zeros(by.size(), by.type()); Mat1d dhnext = Mat::zeros(hs.size(), hs.type()); for (uint32_t t = inputs.size() - 1; t >= 0; t--){ //backprop into y Mat1d dy = Mat::zeros(ps.size(), ps.type()); dy[get<1>(targets[t])][0] -= 1; dWhy += dy * hs; } } <|endoftext|>
<commit_before>/* * GLDepthStencilState.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "GLDepthStencilState.h" #include "../Ext/GLExtensions.h" #include "../../GLCommon/GLExtensionRegistry.h" #include "../../GLCommon/GLCore.h" #include "../../GLCommon/GLTypes.h" #include "../../../Core/HelperMacros.h" #include "GLStateManager.h" #include <LLGL/PipelineStateFlags.h> namespace LLGL { GLDepthStencilState::GLDepthStencilState(const DepthDescriptor& depthDesc, const StencilDescriptor& stencilDesc) { /* Convert depth states */ depthTestEnabled_ = depthDesc.testEnabled; depthMask_ = GLBoolean(depthDesc.writeEnabled); depthFunc_ = GLTypes::Map(depthDesc.compareOp); /* Convert stencil states */ stencilTestEnabled_ = stencilDesc.testEnabled; referenceDynamic_ = stencilDesc.referenceDynamic; GLStencilFaceState::Convert(stencilFront_, stencilDesc.front, stencilDesc.referenceDynamic); GLStencilFaceState::Convert(stencilBack_, stencilDesc.back, stencilDesc.referenceDynamic); independentStencilFaces_ = (GLStencilFaceState::CompareSWO(stencilFront_, stencilBack_) == 0); } void GLDepthStencilState::Bind(GLStateManager& stateMngr) { /* Setup depth state */ if (depthTestEnabled_) { stateMngr.Enable(GLState::DEPTH_TEST); stateMngr.SetDepthFunc(depthFunc_); } else stateMngr.Disable(GLState::DEPTH_TEST); stateMngr.SetDepthMask(depthMask_); /* Setup stencil state */ if (stencilTestEnabled_) { stateMngr.Enable(GLState::STENCIL_TEST); if (independentStencilFaces_) { BindStencilFaceState(stencilFront_, GL_FRONT); BindStencilFaceState(stencilBack_, GL_BACK); } else BindStencilState(stencilFront_); } else stateMngr.Disable(GLState::STENCIL_TEST); } void GLDepthStencilState::BindStencilRefOnly(GLint ref, GLenum face) { if (independentStencilFaces_) { switch (face) { case GL_FRONT_AND_BACK: glStencilFuncSeparate(GL_FRONT, stencilFront_.func, ref, stencilFront_.mask); glStencilFuncSeparate(GL_BACK, stencilBack_.func, ref, stencilBack_.mask); break; case GL_FRONT: glStencilFuncSeparate(GL_FRONT, stencilFront_.func, ref, stencilFront_.mask); break; case GL_BACK: glStencilFuncSeparate(GL_BACK, stencilBack_.func, ref, stencilBack_.mask); break; } } else { switch (face) { case GL_FRONT_AND_BACK: glStencilFunc(stencilFront_.func, ref, stencilFront_.mask); break; case GL_FRONT: glStencilFuncSeparate(GL_FRONT, stencilFront_.func, ref, stencilFront_.mask); break; case GL_BACK: glStencilFuncSeparate(GL_BACK, stencilBack_.func, ref, stencilBack_.mask); break; } } } int GLDepthStencilState::CompareSWO(const GLDepthStencilState& rhs) const { const auto& lhs = *this; LLGL_COMPARE_BOOL_MEMBER_SWO( depthTestEnabled_ ); if (depthTestEnabled_) { LLGL_COMPARE_MEMBER_SWO( depthMask_ ); LLGL_COMPARE_MEMBER_SWO( depthFunc_ ); } LLGL_COMPARE_BOOL_MEMBER_SWO( stencilTestEnabled_ ); if (stencilTestEnabled_) { LLGL_COMPARE_BOOL_MEMBER_SWO( independentStencilFaces_ ); { auto order = GLStencilFaceState::CompareSWO(stencilFront_, rhs.stencilFront_); if (order != 0) return order; } if (!independentStencilFaces_) { auto order = GLStencilFaceState::CompareSWO(stencilBack_, rhs.stencilBack_); if (order != 0) return order; } } return 0; } /* * ======= Private: ======= */ void GLDepthStencilState::BindStencilFaceState(const GLStencilFaceState& state, GLenum face) { glStencilOpSeparate(face, state.sfail, state.dpfail, state.dppass); if (!referenceDynamic_) glStencilFuncSeparate(face, state.func, state.ref, state.mask); glStencilMaskSeparate(face, state.writeMask); } void GLDepthStencilState::BindStencilState(const GLStencilFaceState& state) { glStencilOp(state.sfail, state.dpfail, state.dppass); if (!referenceDynamic_) glStencilFunc(state.func, state.ref, state.mask); glStencilMask(state.writeMask); } /* * GLDrawBufferState struct */ void GLDepthStencilState::GLStencilFaceState::Convert(GLStencilFaceState& dst, const StencilFaceDescriptor& src, bool referenceDynamic) { dst.sfail = GLTypes::Map(src.stencilFailOp); dst.dpfail = GLTypes::Map(src.depthFailOp); dst.dppass = GLTypes::Map(src.depthPassOp); dst.func = GLTypes::Map(src.compareOp); dst.ref = (referenceDynamic ? 0 : static_cast<GLint>(src.reference)); dst.mask = src.readMask; dst.writeMask = src.writeMask; } int GLDepthStencilState::GLStencilFaceState::CompareSWO(const GLStencilFaceState& lhs, const GLStencilFaceState& rhs) { LLGL_COMPARE_MEMBER_SWO( sfail ); LLGL_COMPARE_MEMBER_SWO( dpfail ); LLGL_COMPARE_MEMBER_SWO( dppass ); LLGL_COMPARE_MEMBER_SWO( func ); LLGL_COMPARE_MEMBER_SWO( ref ); LLGL_COMPARE_MEMBER_SWO( mask ); LLGL_COMPARE_MEMBER_SWO( writeMask ); return 0; } } // /namespace LLGL // ================================================================================ <commit_msg>Fixed condition for independent stencil faces in <GLDepthStencilState> class.<commit_after>/* * GLDepthStencilState.cpp * * This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "GLDepthStencilState.h" #include "../Ext/GLExtensions.h" #include "../../GLCommon/GLExtensionRegistry.h" #include "../../GLCommon/GLCore.h" #include "../../GLCommon/GLTypes.h" #include "../../../Core/HelperMacros.h" #include "GLStateManager.h" #include <LLGL/PipelineStateFlags.h> namespace LLGL { GLDepthStencilState::GLDepthStencilState(const DepthDescriptor& depthDesc, const StencilDescriptor& stencilDesc) { /* Convert depth states */ depthTestEnabled_ = depthDesc.testEnabled; depthMask_ = GLBoolean(depthDesc.writeEnabled); depthFunc_ = GLTypes::Map(depthDesc.compareOp); /* Convert stencil states */ stencilTestEnabled_ = stencilDesc.testEnabled; referenceDynamic_ = stencilDesc.referenceDynamic; GLStencilFaceState::Convert(stencilFront_, stencilDesc.front, stencilDesc.referenceDynamic); GLStencilFaceState::Convert(stencilBack_, stencilDesc.back, stencilDesc.referenceDynamic); independentStencilFaces_ = (GLStencilFaceState::CompareSWO(stencilFront_, stencilBack_) != 0); } void GLDepthStencilState::Bind(GLStateManager& stateMngr) { /* Setup depth state */ if (depthTestEnabled_) { stateMngr.Enable(GLState::DEPTH_TEST); stateMngr.SetDepthFunc(depthFunc_); } else stateMngr.Disable(GLState::DEPTH_TEST); stateMngr.SetDepthMask(depthMask_); /* Setup stencil state */ if (stencilTestEnabled_) { stateMngr.Enable(GLState::STENCIL_TEST); if (independentStencilFaces_) { BindStencilFaceState(stencilFront_, GL_FRONT); BindStencilFaceState(stencilBack_, GL_BACK); } else BindStencilState(stencilFront_); } else stateMngr.Disable(GLState::STENCIL_TEST); } void GLDepthStencilState::BindStencilRefOnly(GLint ref, GLenum face) { if (independentStencilFaces_) { switch (face) { case GL_FRONT_AND_BACK: glStencilFuncSeparate(GL_FRONT, stencilFront_.func, ref, stencilFront_.mask); glStencilFuncSeparate(GL_BACK, stencilBack_.func, ref, stencilBack_.mask); break; case GL_FRONT: glStencilFuncSeparate(GL_FRONT, stencilFront_.func, ref, stencilFront_.mask); break; case GL_BACK: glStencilFuncSeparate(GL_BACK, stencilBack_.func, ref, stencilBack_.mask); break; } } else { switch (face) { case GL_FRONT_AND_BACK: glStencilFunc(stencilFront_.func, ref, stencilFront_.mask); break; case GL_FRONT: glStencilFuncSeparate(GL_FRONT, stencilFront_.func, ref, stencilFront_.mask); break; case GL_BACK: glStencilFuncSeparate(GL_BACK, stencilBack_.func, ref, stencilBack_.mask); break; } } } int GLDepthStencilState::CompareSWO(const GLDepthStencilState& rhs) const { const auto& lhs = *this; LLGL_COMPARE_BOOL_MEMBER_SWO( depthTestEnabled_ ); if (depthTestEnabled_) { LLGL_COMPARE_MEMBER_SWO( depthMask_ ); LLGL_COMPARE_MEMBER_SWO( depthFunc_ ); } LLGL_COMPARE_BOOL_MEMBER_SWO( stencilTestEnabled_ ); if (stencilTestEnabled_) { LLGL_COMPARE_BOOL_MEMBER_SWO( independentStencilFaces_ ); { auto order = GLStencilFaceState::CompareSWO(stencilFront_, rhs.stencilFront_); if (order != 0) return order; } if (!independentStencilFaces_) { auto order = GLStencilFaceState::CompareSWO(stencilBack_, rhs.stencilBack_); if (order != 0) return order; } } return 0; } /* * ======= Private: ======= */ void GLDepthStencilState::BindStencilFaceState(const GLStencilFaceState& state, GLenum face) { glStencilOpSeparate(face, state.sfail, state.dpfail, state.dppass); if (!referenceDynamic_) glStencilFuncSeparate(face, state.func, state.ref, state.mask); glStencilMaskSeparate(face, state.writeMask); } void GLDepthStencilState::BindStencilState(const GLStencilFaceState& state) { glStencilOp(state.sfail, state.dpfail, state.dppass); if (!referenceDynamic_) glStencilFunc(state.func, state.ref, state.mask); glStencilMask(state.writeMask); } /* * GLDrawBufferState struct */ void GLDepthStencilState::GLStencilFaceState::Convert(GLStencilFaceState& dst, const StencilFaceDescriptor& src, bool referenceDynamic) { dst.sfail = GLTypes::Map(src.stencilFailOp); dst.dpfail = GLTypes::Map(src.depthFailOp); dst.dppass = GLTypes::Map(src.depthPassOp); dst.func = GLTypes::Map(src.compareOp); dst.ref = (referenceDynamic ? 0 : static_cast<GLint>(src.reference)); dst.mask = src.readMask; dst.writeMask = src.writeMask; } int GLDepthStencilState::GLStencilFaceState::CompareSWO(const GLStencilFaceState& lhs, const GLStencilFaceState& rhs) { LLGL_COMPARE_MEMBER_SWO( sfail ); LLGL_COMPARE_MEMBER_SWO( dpfail ); LLGL_COMPARE_MEMBER_SWO( dppass ); LLGL_COMPARE_MEMBER_SWO( func ); LLGL_COMPARE_MEMBER_SWO( ref ); LLGL_COMPARE_MEMBER_SWO( mask ); LLGL_COMPARE_MEMBER_SWO( writeMask ); return 0; } } // /namespace LLGL // ================================================================================ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll/rbm/rbm.hpp" #include "dll/test.hpp" #include "dll/dbn.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" namespace { using generator_t = dll::inmemory_data_generator_desc<dll::batch_size<25>, dll::autoencoder, dll::noise<30>>; template<typename D> void rbm_dae(const D& dataset){ std::cout << " Test RBM Denoising Auto-Encoder" << std::endl; using network_t = dll::dbn_desc< dll::dbn_layers< dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>>::layer_t > >::dbn_t; auto ae = std::make_unique<network_t>(); ae->display(); ae->template layer_get<0>().learning_rate = 0.001; ae->template layer_get<0>().initial_momentum = 0.9; auto& training_images = dataset.training_images; auto generator = make_generator(training_images, training_images, training_images.size(), generator_t{}); ae->pretrain_denoising(*generator, 50); } template<typename D> void rbm_dae_batch(const D& dataset){ std::cout << " Test RBM Denoising Auto-Encoder" << std::endl; using network_t = dll::dbn_desc< dll::dbn_layers< dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>>::layer_t >, dll::batch_mode>::dbn_t; auto ae = std::make_unique<network_t>(); ae->display(); ae->template layer_get<0>().learning_rate = 0.001; ae->template layer_get<0>().initial_momentum = 0.9; auto& training_images = dataset.training_images; auto generator = make_generator(training_images, training_images, training_images.size(), generator_t{}); ae->pretrain_denoising(*generator, 10); } template<typename D> void rbm_cdae_batch(const D& dataset){ std::cout << " Test RBM Denoising Auto-Encoder" << std::endl; using network_t = dll::dbn_desc< dll::dbn_layers< dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>>::layer_t, dll::rbm_desc<200, 100, dll::momentum, dll::batch_size<25>>::layer_t >, dll::batch_mode>::dbn_t; auto ae = std::make_unique<network_t>(); ae->display(); ae->template layer_get<0>().learning_rate = 0.001; ae->template layer_get<0>().initial_momentum = 0.9; ae->template layer_get<1>().learning_rate = 0.001; ae->template layer_get<1>().initial_momentum = 0.9; auto& training_images = dataset.training_images; auto generator = make_generator(training_images, training_images, training_images.size(), generator_t{}); ae->pretrain_denoising(*generator, 10); } } //end of anonymous namespace int main(int /*argc*/, char* /*argv*/ []) { auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_vector<float>>(); dataset.training_images.resize(20000); auto n = dataset.training_images.size(); std::cout << n << " samples to test" << std::endl; mnist::binarize_dataset(dataset); rbm_cdae_batch(dataset); rbm_dae_batch(dataset); rbm_dae(dataset); return 0; } <commit_msg>Adapt epochs again<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "dll/rbm/rbm.hpp" #include "dll/test.hpp" #include "dll/dbn.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" namespace { using generator_t = dll::inmemory_data_generator_desc<dll::batch_size<25>, dll::autoencoder, dll::noise<30>>; template<typename D> void rbm_dae(const D& dataset){ std::cout << " Test RBM Denoising Auto-Encoder" << std::endl; using network_t = dll::dbn_desc< dll::dbn_layers< dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>>::layer_t > >::dbn_t; auto ae = std::make_unique<network_t>(); ae->display(); ae->template layer_get<0>().learning_rate = 0.001; ae->template layer_get<0>().initial_momentum = 0.9; auto& training_images = dataset.training_images; auto generator = make_generator(training_images, training_images, training_images.size(), generator_t{}); ae->pretrain_denoising(*generator, 50); } template<typename D> void rbm_dae_batch(const D& dataset){ std::cout << " Test RBM Denoising Auto-Encoder" << std::endl; using network_t = dll::dbn_desc< dll::dbn_layers< dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>>::layer_t >, dll::batch_mode>::dbn_t; auto ae = std::make_unique<network_t>(); ae->display(); ae->template layer_get<0>().learning_rate = 0.001; ae->template layer_get<0>().initial_momentum = 0.9; auto& training_images = dataset.training_images; auto generator = make_generator(training_images, training_images, training_images.size(), generator_t{}); ae->pretrain_denoising(*generator, 50); } template<typename D> void rbm_cdae_batch(const D& dataset){ std::cout << " Test RBM Denoising Auto-Encoder" << std::endl; using network_t = dll::dbn_desc< dll::dbn_layers< dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>>::layer_t, dll::rbm_desc<200, 100, dll::momentum, dll::batch_size<25>>::layer_t >, dll::batch_mode>::dbn_t; auto ae = std::make_unique<network_t>(); ae->display(); ae->template layer_get<0>().learning_rate = 0.001; ae->template layer_get<0>().initial_momentum = 0.9; ae->template layer_get<1>().learning_rate = 0.001; ae->template layer_get<1>().initial_momentum = 0.9; auto& training_images = dataset.training_images; auto generator = make_generator(training_images, training_images, training_images.size(), generator_t{}); ae->pretrain_denoising(*generator, 10); } } //end of anonymous namespace int main(int /*argc*/, char* /*argv*/ []) { auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_vector<float>>(); dataset.training_images.resize(20000); auto n = dataset.training_images.size(); std::cout << n << " samples to test" << std::endl; mnist::binarize_dataset(dataset); rbm_cdae_batch(dataset); rbm_dae_batch(dataset); rbm_dae(dataset); return 0; } <|endoftext|>
<commit_before>#include <fcntl.h> #include "conn.h" #include "event_base.h" #include "logging.h" #include "util.h" #include "poller.h" #ifdef OS_LINUX #include <sys/epoll.h> #elif defined(OS_MACOSX) #include <sys/event.h> #else #error "platform unsupported" #endif namespace handy { #ifdef OS_LINUX struct PollerEpoll : public PollerBase { int epfd_; std::set<Channel *> liveChannels_; // for epoll selected active events struct epoll_event activeEvs_[kMaxEvents]; PollerEpoll(); ~PollerEpoll(); void addChannel(Channel *ch) override; void removeChannel(Channel *ch) override; void updateChannel(Channel *ch) override; void loop_once(int waitMs) override; }; PollerBase *createPoller() { return new PollerEpoll(); } PollerEpoll::PollerEpoll() { epfd_ = epoll_create1(EPOLL_CLOEXEC); fatalif(epfd_ < 0, "epoll_create error %d %s", errno, strerror(errno)); info("poller epoll %d created", epfd_); } PollerEpoll::~PollerEpoll() { info("destroying poller %d", epfd_); while (liveChannels_.size()) { (*liveChannels_.begin())->close(); } ::close(epfd_); info("poller %d destroyed", epfd_); } void PollerEpoll::addChannel(Channel *ch) { struct epoll_event ev; memset(&ev, 0, sizeof(ev)); ev.events = ch->events(); ev.data.ptr = ch; trace("adding channel %lld fd %d events %d epoll %d", (long long) ch->id(), ch->fd(), ev.events, epfd_); int r = epoll_ctl(epfd_, EPOLL_CTL_ADD, ch->fd(), &ev); fatalif(r, "epoll_ctl add failed %d %s", errno, strerror(errno)); liveChannels_.insert(ch); } void PollerEpoll::updateChannel(Channel *ch) { struct epoll_event ev; memset(&ev, 0, sizeof(ev)); ev.events = ch->events(); ev.data.ptr = ch; trace("modifying channel %lld fd %d events read %d write %d epoll %d", (long long) ch->id(), ch->fd(), ev.events & POLLIN, ev.events & POLLOUT, epfd_); int r = epoll_ctl(epfd_, EPOLL_CTL_MOD, ch->fd(), &ev); fatalif(r, "epoll_ctl mod failed %d %s", errno, strerror(errno)); } void PollerEpoll::removeChannel(Channel *ch) { trace("deleting channel %lld fd %d epoll %d", (long long) ch->id(), ch->fd(), epfd_); liveChannels_.erase(ch); for (int i = lastActive_; i >= 0; i--) { if (ch == activeEvs_[i].data.ptr) { activeEvs_[i].data.ptr = NULL; break; } } } void PollerEpoll::loop_once(int waitMs) { int64_t ticks = util::timeMilli(); lastActive_ = epoll_wait(epfd_, activeEvs_, kMaxEvents, waitMs); int64_t used = util::timeMilli() - ticks; trace("epoll wait %d return %d errno %d used %lld millsecond", waitMs, lastActive_, errno, (long long) used); fatalif(lastActive_ == -1 && errno != EINTR, "epoll return error %d %s", errno, strerror(errno)); while (--lastActive_ >= 0) { int i = lastActive_; Channel *ch = (Channel *) activeEvs_[i].data.ptr; int events = activeEvs_[i].events; if (ch) { if (events & (kReadEvent | POLLERR)) { trace("channel %lld fd %d handle read", (long long) ch->id(), ch->fd()); ch->handleRead(); } else if (events & kWriteEvent) { trace("channel %lld fd %d handle write", (long long) ch->id(), ch->fd()); ch->handleWrite(); } else { fatal("unexpected poller events"); } } } } #elif defined(OS_MACOSX) struct PollerKqueue : public PollerBase { int kqfd_; std::set<Channel *> liveChannels_; // for epoll selected active events struct kevent activeEvs_[kMaxEvents]; PollerKqueue(); ~PollerKqueue(); void addChannel(Channel *ch) override; void removeChannel(Channel *ch) override; void updateChannel(Channel *ch) override; void loop_once(int waitMs) override; }; PollerBase *createPoller() { return new PollerKqueue(); } PollerKqueue::PollerKqueue() { kqfd_ = kqueue(); fatalif(kqfd_ < 0, "kqueue error %d %s", errno, strerror(errno)); info("poller kqueue %d created", kqfd_); } PollerKqueue::~PollerKqueue() { info("destroying poller %d", kqfd_); while (liveChannels_.size()) { (*liveChannels_.begin())->close(); } ::close(kqfd_); info("poller %d destroyed", kqfd_); } void PollerKqueue::addChannel(Channel *ch) { struct timespec now; now.tv_nsec = 0; now.tv_sec = 0; struct kevent ev[2]; int n = 0; if (ch->readEnabled()) { EV_SET(&ev[n++], ch->fd(), EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, ch); } if (ch->writeEnabled()) { EV_SET(&ev[n++], ch->fd(), EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0, ch); } trace("adding channel %lld fd %d events read %d write %d epoll %d", (long long) ch->id(), ch->fd(), ch->events() & POLLIN, ch->events() & POLLOUT, fd_); int r = kevent(kqfd_, ev, n, NULL, 0, &now); fatalif(r, "kevent add failed %d %s", errno, strerror(errno)); liveChannels_.insert(ch); } void PollerKqueue::updateChannel(Channel *ch) { struct timespec now; now.tv_nsec = 0; now.tv_sec = 0; struct kevent ev[2]; int n = 0; if (ch->readEnabled()) { EV_SET(&ev[n++], ch->fd(), EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, ch); } else { EV_SET(&ev[n++], ch->fd(), EVFILT_READ, EV_DELETE, 0, 0, ch); } if (ch->writeEnabled()) { EV_SET(&ev[n++], ch->fd(), EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0, ch); } else { EV_SET(&ev[n++], ch->fd(), EVFILT_WRITE, EV_DELETE, 0, 0, ch); } trace("modifying channel %lld fd %d events read %d write %d epoll %d", (long long) ch->id(), ch->fd(), ch->events() & POLLIN, ch->events() & POLLOUT, fd_); int r = kevent(kqfd_, ev, n, NULL, 0, &now); fatalif(r, "kevent mod failed %d %s", errno, strerror(errno)); } void PollerKqueue::removeChannel(Channel *ch) { trace("deleting channel %lld fd %d epoll %d", (long long) ch->id(), ch->fd(), kqfd_); liveChannels_.erase(ch); // remove channel if in ready stat for (int i = lastActive_; i >= 0; i--) { if (ch == activeEvs_[i].udata) { activeEvs_[i].udata = NULL; break; } } } void PollerKqueue::loop_once(int waitMs) { struct timespec timeout; timeout.tv_sec = waitMs / 1000; timeout.tv_nsec = (waitMs % 1000) * 1000 * 1000; long ticks = util::timeMilli(); lastActive_ = kevent(kqfd_, NULL, 0, activeEvs_, kMaxEvents, &timeout); trace("kevent wait %d return %d errno %d used %lld millsecond", waitMs, lastActive_, errno, util::timeMilli() - ticks); fatalif(lastActive_ == -1 && errno != EINTR, "kevent return error %d %s", errno, strerror(errno)); while (--lastActive_ >= 0) { int i = lastActive_; Channel *ch = (Channel *) activeEvs_[i].udata; struct kevent &ke = activeEvs_[i]; if (ch) { // only handle write if read and write are enabled if (!(ke.flags & EV_EOF) && ch->writeEnabled()) { trace("channel %lld fd %d handle write", (long long) ch->id(), ch->fd()); ch->handleWrite(); } else if ((ke.flags & EV_EOF) || ch->readEnabled()) { trace("channel %lld fd %d handle read", (long long) ch->id(), ch->fd()); ch->handleRead(); } else { fatal("unexpected epoll events %d", ch->events()); } } } } #endif } // namespace handy<commit_msg>Revert "Rename PollerEpoll::fd_ to epfd_; rename PollerKqueue::fd_ to PollerKqueue::kqfd_ (#85)" (#90)<commit_after>#include <fcntl.h> #include "conn.h" #include "event_base.h" #include "logging.h" #include "util.h" #include "poller.h" #ifdef OS_LINUX #include <sys/epoll.h> #elif defined(OS_MACOSX) #include <sys/event.h> #else #error "platform unsupported" #endif namespace handy { #ifdef OS_LINUX struct PollerEpoll : public PollerBase { int fd_; std::set<Channel *> liveChannels_; // for epoll selected active events struct epoll_event activeEvs_[kMaxEvents]; PollerEpoll(); ~PollerEpoll(); void addChannel(Channel *ch) override; void removeChannel(Channel *ch) override; void updateChannel(Channel *ch) override; void loop_once(int waitMs) override; }; PollerBase *createPoller() { return new PollerEpoll(); } PollerEpoll::PollerEpoll() { fd_ = epoll_create1(EPOLL_CLOEXEC); fatalif(fd_ < 0, "epoll_create error %d %s", errno, strerror(errno)); info("poller epoll %d created", fd_); } PollerEpoll::~PollerEpoll() { info("destroying poller %d", fd_); while (liveChannels_.size()) { (*liveChannels_.begin())->close(); } ::close(fd_); info("poller %d destroyed", fd_); } void PollerEpoll::addChannel(Channel *ch) { struct epoll_event ev; memset(&ev, 0, sizeof(ev)); ev.events = ch->events(); ev.data.ptr = ch; trace("adding channel %lld fd %d events %d epoll %d", (long long) ch->id(), ch->fd(), ev.events, fd_); int r = epoll_ctl(fd_, EPOLL_CTL_ADD, ch->fd(), &ev); fatalif(r, "epoll_ctl add failed %d %s", errno, strerror(errno)); liveChannels_.insert(ch); } void PollerEpoll::updateChannel(Channel *ch) { struct epoll_event ev; memset(&ev, 0, sizeof(ev)); ev.events = ch->events(); ev.data.ptr = ch; trace("modifying channel %lld fd %d events read %d write %d epoll %d", (long long) ch->id(), ch->fd(), ev.events & POLLIN, ev.events & POLLOUT, fd_); int r = epoll_ctl(fd_, EPOLL_CTL_MOD, ch->fd(), &ev); fatalif(r, "epoll_ctl mod failed %d %s", errno, strerror(errno)); } void PollerEpoll::removeChannel(Channel *ch) { trace("deleting channel %lld fd %d epoll %d", (long long) ch->id(), ch->fd(), fd_); liveChannels_.erase(ch); for (int i = lastActive_; i >= 0; i--) { if (ch == activeEvs_[i].data.ptr) { activeEvs_[i].data.ptr = NULL; break; } } } void PollerEpoll::loop_once(int waitMs) { int64_t ticks = util::timeMilli(); lastActive_ = epoll_wait(fd_, activeEvs_, kMaxEvents, waitMs); int64_t used = util::timeMilli() - ticks; trace("epoll wait %d return %d errno %d used %lld millsecond", waitMs, lastActive_, errno, (long long) used); fatalif(lastActive_ == -1 && errno != EINTR, "epoll return error %d %s", errno, strerror(errno)); while (--lastActive_ >= 0) { int i = lastActive_; Channel *ch = (Channel *) activeEvs_[i].data.ptr; int events = activeEvs_[i].events; if (ch) { if (events & (kReadEvent | POLLERR)) { trace("channel %lld fd %d handle read", (long long) ch->id(), ch->fd()); ch->handleRead(); } else if (events & kWriteEvent) { trace("channel %lld fd %d handle write", (long long) ch->id(), ch->fd()); ch->handleWrite(); } else { fatal("unexpected poller events"); } } } } #elif defined(OS_MACOSX) struct PollerKqueue : public PollerBase { int fd_; std::set<Channel *> liveChannels_; // for epoll selected active events struct kevent activeEvs_[kMaxEvents]; PollerKqueue(); ~PollerKqueue(); void addChannel(Channel *ch) override; void removeChannel(Channel *ch) override; void updateChannel(Channel *ch) override; void loop_once(int waitMs) override; }; PollerBase *createPoller() { return new PollerKqueue(); } PollerKqueue::PollerKqueue() { fd_ = kqueue(); fatalif(fd_ < 0, "kqueue error %d %s", errno, strerror(errno)); info("poller kqueue %d created", fd_); } PollerKqueue::~PollerKqueue() { info("destroying poller %d", fd_); while (liveChannels_.size()) { (*liveChannels_.begin())->close(); } ::close(fd_); info("poller %d destroyed", fd_); } void PollerKqueue::addChannel(Channel *ch) { struct timespec now; now.tv_nsec = 0; now.tv_sec = 0; struct kevent ev[2]; int n = 0; if (ch->readEnabled()) { EV_SET(&ev[n++], ch->fd(), EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, ch); } if (ch->writeEnabled()) { EV_SET(&ev[n++], ch->fd(), EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0, ch); } trace("adding channel %lld fd %d events read %d write %d epoll %d", (long long) ch->id(), ch->fd(), ch->events() & POLLIN, ch->events() & POLLOUT, fd_); int r = kevent(fd_, ev, n, NULL, 0, &now); fatalif(r, "kevent add failed %d %s", errno, strerror(errno)); liveChannels_.insert(ch); } void PollerKqueue::updateChannel(Channel *ch) { struct timespec now; now.tv_nsec = 0; now.tv_sec = 0; struct kevent ev[2]; int n = 0; if (ch->readEnabled()) { EV_SET(&ev[n++], ch->fd(), EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0, ch); } else { EV_SET(&ev[n++], ch->fd(), EVFILT_READ, EV_DELETE, 0, 0, ch); } if (ch->writeEnabled()) { EV_SET(&ev[n++], ch->fd(), EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0, ch); } else { EV_SET(&ev[n++], ch->fd(), EVFILT_WRITE, EV_DELETE, 0, 0, ch); } trace("modifying channel %lld fd %d events read %d write %d epoll %d", (long long) ch->id(), ch->fd(), ch->events() & POLLIN, ch->events() & POLLOUT, fd_); int r = kevent(fd_, ev, n, NULL, 0, &now); fatalif(r, "kevent mod failed %d %s", errno, strerror(errno)); } void PollerKqueue::removeChannel(Channel *ch) { trace("deleting channel %lld fd %d epoll %d", (long long) ch->id(), ch->fd(), fd_); liveChannels_.erase(ch); // remove channel if in ready stat for (int i = lastActive_; i >= 0; i--) { if (ch == activeEvs_[i].udata) { activeEvs_[i].udata = NULL; break; } } } void PollerKqueue::loop_once(int waitMs) { struct timespec timeout; timeout.tv_sec = waitMs / 1000; timeout.tv_nsec = (waitMs % 1000) * 1000 * 1000; long ticks = util::timeMilli(); lastActive_ = kevent(fd_, NULL, 0, activeEvs_, kMaxEvents, &timeout); trace("kevent wait %d return %d errno %d used %lld millsecond", waitMs, lastActive_, errno, util::timeMilli() - ticks); fatalif(lastActive_ == -1 && errno != EINTR, "kevent return error %d %s", errno, strerror(errno)); while (--lastActive_ >= 0) { int i = lastActive_; Channel *ch = (Channel *) activeEvs_[i].udata; struct kevent &ke = activeEvs_[i]; if (ch) { // only handle write if read and write are enabled if (!(ke.flags & EV_EOF) && ch->writeEnabled()) { trace("channel %lld fd %d handle write", (long long) ch->id(), ch->fd()); ch->handleWrite(); } else if ((ke.flags & EV_EOF) || ch->readEnabled()) { trace("channel %lld fd %d handle read", (long long) ch->id(), ch->fd()); ch->handleRead(); } else { fatal("unexpected epoll events %d", ch->events()); } } } } #endif } // namespace handy<|endoftext|>
<commit_before>// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_FILE_READER_HPP #define TAO_PEGTL_INTERNAL_FILE_READER_HPP #include <cstdio> #include <filesystem> #include <memory> #include <string> #include <utility> #include "../config.hpp" namespace TAO_PEGTL_NAMESPACE::internal { [[nodiscard]] inline std::FILE* file_open( const std::filesystem::path& path ) { errno = 0; #if defined( _MSC_VER ) std::FILE* file; if( ::fopen_s( &file, path.u8string().c_str(), "rb" ) == 0 ) { return file; } const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "fopen_s() failed", path, ec ); #else #if defined( __MINGW32__ ) if( auto* file = std::fopen( path.u8string().c_str(), "rb" ) ) #else if( auto* file = std::fopen( path.u8string().c_str(), "rbe" ) ) #endif { return file; } const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::fopen() failed", path, ec ); #endif } struct file_close { void operator()( FILE* f ) const noexcept { std::fclose( f ); } }; class file_reader { public: explicit file_reader( const std::filesystem::path& path ) : file_reader( file_open( path ), path ) {} file_reader( FILE* file, const std::filesystem::path& path ) // NOLINT(modernize-pass-by-value) : m_path( path ), m_file( file ) {} file_reader( const file_reader& ) = delete; file_reader( file_reader&& ) = delete; ~file_reader() = default; void operator=( const file_reader& ) = delete; void operator=( file_reader&& ) = delete; [[nodiscard]] std::size_t size() const { errno = 0; if( std::fseek( m_file.get(), 0, SEEK_END ) != 0 ) { // LCOV_EXCL_START const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::fseek() failed [SEEK_END]", m_path, ec ); // LCOV_EXCL_STOP } errno = 0; const auto s = std::ftell( m_file.get() ); if( s < 0 ) { // LCOV_EXCL_START const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::ftell() failed", m_path, ec ); // LCOV_EXCL_STOP } errno = 0; if( std::fseek( m_file.get(), 0, SEEK_SET ) != 0 ) { // LCOV_EXCL_START const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::fseek() failed [SEEK_SET]", m_path, ec ); // LCOV_EXCL_STOP } return std::size_t( s ); } [[nodiscard]] std::string read() const { std::string nrv; nrv.resize( size() ); errno = 0; if( !nrv.empty() && ( std::fread( &nrv[ 0 ], nrv.size(), 1, m_file.get() ) != 1 ) ) { // LCOV_EXCL_START const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::fread() failed", m_path, ec ); // LCOV_EXCL_STOP } return nrv; } private: const std::filesystem::path m_path; const std::unique_ptr< std::FILE, file_close > m_file; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif <commit_msg>Use more secure function<commit_after>// Copyright (c) 2014-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_FILE_READER_HPP #define TAO_PEGTL_INTERNAL_FILE_READER_HPP #include <cstdio> #include <filesystem> #include <memory> #include <string> #include <utility> #include "../config.hpp" namespace TAO_PEGTL_NAMESPACE::internal { [[nodiscard]] inline std::FILE* file_open( const std::filesystem::path& path ) { errno = 0; #if defined( _MSC_VER ) std::FILE* file; if( ::_wfopen_s( &file, path.c_str(), L"rb" ) == 0 ) { return file; } const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "fopen_s() failed", path, ec ); #else #if defined( __MINGW32__ ) if( auto* file = std::fopen( path.u8string().c_str(), "rb" ) ) #else if( auto* file = std::fopen( path.u8string().c_str(), "rbe" ) ) #endif { return file; } const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::fopen() failed", path, ec ); #endif } struct file_close { void operator()( FILE* f ) const noexcept { std::fclose( f ); } }; class file_reader { public: explicit file_reader( const std::filesystem::path& path ) : file_reader( file_open( path ), path ) {} file_reader( FILE* file, const std::filesystem::path& path ) // NOLINT(modernize-pass-by-value) : m_path( path ), m_file( file ) {} file_reader( const file_reader& ) = delete; file_reader( file_reader&& ) = delete; ~file_reader() = default; void operator=( const file_reader& ) = delete; void operator=( file_reader&& ) = delete; [[nodiscard]] std::size_t size() const { errno = 0; if( std::fseek( m_file.get(), 0, SEEK_END ) != 0 ) { // LCOV_EXCL_START const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::fseek() failed [SEEK_END]", m_path, ec ); // LCOV_EXCL_STOP } errno = 0; const auto s = std::ftell( m_file.get() ); if( s < 0 ) { // LCOV_EXCL_START const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::ftell() failed", m_path, ec ); // LCOV_EXCL_STOP } errno = 0; if( std::fseek( m_file.get(), 0, SEEK_SET ) != 0 ) { // LCOV_EXCL_START const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::fseek() failed [SEEK_SET]", m_path, ec ); // LCOV_EXCL_STOP } return std::size_t( s ); } [[nodiscard]] std::string read() const { std::string nrv; nrv.resize( size() ); errno = 0; if( !nrv.empty() && ( std::fread( &nrv[ 0 ], nrv.size(), 1, m_file.get() ) != 1 ) ) { // LCOV_EXCL_START const std::error_code ec( errno, std::system_category() ); throw std::filesystem::filesystem_error( "std::fread() failed", m_path, ec ); // LCOV_EXCL_STOP } return nrv; } private: const std::filesystem::path m_path; const std::unique_ptr< std::FILE, file_close > m_file; }; } // namespace TAO_PEGTL_NAMESPACE::internal #endif <|endoftext|>
<commit_before>#include "flvizgv.h" #include <QFile> #include <QWheelEvent> #include <QMouseEvent> #include <QGraphicsRectItem> #include <QGraphicsSvgItem> #include <QPaintEvent> #include <qmath.h> /* * Constructor makes graphical objects in which we will put picture of the * C graph. Now we make draw a chess-board. */ FLVizGv::FLVizGv(QWidget *parent) : QGraphicsView(parent) , m_svgItem(0) { setScene(new QGraphicsScene(this)); setTransformationAnchor(AnchorUnderMouse); setDragMode(ScrollHandDrag); // To QPixmap tilePixmap(64, 64); tilePixmap.fill(Qt::white); QPainter tilePainter(&tilePixmap); QColor color(220, 220, 220); tilePainter.fillRect(0, 0, 32, 32, color); tilePainter.fillRect(32, 32, 32, 32, color); tilePainter.end(); setBackgroundBrush(tilePixmap); } /* * Open new file. */ void FLVizGv::openFile(const QString &fname) { QGraphicsScene *s = scene(); s->clear(); resetTransform(); m_svgItem = new QGraphicsSvgItem(fname); m_svgItem->setFlags(QGraphicsItem::ItemClipsToShape); m_svgItem->setCacheMode(QGraphicsItem::NoCache); m_svgItem->setZValue(0); s->addItem(m_svgItem); } /* * Request to draw new image. */ void FLVizGv::paintEvent(QPaintEvent *event) { QGraphicsView::paintEvent(event); } /* * Skaling of the image. */ void FLVizGv::wheelEvent(QWheelEvent *event) { qreal factor = qPow(1.2, event->delta() / 240.0); scale(factor, factor); event->accept(); } <commit_msg>Remove more Polish words from flvizgz.cpp<commit_after>#include "flvizgv.h" #include <QFile> #include <QWheelEvent> #include <QMouseEvent> #include <QGraphicsRectItem> #include <QGraphicsSvgItem> #include <QPaintEvent> #include <qmath.h> /* * Constructor makes graphical objects in which we will put picture of the * C graph. Now we make draw a chess-board. */ FLVizGv::FLVizGv(QWidget *parent) : QGraphicsView(parent) , m_svgItem(0) { setScene(new QGraphicsScene(this)); setTransformationAnchor(AnchorUnderMouse); setDragMode(ScrollHandDrag); // Tlo QPixmap tilePixmap(64, 64); tilePixmap.fill(Qt::white); QPainter tilePainter(&tilePixmap); QColor color(220, 220, 220); tilePainter.fillRect(0, 0, 32, 32, color); tilePainter.fillRect(32, 32, 32, 32, color); tilePainter.end(); setBackgroundBrush(tilePixmap); } /* * Open new file. */ void FLVizGv::openFile(const QString &fname) { QGraphicsScene *s = scene(); s->clear(); resetTransform(); m_svgItem = new QGraphicsSvgItem(fname); m_svgItem->setFlags(QGraphicsItem::ItemClipsToShape); m_svgItem->setCacheMode(QGraphicsItem::NoCache); m_svgItem->setZValue(0); s->addItem(m_svgItem); } /* * Request to draw new image. */ void FLVizGv::paintEvent(QPaintEvent *event) { QGraphicsView::paintEvent(event); } /* * Skaling of the image. */ void FLVizGv::wheelEvent(QWheelEvent *event) { qreal factor = qPow(1.2, event->delta() / 240.0); scale(factor, factor); event->accept(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Patrick P. Frey * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /// \file textwolf/xmlpathautomatonparse.hpp /// \brief Parser to create a path expression selector automaton from a source (list of path expression in abbreviated syntax of xpath) #ifndef __TEXTWOLF_XML_PATH_AUTOMATON_PARSE_HPP__ #define __TEXTWOLF_XML_PATH_AUTOMATON_PARSE_HPP__ #include "textwolf/xmlpathautomaton.hpp" #include "textwolf/charset.hpp" #include "textwolf/cstringiterator.hpp" #include <limits> #include <string> #include <cstdlib> #include <list> #include <vector> #include <cstring> #include <cstddef> #include <stdexcept> namespace textwolf { ///\class XMLPathSelectAutomatonParser ///\tparam SrcCharSet character set of the automaton definition source ///\tparam AtmCharSet character set of the token defintions of the automaton ///\brief Automaton to define XML path expressions and assign types (int values) to them template <class SrcCharSet=charset::UTF8, class AtmCharSet=charset::UTF8> class XMLPathSelectAutomatonParser :public XMLPathSelectAutomaton<AtmCharSet> { public: typedef XMLPathSelectAutomaton<AtmCharSet> ThisAutomaton; typedef typename ThisAutomaton::PathElement PathElement; typedef XMLPathSelectAutomatonParser This; typedef TextScanner<CStringIterator,SrcCharSet> SrcScanner; public: ///\brief Constructor XMLPathSelectAutomatonParser(){} virtual ~XMLPathSelectAutomatonParser(){} int addExpression( int typeidx, const char* esrc, std::size_t esrcsize) { // Check for namespaces, not supported: char const* xx = (char const*)std::memchr( esrc, ':', esrcsize); while (xx) { std::size_t xpos = xx - esrc; if (xpos + 1 < esrcsize && xx[1] == ':') { return xpos+1; } xx = (char const*)std::memchr( xx+1, ':', esrcsize - (xpos+1)); } // Parse the expression: IdentifierBuf idbuf( &m_atmcharset); CStringIterator itr( esrc, esrcsize); SrcScanner src( m_srccharset, itr); ExprState expr( this); enum State {SelectStart,SelectTag,SelectAttribute,SelectTagId,SelectAttributeId,SelectContent,SelectCondition}; State state = SelectStart; std::vector<const char*> alt; for (; *src; skipSpaces( src)) { switch (*src) { case '@': { if (state != SelectStart && state != SelectTag && state != SelectTagId) return src.getPosition()+1; ++src; state = SelectAttribute; break; } case '/': { if (state != SelectStart && state != SelectCondition && state != SelectTagId) return src.getPosition()+1; ++src; if (*src == '/') { expr.forAllDescendants(); ++src; } state = SelectTag; break; } case '[': { if (state != SelectStart && state != SelectTag && state != SelectTagId && state != SelectCondition) return src.getPosition()+1; ++src; skipSpaces( src); if (*src == '@') { ++src; skipSpaces( src); // Attribute condition: if (!isIdentifierChar( src)) return src.getPosition()+1; const char* attrname = idbuf.parseIdentifier( src); skipSpaces( src); if (*src != '=') return src.getPosition()+1; ++src; skipSpaces( src); const char* attrval = idbuf.parseValue( src); skipSpaces( src); if (!attrval || *src != ']') return src.getPosition()+1; expr.ifAttribute( attrname, attrval); ++src; } else { // Range skipSpaces( src); if (!isIdentifierChar( src)) return src.getPosition()+1; int range_start = parseNum( src); if (range_start < 0) return src.getPosition()+1; skipSpaces( src); if (*src == ',') { ++src; skipSpaces( src); if (*src == ']') { expr.FROM( range_start); ++src; } else { if (!isIdentifierChar( src)) return src.getPosition()+1; int range_end = parseNum( src); if (range_end < 0) return src.getPosition()+1; skipSpaces( src); if (*src != ']') return src.getPosition()+1; expr.RANGE( range_start, range_end); ++src; } } else if (*src == ']') { expr.INDEX( range_start); ++src; } else { return src.getPosition()+1; } } state = SelectCondition; break; } case '(': if (state != SelectStart && state != SelectTag && state != SelectTagId && state != SelectCondition) return src.getPosition()+1; ++src; skipSpaces( src); if (*src != ')') return src.getPosition()+1; ++src; expr.selectContent(); state = SelectContent; break; case '*': if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; ++src; if (state == SelectAttribute) { expr.selectAttribute( 0); state = SelectAttributeId; } else { expr.selectTag( 0); state = SelectTagId; } break; case '{': if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; alt = idbuf.parseIdentifierList( src, '{', '}'); if (alt.empty()) return src.getPosition()+1; if (state == SelectAttribute) { expr.selectAttributeAlt( alt); state = SelectAttributeId; } else { expr.selectTagAlt( alt); state = SelectTagId; } break; case '~': if (state != SelectTagId && state != SelectStart) return src.getPosition()+1; ++src; expr.selectCloseTag(); state = SelectContent; break; default: if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; if (!isIdentifierChar( src)) return src.getPosition()+1; if (state == SelectAttribute) { expr.selectAttribute( idbuf.parseIdentifier( src)); state = SelectAttributeId; } else { expr.selectTag( idbuf.parseIdentifier( src)); state = SelectTagId; } break; } } expr.assignType( typeidx); return 0; } private: #define ExprState_FOREACH( EXPR) {typename std::vector<PathElement>::iterator si = statelist.begin(), se = statelist.end(); for (; si != se; ++si) {si->EXPR;}} class ExprState { public: ExprState( XMLPathSelectAutomatonParser* atm) { statelist.push_back(PathElement(atm)); } ExprState( const ExprState& o) :statelist(o.statelist){} void selectTagAlt( std::vector<const char*> alt) { std::vector<PathElement> new_statelist; std::vector<const char*>::const_iterator ai = alt.begin(), ae = alt.end(); for (; ai != ae; ++ai) { ExprState alt_path( *this); alt_path.selectTag( *ai); new_statelist.insert( new_statelist.end(), alt_path.statelist.begin(), alt_path.statelist.end()); } statelist = new_statelist; } void selectAttributeAlt( std::vector<const char*> alt) { std::vector<PathElement> new_statelist; std::vector<const char*>::const_iterator ai = alt.begin(), ae = alt.end(); for (; ai != ae; ++ai) { ExprState alt_path( *this); alt_path.selectAttribute( *ai); new_statelist.insert( new_statelist.end(), alt_path.statelist.begin(), alt_path.statelist.end()); } statelist = new_statelist; } void TO(int idx) ExprState_FOREACH(TO(idx)) void FROM(int idx) ExprState_FOREACH(FROM(idx)) void RANGE(int idx1, int idx2) ExprState_FOREACH(RANGE(idx1,idx2)) void INDEX(int idx) ExprState_FOREACH(INDEX(idx)) void selectAttribute( const char* name) ExprState_FOREACH(selectAttribute(name)) void selectTag( const char* name) ExprState_FOREACH(selectTag(name)) void assignType(int type) ExprState_FOREACH(assignType(type)) void forAllDescendants() ExprState_FOREACH(forAllDescendants()) void selectCloseTag() ExprState_FOREACH(selectCloseTag()) void ifAttribute( const char* name, const char* value) ExprState_FOREACH(ifAttribute(name,value)) void selectContent() ExprState_FOREACH(selectContent()) private: std::vector<PathElement> statelist; }; static void skipSpaces( SrcScanner& src) { for (; src.control() == Space; ++src); } static int parseNum( SrcScanner& src) { std::string num; for (; *src>='0' && *src<='9';++src) num.push_back( *src); if (num.size() == 0 || num.size() > 8) return -1; return std::atoi( num.c_str()); } static bool isIdentifierChar( SrcScanner& src) { if (src.control() == Undef || src.control() == Any) { static const char opchr[] = "*~/(){}[]@,;"; return (0==std::strchr( opchr, *src)); } return false; } class IdentifierBuf { public: explicit IdentifierBuf( const AtmCharSet* atmcharset_) :atmcharset(atmcharset_){} ~IdentifierBuf(){} const char* parseIdentifier( SrcScanner& src) { idlist.push_back( std::string()); for (; isIdentifierChar(src); ++src) { atmcharset->print( *src, idlist.back()); } return idlist.back().c_str(); } const char* parseValue( SrcScanner& src) { idlist.push_back( std::string()); if (*src == '"' || *src == '\'') { unsigned char eb = *src; for (++src; *src && *src != eb; ++src) { atmcharset->print( *src, idlist.back()); } if (*src) ++src; return idlist.back().c_str(); } else if (isIdentifierChar(src)) { return parseIdentifier( src); } else { return NULL; } } std::vector<const char*> parseIdentifierList( SrcScanner& src, char startBracket, char endBracket) { std::vector<const char*> rt; if (*src != startBracket) return std::vector<const char*>(); do { ++src; skipSpaces( src); if (!isIdentifierChar( src)) return std::vector<const char*>(); rt.push_back( parseIdentifier( src)); skipSpaces( src); } while (*src == ','); if (*src != endBracket) return std::vector<const char*>(); ++src; return rt; } private: const AtmCharSet* atmcharset; std::list<std::string> idlist; }; private: AtmCharSet m_atmcharset; SrcCharSet m_srccharset; }; } //namespace #endif <commit_msg>fixed signed/unsigned comparison<commit_after>/* * Copyright (c) 2014 Patrick P. Frey * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /// \file textwolf/xmlpathautomatonparse.hpp /// \brief Parser to create a path expression selector automaton from a source (list of path expression in abbreviated syntax of xpath) #ifndef __TEXTWOLF_XML_PATH_AUTOMATON_PARSE_HPP__ #define __TEXTWOLF_XML_PATH_AUTOMATON_PARSE_HPP__ #include "textwolf/xmlpathautomaton.hpp" #include "textwolf/charset.hpp" #include "textwolf/cstringiterator.hpp" #include <limits> #include <string> #include <cstdlib> #include <list> #include <vector> #include <cstring> #include <cstddef> #include <stdexcept> namespace textwolf { ///\class XMLPathSelectAutomatonParser ///\tparam SrcCharSet character set of the automaton definition source ///\tparam AtmCharSet character set of the token defintions of the automaton ///\brief Automaton to define XML path expressions and assign types (int values) to them template <class SrcCharSet=charset::UTF8, class AtmCharSet=charset::UTF8> class XMLPathSelectAutomatonParser :public XMLPathSelectAutomaton<AtmCharSet> { public: typedef XMLPathSelectAutomaton<AtmCharSet> ThisAutomaton; typedef typename ThisAutomaton::PathElement PathElement; typedef XMLPathSelectAutomatonParser This; typedef TextScanner<CStringIterator,SrcCharSet> SrcScanner; public: ///\brief Constructor XMLPathSelectAutomatonParser(){} virtual ~XMLPathSelectAutomatonParser(){} int addExpression( int typeidx, const char* esrc, std::size_t esrcsize) { // Check for namespaces, not supported: char const* xx = (char const*)std::memchr( esrc, ':', esrcsize); while (xx) { std::size_t xpos = xx - esrc; if (xpos + 1 < esrcsize && xx[1] == ':') { return xpos+1; } xx = (char const*)std::memchr( xx+1, ':', esrcsize - (xpos+1)); } // Parse the expression: IdentifierBuf idbuf( &m_atmcharset); CStringIterator itr( esrc, esrcsize); SrcScanner src( m_srccharset, itr); ExprState expr( this); enum State {SelectStart,SelectTag,SelectAttribute,SelectTagId,SelectAttributeId,SelectContent,SelectCondition}; State state = SelectStart; std::vector<const char*> alt; for (; *src; skipSpaces( src)) { switch (*src) { case '@': { if (state != SelectStart && state != SelectTag && state != SelectTagId) return src.getPosition()+1; ++src; state = SelectAttribute; break; } case '/': { if (state != SelectStart && state != SelectCondition && state != SelectTagId) return src.getPosition()+1; ++src; if (*src == '/') { expr.forAllDescendants(); ++src; } state = SelectTag; break; } case '[': { if (state != SelectStart && state != SelectTag && state != SelectTagId && state != SelectCondition) return src.getPosition()+1; ++src; skipSpaces( src); if (*src == '@') { ++src; skipSpaces( src); // Attribute condition: if (!isIdentifierChar( src)) return src.getPosition()+1; const char* attrname = idbuf.parseIdentifier( src); skipSpaces( src); if (*src != '=') return src.getPosition()+1; ++src; skipSpaces( src); const char* attrval = idbuf.parseValue( src); skipSpaces( src); if (!attrval || *src != ']') return src.getPosition()+1; expr.ifAttribute( attrname, attrval); ++src; } else { // Range skipSpaces( src); if (!isIdentifierChar( src)) return src.getPosition()+1; int range_start = parseNum( src); if (range_start < 0) return src.getPosition()+1; skipSpaces( src); if (*src == ',') { ++src; skipSpaces( src); if (*src == ']') { expr.FROM( range_start); ++src; } else { if (!isIdentifierChar( src)) return src.getPosition()+1; int range_end = parseNum( src); if (range_end < 0) return src.getPosition()+1; skipSpaces( src); if (*src != ']') return src.getPosition()+1; expr.RANGE( range_start, range_end); ++src; } } else if (*src == ']') { expr.INDEX( range_start); ++src; } else { return src.getPosition()+1; } } state = SelectCondition; break; } case '(': if (state != SelectStart && state != SelectTag && state != SelectTagId && state != SelectCondition) return src.getPosition()+1; ++src; skipSpaces( src); if (*src != ')') return src.getPosition()+1; ++src; expr.selectContent(); state = SelectContent; break; case '*': if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; ++src; if (state == SelectAttribute) { expr.selectAttribute( 0); state = SelectAttributeId; } else { expr.selectTag( 0); state = SelectTagId; } break; case '{': if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; alt = idbuf.parseIdentifierList( src, '{', '}'); if (alt.empty()) return src.getPosition()+1; if (state == SelectAttribute) { expr.selectAttributeAlt( alt); state = SelectAttributeId; } else { expr.selectTagAlt( alt); state = SelectTagId; } break; case '~': if (state != SelectTagId && state != SelectStart) return src.getPosition()+1; ++src; expr.selectCloseTag(); state = SelectContent; break; default: if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; if (!isIdentifierChar( src)) return src.getPosition()+1; if (state == SelectAttribute) { expr.selectAttribute( idbuf.parseIdentifier( src)); state = SelectAttributeId; } else { expr.selectTag( idbuf.parseIdentifier( src)); state = SelectTagId; } break; } } expr.assignType( typeidx); return 0; } private: #define ExprState_FOREACH( EXPR) {typename std::vector<PathElement>::iterator si = statelist.begin(), se = statelist.end(); for (; si != se; ++si) {si->EXPR;}} class ExprState { public: ExprState( XMLPathSelectAutomatonParser* atm) { statelist.push_back(PathElement(atm)); } ExprState( const ExprState& o) :statelist(o.statelist){} void selectTagAlt( std::vector<const char*> alt) { std::vector<PathElement> new_statelist; std::vector<const char*>::const_iterator ai = alt.begin(), ae = alt.end(); for (; ai != ae; ++ai) { ExprState alt_path( *this); alt_path.selectTag( *ai); new_statelist.insert( new_statelist.end(), alt_path.statelist.begin(), alt_path.statelist.end()); } statelist = new_statelist; } void selectAttributeAlt( std::vector<const char*> alt) { std::vector<PathElement> new_statelist; std::vector<const char*>::const_iterator ai = alt.begin(), ae = alt.end(); for (; ai != ae; ++ai) { ExprState alt_path( *this); alt_path.selectAttribute( *ai); new_statelist.insert( new_statelist.end(), alt_path.statelist.begin(), alt_path.statelist.end()); } statelist = new_statelist; } void TO(int idx) ExprState_FOREACH(TO(idx)) void FROM(int idx) ExprState_FOREACH(FROM(idx)) void RANGE(int idx1, int idx2) ExprState_FOREACH(RANGE(idx1,idx2)) void INDEX(int idx) ExprState_FOREACH(INDEX(idx)) void selectAttribute( const char* name) ExprState_FOREACH(selectAttribute(name)) void selectTag( const char* name) ExprState_FOREACH(selectTag(name)) void assignType(int type) ExprState_FOREACH(assignType(type)) void forAllDescendants() ExprState_FOREACH(forAllDescendants()) void selectCloseTag() ExprState_FOREACH(selectCloseTag()) void ifAttribute( const char* name, const char* value) ExprState_FOREACH(ifAttribute(name,value)) void selectContent() ExprState_FOREACH(selectContent()) private: std::vector<PathElement> statelist; }; static void skipSpaces( SrcScanner& src) { for (; src.control() == Space; ++src); } static int parseNum( SrcScanner& src) { std::string num; for (; *src>='0' && *src<='9';++src) num.push_back( *src); if (num.size() == 0 || num.size() > 8) return -1; return std::atoi( num.c_str()); } static bool isIdentifierChar( SrcScanner& src) { if (src.control() == Undef || src.control() == Any) { static const char opchr[] = "*~/(){}[]@,;"; return (0==std::strchr( opchr, *src)); } return false; } class IdentifierBuf { public: explicit IdentifierBuf( const AtmCharSet* atmcharset_) :atmcharset(atmcharset_){} ~IdentifierBuf(){} const char* parseIdentifier( SrcScanner& src) { idlist.push_back( std::string()); for (; isIdentifierChar(src); ++src) { atmcharset->print( *src, idlist.back()); } return idlist.back().c_str(); } const char* parseValue( SrcScanner& src) { idlist.push_back( std::string()); if (*src == '"' || *src == '\'') { unsigned char eb = *src; for (++src; *src && *src != eb; ++src) { atmcharset->print( *src, idlist.back()); } if (*src) ++src; return idlist.back().c_str(); } else if (isIdentifierChar(src)) { return parseIdentifier( src); } else { return NULL; } } std::vector<const char*> parseIdentifierList( SrcScanner& src, unsigned char startBracket, unsigned char endBracket) { std::vector<const char*> rt; if (*src != startBracket) return std::vector<const char*>(); do { ++src; skipSpaces( src); if (!isIdentifierChar( src)) return std::vector<const char*>(); rt.push_back( parseIdentifier( src)); skipSpaces( src); } while (*src == ','); if (*src != endBracket) return std::vector<const char*>(); ++src; return rt; } private: const AtmCharSet* atmcharset; std::list<std::string> idlist; }; private: AtmCharSet m_atmcharset; SrcCharSet m_srccharset; }; } //namespace #endif <|endoftext|>
<commit_before>// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "BrightnessController.h" #include "../Monitor.h" #include "../Logger.h" BrightnessController::BrightnessController(HMONITOR monitor) { BOOL result; DWORD numPhysicalMonitors = 0; result = GetNumberOfPhysicalMonitorsFromHMONITOR( monitor, &numPhysicalMonitors); if (result == FALSE || numPhysicalMonitors <= 0) { CLOG(L"Could not get physical monitors"); return; } CLOG(L"Number of physical monitors detected: %d", numPhysicalMonitors); PHYSICAL_MONITOR *monitors = new PHYSICAL_MONITOR[numPhysicalMonitors]; result = GetPhysicalMonitorsFromHMONITOR( monitor, numPhysicalMonitors, monitors); for (unsigned int i = 0; i < numPhysicalMonitors; ++i) { CLOG(L"Monitor: %s", monitors[i].szPhysicalMonitorDescription); bool supportsAPI = SupportsBrightnessAPI(monitors[i]); QCLOG(L"Supports *MonitorBrightness APIs: %s", supportsAPI ? L"YES" : L"NO"); if (supportsAPI) { /* For now, we use the first compatible monitor found. */ _monitorHandle = monitors[i].hPhysicalMonitor; break; } } delete[] monitors; DWORD min, cur, max; result = GetMonitorBrightness(_monitorHandle, &min, &cur, &max); if (result == 0) { Logger::LogLastError(); } _minBrightness = min; _maxBrightness = max; CLOG(L"Got brightness: %d, %d, %d %f", min, cur, max, Brightness()); } BrightnessController::BrightnessController(Monitor &monitor) : BrightnessController(monitor.Handle()) { } float BrightnessController::Brightness() { DWORD min, cur, max; GetMonitorBrightness(_monitorHandle, &min, &cur, &max); return (float) (cur - _minBrightness) / (_maxBrightness - _minBrightness); } void BrightnessController::Brightness(float level) { DWORD setLevel = (DWORD) ((_maxBrightness - _minBrightness) * level); SetMonitorBrightness(_monitorHandle, setLevel); } bool BrightnessController::SupportsBrightnessAPI(PHYSICAL_MONITOR &pm) { DWORD caps, color; BOOL result = GetMonitorCapabilities(pm.hPhysicalMonitor, &caps, &color); if (result == FALSE) { QCLOG(L"Monitor does not support DDC/CI"); return false; } return ((caps & MC_CAPS_BRIGHTNESS) == MC_CAPS_BRIGHTNESS); } <commit_msg>Update log message for brightness<commit_after>// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #include "BrightnessController.h" #include "../Monitor.h" #include "../Logger.h" BrightnessController::BrightnessController(HMONITOR monitor) { BOOL result; DWORD numPhysicalMonitors = 0; result = GetNumberOfPhysicalMonitorsFromHMONITOR( monitor, &numPhysicalMonitors); if (result == FALSE || numPhysicalMonitors <= 0) { CLOG(L"Could not get physical monitors"); return; } CLOG(L"Number of physical monitors detected: %d", numPhysicalMonitors); PHYSICAL_MONITOR *monitors = new PHYSICAL_MONITOR[numPhysicalMonitors]; result = GetPhysicalMonitorsFromHMONITOR( monitor, numPhysicalMonitors, monitors); for (unsigned int i = 0; i < numPhysicalMonitors; ++i) { CLOG(L"Monitor: %s", monitors[i].szPhysicalMonitorDescription); bool supportsAPI = SupportsBrightnessAPI(monitors[i]); QCLOG(L"Supports *MonitorBrightness APIs: %s", supportsAPI ? L"YES" : L"NO"); if (supportsAPI) { /* For now, we use the first compatible monitor found. */ _monitorHandle = monitors[i].hPhysicalMonitor; break; } } delete[] monitors; DWORD min, cur, max; result = GetMonitorBrightness(_monitorHandle, &min, &cur, &max); if (result == 0) { Logger::LogLastError(); } _minBrightness = min; _maxBrightness = max; CLOG(L"Got brightness: [%d, %d] %f", min, max, Brightness()); } BrightnessController::BrightnessController(Monitor &monitor) : BrightnessController(monitor.Handle()) { } float BrightnessController::Brightness() { DWORD min, cur, max; GetMonitorBrightness(_monitorHandle, &min, &cur, &max); return (float) (cur - _minBrightness) / (_maxBrightness - _minBrightness); } void BrightnessController::Brightness(float level) { DWORD setLevel = (DWORD) ((_maxBrightness - _minBrightness) * level); SetMonitorBrightness(_monitorHandle, setLevel); } bool BrightnessController::SupportsBrightnessAPI(PHYSICAL_MONITOR &pm) { DWORD caps, color; BOOL result = GetMonitorCapabilities(pm.hPhysicalMonitor, &caps, &color); if (result == FALSE) { QCLOG(L"Monitor does not support DDC/CI"); return false; } return ((caps & MC_CAPS_BRIGHTNESS) == MC_CAPS_BRIGHTNESS); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: docvor.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2006-06-19 21:58:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFXDOCVOR_HXX #define _SFXDOCVOR_HXX #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #include "objsh.hxx" #include "orgmgr.hxx" //========================================================================= class SfxDocumentTemplates; class Path; //========================================================================= #ifndef _SFX_HXX class SfxOrganizeDlg_Impl; class SfxOrganizeListBox_Impl : public SvTreeListBox { enum BMPTYPE { BMPTYPE_FOLDER, BMPTYPE_DOC }; friend class SfxOrganizeDlg_Impl; Image aOpenedFolderBmp; Image aClosedFolderBmp; Image aOpenedDocBmp; Image aClosedDocBmp; Image aOpenedFolderBmpHC; Image aClosedFolderBmpHC; Image aOpenedDocBmpHC; Image aClosedDocBmpHC; SfxOrganizeMgr* pMgr; SfxOrganizeDlg_Impl* pDlg; static BOOL bDropMoveOk; DECL_LINK( OnAsyncExecuteDrop, ExecuteDropEvent* ); protected: virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection & ); virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText ); virtual BOOL NotifyMoving(SvLBoxEntry *pSource, SvLBoxEntry* pTarget, SvLBoxEntry *&pNewParent, ULONG &); virtual BOOL NotifyCopying(SvLBoxEntry *pSource, SvLBoxEntry* pTarget, SvLBoxEntry *&pNewParent, ULONG &); virtual void RequestingChilds( SvLBoxEntry* pParent ); virtual long ExpandingHdl(); virtual BOOL Select( SvLBoxEntry* pEntry, BOOL bSelect=TRUE ); using SvLBox::ExecuteDrop; // new d&d virtual DragDropMode NotifyStartDrag( TransferDataContainer&, SvLBoxEntry* ); virtual BOOL NotifyAcceptDrop( SvLBoxEntry* ); virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); virtual void DragFinished( sal_Int8 nDropAction ); public: using SvListView::Select; enum DataEnum { VIEW_TEMPLATES, VIEW_FILES } eViewType; SfxOrganizeListBox_Impl( SfxOrganizeDlg_Impl* pDlg, Window* pParent, WinBits, DataEnum ); DataEnum GetViewType() const { return eViewType; } void SetViewType(DataEnum eType) { eViewType = eType; } void SetMgr(SfxOrganizeMgr *pM) { pMgr = pM; } void Reset(); inline void SetBitmaps( const Image &rOFolderBmp, const Image &rCFolderBmp, const Image &rODocBmp, const Image &rCDocBmp, const Image &rOFolderBmpHC, const Image &rCFolderBmpHC, const Image &rODocBmpHC, const Image &rCDocBmpHC ); const Image &GetClosedBmp(USHORT nLevel) const; const Image &GetOpenedBmp(USHORT nLevel) const; virtual PopupMenu* CreateContextMenu(); private: BOOL IsStandard_Impl( SvLBoxEntry *) const; BOOL MoveOrCopyTemplates(SvLBox *pSourceBox, SvLBoxEntry *pSource, SvLBoxEntry* pTarget, SvLBoxEntry *&pNewParent, ULONG &rIdx, BOOL bCopy); BOOL MoveOrCopyContents(SvLBox *pSourceBox, SvLBoxEntry *pSource, SvLBoxEntry* pTarget, SvLBoxEntry *&pNewParent, ULONG &rIdx, BOOL bCopy); inline USHORT GetDocLevel() const; SfxObjectShellRef GetObjectShell( const Path& ); BOOL IsUniqName_Impl( const String &rText, SvLBoxEntry* pParent, SvLBoxEntry* pEntry = 0 ) const; USHORT GetLevelCount_Impl( SvLBoxEntry* pParent ) const; SvLBoxEntry* InsertEntryByBmpType( const XubString& rText, BMPTYPE eBmpType, SvLBoxEntry* pParent = NULL, BOOL bChildsOnDemand = FALSE, ULONG nPos = LIST_APPEND, void* pUserData = NULL ); }; #endif // _SFX_HXX //========================================================================= class SfxTemplateOrganizeDlg : public ModalDialog { friend class SfxOrganizeListBox_Impl; class SfxOrganizeDlg_Impl *pImp; // virtual void DataChanged( const DataChangedEvent& rDCEvt ); public: SfxTemplateOrganizeDlg(Window * pParent, SfxDocumentTemplates* = 0); ~SfxTemplateOrganizeDlg(); #define RET_EDIT_STYLE 100 virtual short Execute(); }; #endif <commit_msg>INTEGRATION: CWS vgbugs07 (1.11.308); FILE MERGED 2007/06/04 13:34:36 vg 1.11.308.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: docvor.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2007-06-27 22:51:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFXDOCVOR_HXX #define _SFXDOCVOR_HXX #ifndef _DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #include <sfx2/objsh.hxx> #include "orgmgr.hxx" //========================================================================= class SfxDocumentTemplates; class Path; //========================================================================= #ifndef _SFX_HXX class SfxOrganizeDlg_Impl; class SfxOrganizeListBox_Impl : public SvTreeListBox { enum BMPTYPE { BMPTYPE_FOLDER, BMPTYPE_DOC }; friend class SfxOrganizeDlg_Impl; Image aOpenedFolderBmp; Image aClosedFolderBmp; Image aOpenedDocBmp; Image aClosedDocBmp; Image aOpenedFolderBmpHC; Image aClosedFolderBmpHC; Image aOpenedDocBmpHC; Image aClosedDocBmpHC; SfxOrganizeMgr* pMgr; SfxOrganizeDlg_Impl* pDlg; static BOOL bDropMoveOk; DECL_LINK( OnAsyncExecuteDrop, ExecuteDropEvent* ); protected: virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection & ); virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const String& rNewText ); virtual BOOL NotifyMoving(SvLBoxEntry *pSource, SvLBoxEntry* pTarget, SvLBoxEntry *&pNewParent, ULONG &); virtual BOOL NotifyCopying(SvLBoxEntry *pSource, SvLBoxEntry* pTarget, SvLBoxEntry *&pNewParent, ULONG &); virtual void RequestingChilds( SvLBoxEntry* pParent ); virtual long ExpandingHdl(); virtual BOOL Select( SvLBoxEntry* pEntry, BOOL bSelect=TRUE ); using SvLBox::ExecuteDrop; // new d&d virtual DragDropMode NotifyStartDrag( TransferDataContainer&, SvLBoxEntry* ); virtual BOOL NotifyAcceptDrop( SvLBoxEntry* ); virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); virtual void DragFinished( sal_Int8 nDropAction ); public: using SvListView::Select; enum DataEnum { VIEW_TEMPLATES, VIEW_FILES } eViewType; SfxOrganizeListBox_Impl( SfxOrganizeDlg_Impl* pDlg, Window* pParent, WinBits, DataEnum ); DataEnum GetViewType() const { return eViewType; } void SetViewType(DataEnum eType) { eViewType = eType; } void SetMgr(SfxOrganizeMgr *pM) { pMgr = pM; } void Reset(); inline void SetBitmaps( const Image &rOFolderBmp, const Image &rCFolderBmp, const Image &rODocBmp, const Image &rCDocBmp, const Image &rOFolderBmpHC, const Image &rCFolderBmpHC, const Image &rODocBmpHC, const Image &rCDocBmpHC ); const Image &GetClosedBmp(USHORT nLevel) const; const Image &GetOpenedBmp(USHORT nLevel) const; virtual PopupMenu* CreateContextMenu(); private: BOOL IsStandard_Impl( SvLBoxEntry *) const; BOOL MoveOrCopyTemplates(SvLBox *pSourceBox, SvLBoxEntry *pSource, SvLBoxEntry* pTarget, SvLBoxEntry *&pNewParent, ULONG &rIdx, BOOL bCopy); BOOL MoveOrCopyContents(SvLBox *pSourceBox, SvLBoxEntry *pSource, SvLBoxEntry* pTarget, SvLBoxEntry *&pNewParent, ULONG &rIdx, BOOL bCopy); inline USHORT GetDocLevel() const; SfxObjectShellRef GetObjectShell( const Path& ); BOOL IsUniqName_Impl( const String &rText, SvLBoxEntry* pParent, SvLBoxEntry* pEntry = 0 ) const; USHORT GetLevelCount_Impl( SvLBoxEntry* pParent ) const; SvLBoxEntry* InsertEntryByBmpType( const XubString& rText, BMPTYPE eBmpType, SvLBoxEntry* pParent = NULL, BOOL bChildsOnDemand = FALSE, ULONG nPos = LIST_APPEND, void* pUserData = NULL ); }; #endif // _SFX_HXX //========================================================================= class SfxTemplateOrganizeDlg : public ModalDialog { friend class SfxOrganizeListBox_Impl; class SfxOrganizeDlg_Impl *pImp; // virtual void DataChanged( const DataChangedEvent& rDCEvt ); public: SfxTemplateOrganizeDlg(Window * pParent, SfxDocumentTemplates* = 0); ~SfxTemplateOrganizeDlg(); #define RET_EDIT_STYLE 100 virtual short Execute(); }; #endif <|endoftext|>
<commit_before>//============================================================================ // vSMC/include/vsmc/rng/discrete_distribution.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2015, 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 VSMC_RNG_DISCRETE_DISTRIBUTION_HPP #define VSMC_RNG_DISCRETE_DISTRIBUTION_HPP #include <vsmc/rng/internal/common.hpp> #include <vsmc/rng/u01_distribution.hpp> #include <vsmc/math/cblas.hpp> #define VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(flag) \ VSMC_RUNTIME_ASSERT( \ (flag), "**DiscreteDistribution** WEIGHTS ARE NOT NON-NEGATIVE") namespace vsmc { /// \brief Draw a single sample given weights /// \ingroup Distribution template <typename IntType = int> class DiscreteDistribution { public: using result_type = IntType; using distribution_type = DiscreteDistribution<IntType>; class param_type { public: using result_type = IntType; using distribution_type = DiscreteDistribution<IntType>; param_type() {} template <typename InputIter> param_type(InputIter first, InputIter last) : probability_(first, last) { invariant(); } param_type(std::initializer_list<double> weights) : probability_(weights.begin(), weights.end()) { invariant(); } template <typename UnaryOperation> param_type(std::size_t count, double xmin, double xmax, UnaryOperation unary_op) { probability_.reserve(count); double delta = (xmax - xmin) / static_cast<double>(count); xmin += 0.5 * delta; for (std::size_t i = 0; i != count; ++i) probability_.push_back( unary_op(xmin + static_cast<double>(i) * delta)); invariant(); } Vector<double> probability() const { return probability_; } friend bool operator==( const param_type &param1, const param_type &param2) { if (param1.probability_.size() != param2.probability_.size()) return false; for (std::size_t i = 0; i != param1.probability_.size(); ++i) if (!is_equal(param1.probability_[i], param2.probability_[i])) return false; return true; } friend bool operator!=( const param_type &param1, const param_type &param2) { return !(param1 == param2); } template <typename CharT, typename Traits> friend std::basic_ostream<CharT, Traits> &operator<<( std::basic_ostream<CharT, Traits> &os, const param_type &param) { if (!os.good()) return os; os << param.probability_.size() << ' '; for (std::size_t i = 0; i != param.probability_.size(); ++i) os << param.probability_[i] << ' '; return os; } template <typename CharT, typename Traits> friend std::basic_istream<CharT, Traits> &operator>>( std::basic_istream<CharT, Traits> &is, param_type &param) { if (!is.good()) return is; std::size_t n = 0; is >> std::ws >> n; if (!is.good()) return is; Vector<double> probability(n); for (std::size_t i = 0; i != n; ++i) is >> std::ws >> probability[i]; if (is.good()) { double sum = 0; if (is_positive(probability, sum)) { math::scal( probability.size(), 1 / sum, probability.data(), 1); param.probability_ = std::move(probability); } else { is.setstate(std::ios_base::failbit); } } return is; } private: Vector<double> probability_; friend distribution_type; void invariant() { if (probability_.size() == 0) return; double sum = 0; #ifndef NDEBUG bool flag = is_positive(probability_, sum); VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(flag); #else is_positive(probability_, sum); #endif math::scal(probability_.size(), 1 / sum, probability_.data(), 1); } void reset() {} static bool is_positive(const Vector<double> &probability, double &sum) { sum = 0; bool flag = true; for (std::size_t i = 0; i != probability.size(); ++i) { sum += probability[i]; if (probability[i] < 0) flag = false; } return flag && sum > 0; } }; // class param_type DiscreteDistribution() {} template <typename InputIter> DiscreteDistribution(InputIter first, InputIter last) : param_(first, last) { } DiscreteDistribution(std::initializer_list<double> weights) : param_(weights) { } template <typename UnaryOperation> DiscreteDistribution( std::size_t count, double xmin, double xmax, UnaryOperation &&unary_op) : param_type(count, xmin, xmax, std::forward<UnaryOperation>(unary_op)) { } explicit DiscreteDistribution(const param_type &param) : param_(param) {} explicit DiscreteDistribution(param_type &&param) : param_(std::move(param)) { } result_type min VSMC_MNE() const { return 0; } result_type max VSMC_MNE() const { return param_.size() == 0 ? 0 : param_.size() - 1; } Vector<double> probability() const { return param_.probability_; } template <typename RNGType> result_type operator()(RNGType &rng) const { return operator()( rng, param_.probability_.begin(), param_.probability_.end(), true); } /// \brief Draw sample with external probabilities /// /// \param rng A uniform random number generator /// \param first The first iterator of the weights sequence. /// \param last The one past the end iterator of the weights sequence. /// \param normalized If the weights are already normalized /// /// \details /// Given weights \f$(W_1,\dots,W_N)\f$, it is possible to draw the /// index /// \f$i\f$ using the `std::discrete_distribuiton` template. However, /// there /// are two drawbacks with this approach. First, if the weights are /// already /// normalized, this template does uncessary extra work to normalized /// the /// weights. Second, whenever the weights change, a new distribution /// need /// to be constructed (the `param_type` of the distribution is /// implementation defined and cannot be used to write portable code), /// which will lead to uncessary dynamic memory allocation. This /// function /// does not use dynamic memory and improve performance for normalized /// weights. template <typename RNGType, typename InputIter> result_type operator()(RNGType &rng, InputIter first, InputIter last, bool normalized = false) const { using value_type = typename std::iterator_traits<InputIter>::value_type; U01DistributionType<RNGType, value_type> runif; value_type u = runif(rng); if (!normalized) { value_type mulw = 1 / std::accumulate(first, last, static_cast<value_type>(0)); value_type accw = 0; result_type index = 0; while (first != last) { accw += *first * mulw; if (u <= accw) return index; ++first; ++index; } return index - 1; } value_type accw = 0; result_type index = 0; while (first != last) { accw += *first; if (u <= accw) return index; ++first; ++index; } return index - 1; } VSMC_DEFINE_RNG_DISTRIBUTION_OPERATORS private: param_type param_; }; // class DiscreteDistribution } // namespace vsmc #endif // VSMC_RNG_DISCRETE_DISTRIBUTION_HPP <commit_msg>fix missing namespace qualifier<commit_after>//============================================================================ // vSMC/include/vsmc/rng/discrete_distribution.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2015, 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 VSMC_RNG_DISCRETE_DISTRIBUTION_HPP #define VSMC_RNG_DISCRETE_DISTRIBUTION_HPP #include <vsmc/rng/internal/common.hpp> #include <vsmc/rng/u01_distribution.hpp> #include <vsmc/math/cblas.hpp> #define VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(flag) \ VSMC_RUNTIME_ASSERT( \ (flag), "**DiscreteDistribution** WEIGHTS ARE NOT NON-NEGATIVE") namespace vsmc { /// \brief Draw a single sample given weights /// \ingroup Distribution template <typename IntType = int> class DiscreteDistribution { public: using result_type = IntType; using distribution_type = DiscreteDistribution<IntType>; class param_type { public: using result_type = IntType; using distribution_type = DiscreteDistribution<IntType>; param_type() {} template <typename InputIter> param_type(InputIter first, InputIter last) : probability_(first, last) { invariant(); } param_type(std::initializer_list<double> weights) : probability_(weights.begin(), weights.end()) { invariant(); } template <typename UnaryOperation> param_type(std::size_t count, double xmin, double xmax, UnaryOperation unary_op) { probability_.reserve(count); double delta = (xmax - xmin) / static_cast<double>(count); xmin += 0.5 * delta; for (std::size_t i = 0; i != count; ++i) probability_.push_back( unary_op(xmin + static_cast<double>(i) * delta)); invariant(); } Vector<double> probability() const { return probability_; } friend bool operator==( const param_type &param1, const param_type &param2) { if (param1.probability_.size() != param2.probability_.size()) return false; for (std::size_t i = 0; i != param1.probability_.size(); ++i) if (!internal::is_equal( param1.probability_[i], param2.probability_[i])) return false; return true; } friend bool operator!=( const param_type &param1, const param_type &param2) { return !(param1 == param2); } template <typename CharT, typename Traits> friend std::basic_ostream<CharT, Traits> &operator<<( std::basic_ostream<CharT, Traits> &os, const param_type &param) { if (!os.good()) return os; os << param.probability_.size() << ' '; for (std::size_t i = 0; i != param.probability_.size(); ++i) os << param.probability_[i] << ' '; return os; } template <typename CharT, typename Traits> friend std::basic_istream<CharT, Traits> &operator>>( std::basic_istream<CharT, Traits> &is, param_type &param) { if (!is.good()) return is; std::size_t n = 0; is >> std::ws >> n; if (!is.good()) return is; Vector<double> probability(n); for (std::size_t i = 0; i != n; ++i) is >> std::ws >> probability[i]; if (is.good()) { double sum = 0; if (is_positive(probability, sum)) { math::scal( probability.size(), 1 / sum, probability.data(), 1); param.probability_ = std::move(probability); } else { is.setstate(std::ios_base::failbit); } } return is; } private: Vector<double> probability_; friend distribution_type; void invariant() { if (probability_.size() == 0) return; double sum = 0; #ifndef NDEBUG bool flag = is_positive(probability_, sum); VSMC_RUNTIME_ASSERT_RNG_DISCRETE_DISTRIBUTION_POSITIVE(flag); #else is_positive(probability_, sum); #endif math::scal(probability_.size(), 1 / sum, probability_.data(), 1); } void reset() {} static bool is_positive(const Vector<double> &probability, double &sum) { sum = 0; bool flag = true; for (std::size_t i = 0; i != probability.size(); ++i) { sum += probability[i]; if (probability[i] < 0) flag = false; } return flag && sum > 0; } }; // class param_type DiscreteDistribution() {} template <typename InputIter> DiscreteDistribution(InputIter first, InputIter last) : param_(first, last) { } DiscreteDistribution(std::initializer_list<double> weights) : param_(weights) { } template <typename UnaryOperation> DiscreteDistribution( std::size_t count, double xmin, double xmax, UnaryOperation &&unary_op) : param_type(count, xmin, xmax, std::forward<UnaryOperation>(unary_op)) { } explicit DiscreteDistribution(const param_type &param) : param_(param) {} explicit DiscreteDistribution(param_type &&param) : param_(std::move(param)) { } result_type min VSMC_MNE() const { return 0; } result_type max VSMC_MNE() const { return param_.size() == 0 ? 0 : param_.size() - 1; } Vector<double> probability() const { return param_.probability_; } template <typename RNGType> result_type operator()(RNGType &rng) const { return operator()( rng, param_.probability_.begin(), param_.probability_.end(), true); } /// \brief Draw sample with external probabilities /// /// \param rng A uniform random number generator /// \param first The first iterator of the weights sequence. /// \param last The one past the end iterator of the weights sequence. /// \param normalized If the weights are already normalized /// /// \details /// Given weights \f$(W_1,\dots,W_N)\f$, it is possible to draw the /// index /// \f$i\f$ using the `std::discrete_distribuiton` template. However, /// there /// are two drawbacks with this approach. First, if the weights are /// already /// normalized, this template does uncessary extra work to normalized /// the /// weights. Second, whenever the weights change, a new distribution /// need /// to be constructed (the `param_type` of the distribution is /// implementation defined and cannot be used to write portable code), /// which will lead to uncessary dynamic memory allocation. This /// function /// does not use dynamic memory and improve performance for normalized /// weights. template <typename RNGType, typename InputIter> result_type operator()(RNGType &rng, InputIter first, InputIter last, bool normalized = false) const { using value_type = typename std::iterator_traits<InputIter>::value_type; U01DistributionType<RNGType, value_type> runif; value_type u = runif(rng); if (!normalized) { value_type mulw = 1 / std::accumulate(first, last, static_cast<value_type>(0)); value_type accw = 0; result_type index = 0; while (first != last) { accw += *first * mulw; if (u <= accw) return index; ++first; ++index; } return index - 1; } value_type accw = 0; result_type index = 0; while (first != last) { accw += *first; if (u <= accw) return index; ++first; ++index; } return index - 1; } VSMC_DEFINE_RNG_DISTRIBUTION_OPERATORS private: param_type param_; }; // class DiscreteDistribution } // namespace vsmc #endif // VSMC_RNG_DISCRETE_DISTRIBUTION_HPP <|endoftext|>
<commit_before>#ifndef SILICIUM_BUFFER_HPP #define SILICIUM_BUFFER_HPP #include <silicium/observable/observer.hpp> #include <silicium/config.hpp> #include <boost/circular_buffer.hpp> #include <cassert> #include <cstddef> namespace Si { template <class Element, class Original> struct buffer_observable : private observer<Element> { typedef Element element_type; buffer_observable() : receiver(nullptr) , fetching(false) { } explicit buffer_observable(Original from, std::size_t size) : from(std::move(from)) , elements(size) , receiver(nullptr) , fetching(false) { } #if defined(_MSC_VER) || (BOOST_VERSION <= 105400) buffer_observable(buffer_observable &&other) : from(std::move(other.from)) , elements(std::move(other.elements)) , receiver(nullptr) , fetching(false) { } buffer_observable &operator = (buffer_observable &&other) { //TODO: exception safety from = std::move(other.from); elements = std::move(other.elements); receiver = std::move(other.receiver); fetching = std::move(other.fetching); return *this; } #else buffer_observable(buffer_observable &&) = default; buffer_observable &operator = (buffer_observable &&) = default; #endif void async_get_one(ptr_observer<observer<element_type>> receiver) { assert(!this->receiver); this->receiver = receiver.get(); if (elements.empty()) { return check_fetch(); } else { return deliver_front(); } } void prefetch() { check_fetch(); } private: Original from; boost::circular_buffer<Element> elements; observer<element_type> *receiver; bool fetching; virtual void got_element(element_type value) SILICIUM_OVERRIDE { assert(!elements.full()); assert(fetching); fetching = false; if (elements.empty() && receiver) { exchange(receiver, nullptr)->got_element(std::move(value)); return check_fetch(); } elements.push_back(std::move(value)); if (!receiver) { return check_fetch(); } deliver_front(); return check_fetch(); } virtual void ended() SILICIUM_OVERRIDE { assert(fetching); assert(receiver); exchange(receiver, nullptr)->ended(); } void deliver_front() { auto front = std::move(elements.front()); elements.pop_front(); exchange(receiver, nullptr)->got_element(std::move(front)); } void check_fetch() { if (elements.full()) { return; } if (fetching) { return; } fetching = true; from.async_get_one(observe_by_ref(static_cast<observer<Element> &>(*this))); } SILICIUM_DELETED_FUNCTION(buffer_observable(buffer_observable const &)) SILICIUM_DELETED_FUNCTION(buffer_observable &operator = (buffer_observable const &)) }; template <class Original> auto make_buffer_observable(Original &&from, std::size_t size) -> buffer_observable<typename std::decay<Original>::type::element_type, typename std::decay<Original>::type> { typedef typename std::decay<Original>::type clean_original; typedef typename clean_original::element_type element; return buffer_observable<element, clean_original>(std::forward<Original>(from), size); } } #endif <commit_msg>fix another warning about a hidden variable<commit_after>#ifndef SILICIUM_BUFFER_HPP #define SILICIUM_BUFFER_HPP #include <silicium/observable/observer.hpp> #include <silicium/config.hpp> #include <boost/circular_buffer.hpp> #include <cassert> #include <cstddef> namespace Si { template <class Element, class Original> struct buffer_observable : private observer<Element> { typedef Element element_type; buffer_observable() : receiver_(nullptr) , fetching(false) { } explicit buffer_observable(Original from, std::size_t size) : from(std::move(from)) , elements(size) , receiver_(nullptr) , fetching(false) { } #if defined(_MSC_VER) || (BOOST_VERSION <= 105400) buffer_observable(buffer_observable &&other) : from(std::move(other.from)) , elements(std::move(other.elements)) , receiver_(nullptr) , fetching(false) { } buffer_observable &operator = (buffer_observable &&other) { //TODO: exception safety from = std::move(other.from); elements = std::move(other.elements); receiver_ = std::move(other.receiver); fetching = std::move(other.fetching); return *this; } #else buffer_observable(buffer_observable &&) = default; buffer_observable &operator = (buffer_observable &&) = default; #endif void async_get_one(ptr_observer<observer<element_type>> receiver) { assert(!this->receiver_); this->receiver_ = receiver.get(); if (elements.empty()) { return check_fetch(); } else { return deliver_front(); } } void prefetch() { check_fetch(); } private: Original from; boost::circular_buffer<Element> elements; observer<element_type> *receiver_; bool fetching; virtual void got_element(element_type value) SILICIUM_OVERRIDE { assert(!elements.full()); assert(fetching); fetching = false; if (elements.empty() && receiver_) { exchange(receiver_, nullptr)->got_element(std::move(value)); return check_fetch(); } elements.push_back(std::move(value)); if (!receiver_) { return check_fetch(); } deliver_front(); return check_fetch(); } virtual void ended() SILICIUM_OVERRIDE { assert(fetching); assert(receiver_); exchange(receiver_, nullptr)->ended(); } void deliver_front() { auto front = std::move(elements.front()); elements.pop_front(); exchange(receiver_, nullptr)->got_element(std::move(front)); } void check_fetch() { if (elements.full()) { return; } if (fetching) { return; } fetching = true; from.async_get_one(observe_by_ref(static_cast<observer<Element> &>(*this))); } SILICIUM_DELETED_FUNCTION(buffer_observable(buffer_observable const &)) SILICIUM_DELETED_FUNCTION(buffer_observable &operator = (buffer_observable const &)) }; template <class Original> auto make_buffer_observable(Original &&from, std::size_t size) -> buffer_observable<typename std::decay<Original>::type::element_type, typename std::decay<Original>::type> { typedef typename std::decay<Original>::type clean_original; typedef typename clean_original::element_type element; return buffer_observable<element, clean_original>(std::forward<Original>(from), size); } } #endif <|endoftext|>
<commit_before>#include <fountain/ft_type.h> #include <fountain/ft_render.h> #include <fountain/ft_algorithm.h> #include <cstdio> using ftType::FontMan; FT_Library library; bool ftType::init() { int error = FT_Init_FreeType(&library); if (error) { return false; } return true; } void copyBitmapToBufferData(FT_Bitmap &bitmap, unsigned char *expanded_data, int imgW, int w, int h, int row, int col) { for(int j = 0; j < h; j++) { for(int i = 0; i < w; i++) { int r = row * h + j; int c = col * w + i; expanded_data[2 * (r * imgW + c)] = 255; expanded_data[2 * (r * imgW + c) + 1] = (i >= bitmap.width || j >= bitmap.rows) ? 0 : bitmap.buffer[i + bitmap.width * (bitmap.rows - 1 - j)]; } } } FontMan::FontMan() { picID = 0; } FontMan::~FontMan() { //TODO: fix the bug (double free when delete the pic) //ftRender::deletePicture(picID); } bool FontMan::loadFont(const char *fontname) { int error = FT_New_Face(library, fontname, 0, &face); if (error) { return false; } return true; } //TODO: make these two functions less code void FontMan::genAsciiTable(int h) { //TODO: check the state of picID h = ftAlgorithm::nextPower2(h); int w = h; int cols = 16; int rows = 8; int imgW = w * cols; int imgH = h * rows; FT_Set_Pixel_Sizes(face, 0, h); FT_GlyphSlot slot = face->glyph; unsigned char* expanded_data = new unsigned char[2 * imgW * imgH]; for (unsigned char ch = 0; ch < 128; ch++) { FT_Load_Char(face, ch, FT_LOAD_RENDER); FT_Bitmap& bitmap = slot->bitmap; int row = ch / cols; int col = ch % cols; copyBitmapToBufferData(bitmap, expanded_data, imgW, w, h, row, col); } //TODO: use SubImage to draw? picID = ftRender::getPicture(expanded_data, imgW, imgH, FT_GRAY_ALPHA); delete [] expanded_data; } void FontMan::genStringTable(const char *str, int h) { //TODO: check the state of picID h = ftAlgorithm::nextPower2(h); std::vector<unsigned long> v = ftAlgorithm::utf8toUnicode(str); int strSize = v.size(); int size = ftAlgorithm::nextPower2(strSize); int cols = 1; while (size / cols > cols) cols <<= 1; int rows = size / cols; int w = h; int imgW = w * cols; int imgH = h * rows; FT_Set_Pixel_Sizes(face, 0, h); FT_GlyphSlot slot = face->glyph; unsigned char* expanded_data = new unsigned char[2 * imgW * imgH]; for (int ci = 0; ci < strSize; ci++) { FT_Load_Char(face, v[ci], FT_LOAD_RENDER); FT_Bitmap& bitmap = slot->bitmap; //TODO: save the slot's data in FontMan //std::printf("%d %d %d %d\n", slot->bitmap_left, slot->bitmap_top, bitmap.width, bitmap.rows); int row = ci / cols; int col = ci % cols; copyBitmapToBufferData(bitmap, expanded_data, imgW, w, h, row, col); } //TODO: use SubImage to draw? picID = ftRender::getPicture(expanded_data, imgW, imgH, FT_GRAY_ALPHA); delete [] expanded_data; } <commit_msg>simplify ftType::FontMan::genAsciiTable()<commit_after>#include <fountain/ft_type.h> #include <fountain/ft_render.h> #include <fountain/ft_algorithm.h> #include <cstdio> using ftType::FontMan; FT_Library library; bool ftType::init() { int error = FT_Init_FreeType(&library); if (error) { return false; } return true; } void copyBitmapToBufferData(FT_Bitmap &bitmap, unsigned char *expanded_data, int imgW, int w, int h, int row, int col) { for(int j = 0; j < h; j++) { for(int i = 0; i < w; i++) { int r = row * h + j; int c = col * w + i; expanded_data[2 * (r * imgW + c)] = 255; expanded_data[2 * (r * imgW + c) + 1] = (i >= bitmap.width || j >= bitmap.rows) ? 0 : bitmap.buffer[i + bitmap.width * (bitmap.rows - 1 - j)]; } } } FontMan::FontMan() { picID = 0; } FontMan::~FontMan() { //TODO: fix the bug (double free when delete the pic) //ftRender::deletePicture(picID); } bool FontMan::loadFont(const char *fontname) { int error = FT_New_Face(library, fontname, 0, &face); if (error) { return false; } return true; } //TODO: make these two functions less code void FontMan::genAsciiTable(int h) { //TODO: check the state of picID char asciiTable[129]; asciiTable[0] = ' '; for (int i = 1; i < 128; i++) asciiTable[i] = i; asciiTable[128] = '\0'; this->genStringTable(asciiTable, h); } void FontMan::genStringTable(const char *str, int h) { //TODO: check the state of picID h = ftAlgorithm::nextPower2(h); std::vector<unsigned long> v = ftAlgorithm::utf8toUnicode(str); int strSize = v.size(); int size = ftAlgorithm::nextPower2(strSize); int cols = 1; while (size / cols > cols) cols <<= 1; int rows = size / cols; int w = h; int imgW = w * cols; int imgH = h * rows; FT_Set_Pixel_Sizes(face, 0, h); FT_GlyphSlot slot = face->glyph; unsigned char* expanded_data = new unsigned char[2 * imgW * imgH]; for (int ci = 0; ci < strSize; ci++) { FT_Load_Char(face, v[ci], FT_LOAD_RENDER); FT_Bitmap& bitmap = slot->bitmap; //TODO: save the slot's data in FontMan //std::printf("%d %d %d %d\n", slot->bitmap_left, slot->bitmap_top, bitmap.width, bitmap.rows); int row = ci / cols; int col = ci % cols; copyBitmapToBufferData(bitmap, expanded_data, imgW, w, h, row, col); } //TODO: use SubImage to draw? picID = ftRender::getPicture(expanded_data, imgW, imgH, FT_GRAY_ALPHA); delete [] expanded_data; } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Sven Kaulmann #ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #include <dune/common/fvector.hh> #include <dune/grid/common/backuprestore.hh> #include <dune/grid/common/grid.hh> #include <dune/grid/common/entity.hh> #include <dune/grid/io/file/vtk/function.hh> #if HAVE_DUNE_FEM # include <dune/fem/function/common/discretefunction.hh> # include <dune/fem/quadrature/cachingquadrature.hh> # include <dune/fem/space/lagrange.hh> # include <dune/fem/space/finitevolume.hh> #endif #include <dune/stuff/common/ranges.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/fem/namespace.hh> #include <dune/stuff/grid/search.hh> namespace Dune { namespace Stuff { #if HAVE_DUNE_FEM template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space, const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.nop(); std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP)); } return points; } template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& /*space*/, const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity) { assert(false); typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret; return Ret(1, target_entity.geometry().center()); } template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class HeterogenousProjection { public: /** If your SearchStrategy only takes a leafview of the source grid, you may use this signature. * Otherwise you'll have to provide an instance of the SearchStrategy to the method below **/ template < class SourceDFImp, class TargetDFImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target) { SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView()); project(source, target, search); } //! signature for non-default SearchStrategy constructions template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target, SearchStrategyImp& search) { typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType; static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange; const auto& space = target.space(); // set all DoFs to infinity preprocess(target); const auto endit = space.end(); for(auto it = space.begin(); it != endit ; ++it) { const auto& target_entity = *it; auto target_local_function = target.localFunction(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename TargetDiscreteFunctionSpaceType::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { if(std::isinf(target_local_function[ k ])) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& source_local_function = source.localFunction(*source_entity_ptr); source_local_function.evaluate(source_local_point, source_value); for(int i = 0; i < target_dimRange; ++i, ++k) setDofValue(target_local_function[k], source_value[i]); } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } else k += target_dimRange; } } postprocess(target); } // ... project(...) protected: template<class TargetDFImp> static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { typedef typename TargetDFImp::DofType TargetDofType; const auto infinity = DSC::numeric_limits< TargetDofType >::infinity(); // set all DoFs to infinity const auto dend = func.dend(); for( auto dit = func.dbegin(); dit != dend; ++dit ) *dit = infinity; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof = value; } template<class TargetDFImp> static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& /*func*/) { return; } }; // class HeterogenousProjection #endif // HAVE_DUNE_FEM #if HAVE_DUNE_GDT template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim > std::vector<typename GDT::Spaces::CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::DomainType> global_evaluation_points(const GDT::Spaces::CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >& space, const typename GDT::Spaces::CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrange_points(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.size(); std::vector<typename GDT::Spaces::CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set[qP]); } return points; } class MsFEMProjection { public: //! signature for non-default SearchStrategy constructions template < class SourceSpaceImp, class TargetSpaceImp, class SourceVectorImp, class TargetVectorImp, class SearchStrategyImp > static void project(const GDT::ConstDiscreteFunction< SourceSpaceImp, SourceVectorImp >& source, GDT::DiscreteFunction< TargetSpaceImp, TargetVectorImp >& target, SearchStrategyImp& search) { static const int target_dimRange = TargetSpaceImp::dimRange; const auto& space = target.space(); preprocess(target); const auto interior = space.grid_view().grid().template leafGridView<Interior_Partition>(); for(const auto& target_entity : DSC::entityRange(interior)) { auto target_local_function = target.local_discrete_function(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); int k = 0; typename GDT::DiscreteFunction< SourceSpaceImp, SourceVectorImp >::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& ent = *source_entity_ptr; const auto& source_local_function = source.local_function(ent); source_value = source_local_function->evaluate(source_local_point); for(int i = 0; i < target_dimRange; ++i, ++k) { target_local_function->vector().add(k, source_value[i]); } } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } } postprocess(target); } // ... project(...) protected: template<class TargetSpaceImp, class VectorImp> static void preprocess(GDT::DiscreteFunction< TargetSpaceImp, VectorImp >& func) { // set all DoFs to zero func.vector() *= 0; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof += value; } template<class TargetSpaceImp, class VectorImp> static void postprocess(GDT::DiscreteFunction< TargetSpaceImp, VectorImp >& func) { // compute node to entity relations constexpr static int dimension = TargetSpaceImp::GridViewType::Grid::dimension; std::vector<int> nodeToEntity(func.space().grid_view().grid().size(dimension), 0); identifySharedNodes(func.space().grid_view(), nodeToEntity); auto factorsIt = nodeToEntity.begin(); for (auto& dit : func.vector()) { assert(factorsIt!=nodeToEntity.end()); assert(*factorsIt>0); dit /= *factorsIt; ++factorsIt; } return; } template<class GridPartType, class MapType> static void identifySharedNodes(const GridPartType& gridPart, MapType& map) { typedef typename GridPartType::Grid GridType; const auto& indexSet = gridPart.indexSet(); for (auto& entity : DSC::entityRange(gridPart.grid().leafGridView())) { int number_of_nodes_in_entity = entity.template count<GridType::dimension>(); for (int i = 0; i < number_of_nodes_in_entity; ++i) { const auto node = entity.template subEntity<GridType::dimension>(i); const auto global_index_node = indexSet.index(*node); // make sure we don't access non-existing elements assert(map.size() > global_index_node); ++map[global_index_node]; } } } }; #endif // HAVE_DUNE_GDT } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH <commit_msg>[discretefunction.projection.heterogeneous] refs #10<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Sven Kaulmann #ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH #include <dune/common/fvector.hh> #include <dune/grid/common/backuprestore.hh> #include <dune/grid/common/grid.hh> #include <dune/grid/common/entity.hh> #include <dune/grid/io/file/vtk/function.hh> #if HAVE_DUNE_FEM # include <dune/fem/function/common/discretefunction.hh> # include <dune/fem/quadrature/cachingquadrature.hh> # include <dune/fem/space/lagrange.hh> # include <dune/fem/space/finitevolume.hh> #endif #include <dune/stuff/common/ranges.hh> #include <dune/stuff/aliases.hh> #include <dune/stuff/fem/namespace.hh> #include <dune/stuff/grid/search.hh> namespace Dune { namespace Stuff { #if HAVE_DUNE_FEM template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space, const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.nop(); std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP)); } return points; } template< class F, class G, int p, template< class > class S > std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> global_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& /*space*/, const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity) { assert(false); typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret; return Ret(1, target_entity.geometry().center()); } template< template< class > class SearchStrategy = Grid::EntityInlevelSearch > class HeterogenousProjection { public: /** If your SearchStrategy only takes a leafview of the source grid, you may use this signature. * Otherwise you'll have to provide an instance of the SearchStrategy to the method below **/ template < class SourceDFImp, class TargetDFImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target) { SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView()); project(source, target, search); } //! signature for non-default SearchStrategy constructions template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp > static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source, Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target, SearchStrategyImp& search) { typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType; static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange; const auto& space = target.space(); // set all DoFs to infinity preprocess(target); const auto endit = space.end(); for(auto it = space.begin(); it != endit ; ++it) { const auto& target_entity = *it; auto target_local_function = target.localFunction(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); size_t k = 0; typename TargetDiscreteFunctionSpaceType::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { if(std::isinf(target_local_function[ k ])) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& source_local_function = source.localFunction(*source_entity_ptr); source_local_function.evaluate(source_local_point, source_value); for(size_t i = 0; i < target_dimRange; ++i, ++k) setDofValue(target_local_function[k], source_value[i]); } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } else k += target_dimRange; } } postprocess(target); } // ... project(...) protected: template<class TargetDFImp> static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) { typedef typename TargetDFImp::DofType TargetDofType; const auto infinity = DSC::numeric_limits< TargetDofType >::infinity(); // set all DoFs to infinity const auto dend = func.dend(); for( auto dit = func.dbegin(); dit != dend; ++dit ) *dit = infinity; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof = value; } template<class TargetDFImp> static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& /*func*/) { return; } }; // class HeterogenousProjection #endif // HAVE_DUNE_FEM #if HAVE_DUNE_GDT template< class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim > std::vector<typename GDT::Spaces::CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::DomainType> global_evaluation_points(const GDT::Spaces::CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >& space, const typename GDT::Spaces::CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::EntityType& target_entity) { const auto& target_lagrangepoint_set = space.lagrange_points(target_entity); const auto& target_geometry = target_entity.geometry(); const auto quadNop = target_lagrangepoint_set.size(); std::vector<typename GDT::Spaces::CGInterface< ImpTraits, domainDim, RangeFieldImp, rangeDim, 1 >::DomainType> points(quadNop); for(size_t qP = 0; qP < quadNop ; ++qP) { points[qP] = target_geometry.global(target_lagrangepoint_set[qP]); } return points; } class MsFEMProjection { public: //! signature for non-default SearchStrategy constructions template < class SourceSpaceImp, class TargetSpaceImp, class SourceVectorImp, class TargetVectorImp, class SearchStrategyImp > static void project(const GDT::ConstDiscreteFunction< SourceSpaceImp, SourceVectorImp >& source, GDT::DiscreteFunction< TargetSpaceImp, TargetVectorImp >& target, SearchStrategyImp& search) { static const int target_dimRange = TargetSpaceImp::dimRange; const auto& space = target.space(); preprocess(target); const auto interior = space.grid_view().grid().template leafGridView<Interior_Partition>(); for(const auto& target_entity : DSC::entityRange(interior)) { auto target_local_function = target.local_discrete_function(target_entity); const auto global_quads = global_evaluation_points(space, target_entity); const auto evaluation_entity_ptrs = search(global_quads); assert(evaluation_entity_ptrs.size() >= global_quads.size()); size_t k = 0; typename GDT::DiscreteFunction< SourceSpaceImp, SourceVectorImp >::RangeType source_value; for(size_t qP = 0; qP < global_quads.size() ; ++qP) { const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP]; if (source_entity_unique_ptr) { const auto& source_entity_ptr = (*source_entity_unique_ptr); const auto& source_geometry = source_entity_ptr->geometry(); const auto& global_point = global_quads[qP]; const auto& source_local_point = source_geometry.local(global_point); const auto& ent = *source_entity_ptr; const auto& source_local_function = source.local_function(ent); source_value = source_local_function->evaluate(source_local_point); for(size_t i = 0; i < target_dimRange; ++i, ++k) { target_local_function->vector().add(k, source_value[i]); } } else { DUNE_THROW(InvalidStateException, "Did not find the local lagrange point in the source mesh!"); } } } postprocess(target); } // ... project(...) protected: template<class TargetSpaceImp, class VectorImp> static void preprocess(GDT::DiscreteFunction< TargetSpaceImp, VectorImp >& func) { // set all DoFs to zero func.vector() *= 0; } template<class DofType, class SourceType > static void setDofValue(DofType& dof, const SourceType& value) { dof += value; } template<class TargetSpaceImp, class VectorImp> static void postprocess(GDT::DiscreteFunction< TargetSpaceImp, VectorImp >& func) { // compute node to entity relations constexpr static size_t dimension = TargetSpaceImp::GridViewType::Grid::dimension; std::vector<int> nodeToEntity(func.space().grid_view().grid().size(dimension), 0); identifySharedNodes(func.space().grid_view(), nodeToEntity); auto factorsIt = nodeToEntity.begin(); for (auto& dit : func.vector()) { assert(factorsIt!=nodeToEntity.end()); assert(*factorsIt>0); dit /= *factorsIt; ++factorsIt; } return; } template<class GridPartType, class MapType> static void identifySharedNodes(const GridPartType& gridPart, MapType& map) { typedef typename GridPartType::Grid GridType; const auto& indexSet = gridPart.indexSet(); for (auto& entity : DSC::entityRange(gridPart.grid().leafGridView())) { const auto number_of_nodes_in_entity = entity.template count<GridType::dimension>(); for (decltype(number_of_nodes_in_entity) i = 0; i < number_of_nodes_in_entity; ++i) { const auto node = entity.template subEntity<GridType::dimension>(i); const auto global_index_node = indexSet.index(*node); // make sure we don't access non-existing elements assert(map.size() > global_index_node); ++map[global_index_node]; } } } }; #endif // HAVE_DUNE_GDT } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH <|endoftext|>
<commit_before>/** @file @brief Wrapper for a vrpn_Tracker_VideoBasedHMDTracker @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include <osvr/PluginKit/PluginKit.h> #include <osvr/PluginKit/TrackerInterfaceC.h> #include "Oculus_DK2.h" #include "LED.h" #include "BeaconBasedPoseEstimator.h" // Generated JSON header file #include "com_osvr_VideoBasedHMDTracker_json.h" // Library/third-party includes #include <opencv2/core/core.hpp> // for basic OpenCV types #include <opencv2/core/operations.hpp> #include <opencv2/highgui/highgui.hpp> // for image capture #include <opencv2/imgproc/imgproc.hpp> // for image scaling #include <boost/noncopyable.hpp> // Standard includes #include <iostream> #include <sstream> #include <memory> #define VBHMD_DEBUG // Anonymous namespace to avoid symbol collision namespace { class VideoBasedHMDTracker : boost::noncopyable { public: VideoBasedHMDTracker(OSVR_PluginRegContext ctx, int cameraNum = 0, int channel = 0) { // Initialize things from parameters and from defaults. Do it here rather than // in an initialization list so that we're independent of member order declaration. m_camera = cameraNum; m_channel = channel; m_type = Unknown; m_dk2 = nullptr; m_estimator = nullptr; /// Create the initialization options OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx); // Configure the tracker interface. osvrDeviceTrackerConfigure(opts, &m_tracker); /// Come up with a device name std::ostringstream os; os << "TrackedCamera" << cameraNum << "_" << channel; /// Create an asynchronous (threaded) device m_dev.initAsync(ctx, os.str(), opts); /// Send JSON descriptor m_dev.sendJsonDescriptor( com_osvr_VideoBasedHMDTracker_json); /// Register update callback m_dev.registerUpdateCallback(this); //=============================================== // Figure out what type of HMD we're using. int height = 0; int width = 0; if (m_camera.isOpened()) { height = static_cast<int>(m_camera.get(CV_CAP_PROP_FRAME_HEIGHT)); width = static_cast<int>(m_camera.get(CV_CAP_PROP_FRAME_WIDTH)); // See if this is an Oculus camera by checking the dimensions of // the image. This camera type improperly describes its format // as being a color format when it is in fact a mono format. bool isOculusCamera = (width == 376) && (height == 480); if (isOculusCamera) { m_type = OculusDK2; } // TODO: Check to see if the resolution/name matches the OSVR HDK camera else { m_type = OSVRHDK; } #ifdef VBHMD_DEBUG std::cout << "Got image of size " << width << "x" << height << ", Format " << m_camera.get(CV_CAP_PROP_FORMAT) << ", Mode " << m_camera.get(CV_CAP_PROP_MODE) << std::endl; if (m_type == OculusDK2) { std::cout << "Is Oculus camera, reformatting to mono" << std::endl; m_dk2.reset(new osvr::oculus_dk2::Oculus_DK2_HID()); } #endif } //=============================================== // Configure objects and set up data structures and devices based on the // type of device we have. switch (m_type) { case OculusDK2: // TODO: Fill these in when they are known m_identifier = nullptr; m_estimator = nullptr; // Set Oculus' camera capture parameters as described // in Oliver Kreylos' OculusRiftDK2VideoDevice.cpp program. Thank you for // him for sharing this with us, used with permission. if (m_type == OculusDK2) { // Trying to find the closest matches to what was being done // in OculusRiftDK2VideoDevice.cpp, but I don't think we're going to // be able to set everything we need to. In fact, these don't seem // to be doing anything (gain does not change the brightness, for // example) and all but the gain setting fails (we must not have the // XIMEA interface). // TODO: There is no OS-independent way to set these parameters on // the camera, so we're not going to be able to use it. // TODO: Would like to set a number of things, but since these are not working, // giving up. } break; case OSVRHDK: { // TODO: Come up with actual estimates for camera and distortion // parameters by calibrating them in OpenCV. double cx = width / 2.0; double cy = height / 2.0; double fx = 300.0; double fy = fx; std::vector< std::vector<double> > m; m.push_back({ fx, 0.0, cx }); m.push_back({ 0.0, fy, cy }); m.push_back({ 0.0, 0.0, 1.0 }); std::vector<double> d; d.push_back(0); d.push_back(0); d.push_back(0); d.push_back(0); d.push_back(0); m_identifier = new osvr::vbtracker::OsvrHdkLedIdentifier(); m_estimator = new osvr::vbtracker::BeaconBasedPoseEstimator(m, d); } break; default: // Also handles the "Unknown" case. // We've already got a NULL identifier and estimator, so nothing to do. break; } } ~VideoBasedHMDTracker() { } OSVR_ReturnCode update() { if (!m_camera.isOpened()) { // Couldn't open the camera. Failing silently for now. Maybe the // camera will be plugged back in later. return OSVR_RETURN_SUCCESS; } // Trigger a camera grab. if (!m_camera.grab()) { // No frame available. return OSVR_RETURN_SUCCESS; } if (!m_camera.retrieve(m_frame, m_channel)) { return OSVR_RETURN_FAILURE; } // Keep track of when we got the image, since that is our // best estimate for when the tracker was at the specified // pose. // TODO: Back-date the aquisition time by the expected image // transfer time and perhaps by half the exposure time to say // when the photons actually arrived. OSVR_TimeValue timestamp; osvrTimeValueGetNow(&timestamp); // If we have an Oculus camera, then we need to reformat the // image pixels. if (m_type == OculusDK2) { m_frame = osvr::oculus_dk2::unscramble_image(m_frame); // Read any reports and discard them. We do this to keep the // LED keepAlive going. m_dk2->poll(); } #ifdef VBHMD_DEBUG if (m_camera.isOpened()) { cv::imshow("Debug window", m_frame); cv::waitKey(1); } #endif // Compute the pose of the HMD w.r.t. the camera frame of reference. OSVR_PoseState pose; osvrPose3SetIdentity(&pose); // XXX Compute pose here. /// Report the new pose, time-stamped with the time we // received the image from the camera. osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker, &pose, 0, &timestamp); return OSVR_RETURN_SUCCESS; } private: osvr::pluginkit::DeviceToken m_dev; OSVR_TrackerDeviceInterface m_tracker; cv::VideoCapture m_camera; int m_channel; cv::Mat m_frame; // What type of HMD are we tracking? enum { Unknown, OSVRHDK, OculusDK2 } m_type; // Structures needed to do the tracking. osvr::vbtracker::LedIdentifier *m_identifier; std::list<osvr::vbtracker::Led> m_leds; osvr::vbtracker::BeaconBasedPoseEstimator *m_estimator; // In case we are using a DK2, we need a pointer to one. std::unique_ptr<osvr::oculus_dk2::Oculus_DK2_HID> m_dk2; }; class HardwareDetection { public: HardwareDetection() : m_found(false) {} OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { if (m_found) { return OSVR_RETURN_SUCCESS; } { // Autodetect camera. This needs to have the same // parameter as the constructor for the VideoBasedHMDTracker // class above or else it will not be looking for the // same camera. This instance of the camera will auto- // delete itself when this block finishes, so should // close the camera -- leaving it to be opened again // in the constructor. cv::VideoCapture cap(0); if (!cap.isOpened()) { // Failed to find camera return OSVR_RETURN_FAILURE; } } m_found = true; /// Create our device object, passing the context. osvr::pluginkit::registerObjectForDeletion(ctx, new VideoBasedHMDTracker(ctx)); return OSVR_RETURN_SUCCESS; } private: /// @brief Have we found our device yet? (this limits the plugin to one /// instance, so that only one tracker will use this camera.) bool m_found; }; } // namespace OSVR_PLUGIN(com_osvr_VideoBasedHMDTracker) { osvr::pluginkit::PluginContext context(ctx); /// Register a detection callback function object. context.registerHardwareDetectCallback(new HardwareDetection()); return OSVR_RETURN_SUCCESS; } <commit_msg>Added code from external stand-alone application that was able to track blobs in video taken on Linux of an OSVR DK2 from a synchronized camera and identify LEDs in it. Added debugging to show different levels along the processing to help track down issues. Ready to try with actual hardware once it arrives.<commit_after>/** @file @brief Wrapper for a vrpn_Tracker_VideoBasedHMDTracker @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include <osvr/PluginKit/PluginKit.h> #include <osvr/PluginKit/TrackerInterfaceC.h> #include "Oculus_DK2.h" #include "LED.h" #include "BeaconBasedPoseEstimator.h" // Generated JSON header file #include "com_osvr_VideoBasedHMDTracker_json.h" // Library/third-party includes #include <opencv2/core/core.hpp> // for basic OpenCV types #include <opencv2/core/operations.hpp> #include <opencv2/highgui/highgui.hpp> // for image capture #include <opencv2/imgproc/imgproc.hpp> // for image scaling #include <boost/noncopyable.hpp> // Standard includes #include <iostream> #include <sstream> #include <memory> #define VBHMD_DEBUG // Anonymous namespace to avoid symbol collision namespace { class VideoBasedHMDTracker : boost::noncopyable { public: VideoBasedHMDTracker(OSVR_PluginRegContext ctx, int cameraNum = 0, int channel = 0) { // Initialize things from parameters and from defaults. Do it here rather than // in an initialization list so that we're independent of member order declaration. m_camera = cameraNum; m_channel = channel; m_type = Unknown; m_dk2 = nullptr; m_estimator = nullptr; /// Create the initialization options OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx); // Configure the tracker interface. osvrDeviceTrackerConfigure(opts, &m_tracker); /// Come up with a device name std::ostringstream os; os << "TrackedCamera" << cameraNum << "_" << channel; /// Create an asynchronous (threaded) device m_dev.initAsync(ctx, os.str(), opts); /// Send JSON descriptor m_dev.sendJsonDescriptor( com_osvr_VideoBasedHMDTracker_json); /// Register update callback m_dev.registerUpdateCallback(this); //=============================================== // Figure out what type of HMD we're using. int height = 0; int width = 0; if (m_camera.isOpened()) { height = static_cast<int>(m_camera.get(CV_CAP_PROP_FRAME_HEIGHT)); width = static_cast<int>(m_camera.get(CV_CAP_PROP_FRAME_WIDTH)); // See if this is an Oculus camera by checking the dimensions of // the image. This camera type improperly describes its format // as being a color format when it is in fact a mono format. bool isOculusCamera = (width == 376) && (height == 480); if (isOculusCamera) { m_type = OculusDK2; } // TODO: Check to see if the resolution/name matches the OSVR HDK camera else { m_type = OSVRHDK; } #ifdef VBHMD_DEBUG std::cout << "Got image of size " << width << "x" << height << ", Format " << m_camera.get(CV_CAP_PROP_FORMAT) << ", Mode " << m_camera.get(CV_CAP_PROP_MODE) << std::endl; if (m_type == OculusDK2) { std::cout << "Is Oculus camera, reformatting to mono" << std::endl; m_dk2.reset(new osvr::oculus_dk2::Oculus_DK2_HID()); } #endif } //=============================================== // Configure objects and set up data structures and devices based on the // type of device we have. switch (m_type) { case OculusDK2: // TODO: Fill these in when they are known m_identifier = nullptr; m_estimator = nullptr; // Set Oculus' camera capture parameters as described // in Oliver Kreylos' OculusRiftDK2VideoDevice.cpp program. Thank you for // him for sharing this with us, used with permission. if (m_type == OculusDK2) { // Trying to find the closest matches to what was being done // in OculusRiftDK2VideoDevice.cpp, but I don't think we're going to // be able to set everything we need to. In fact, these don't seem // to be doing anything (gain does not change the brightness, for // example) and all but the gain setting fails (we must not have the // XIMEA interface). // TODO: There is no OS-independent way to set these parameters on // the camera, so we're not going to be able to use it. // TODO: Would like to set a number of things, but since these are not working, // giving up. } break; case OSVRHDK: { // TODO: Come up with actual estimates for camera and distortion // parameters by calibrating them in OpenCV. double cx = width / 2.0; double cy = height / 2.0; double fx = 300.0; double fy = fx; std::vector< std::vector<double> > m; m.push_back({ fx, 0.0, cx }); m.push_back({ 0.0, fy, cy }); m.push_back({ 0.0, 0.0, 1.0 }); std::vector<double> d; d.push_back(0); d.push_back(0); d.push_back(0); d.push_back(0); d.push_back(0); m_identifier = new osvr::vbtracker::OsvrHdkLedIdentifier(); m_estimator = new osvr::vbtracker::BeaconBasedPoseEstimator(m, d); } break; default: // Also handles the "Unknown" case. // We've already got a NULL identifier and estimator, so nothing to do. break; } } ~VideoBasedHMDTracker() { // It is okay to delete NULL pointers, so we don't check here. delete m_estimator; delete m_identifier; } OSVR_ReturnCode update() { if (!m_camera.isOpened()) { // Couldn't open the camera. Failing silently for now. Maybe the // camera will be plugged back in later. return OSVR_RETURN_SUCCESS; } //================================================================== // Trigger a camera grab. if (!m_camera.grab()) { // No frame available. return OSVR_RETURN_SUCCESS; } if (!m_camera.retrieve(m_frame, m_channel)) { return OSVR_RETURN_FAILURE; } //================================================================== // Keep track of when we got the image, since that is our // best estimate for when the tracker was at the specified // pose. // TODO: Back-date the aquisition time by the expected image // transfer time and perhaps by half the exposure time to say // when the photons actually arrived. OSVR_TimeValue timestamp; osvrTimeValueGetNow(&timestamp); //================================================================== // If we have an Oculus camera, then we need to reformat the // image pixels. if (m_type == OculusDK2) { m_frame = osvr::oculus_dk2::unscramble_image(m_frame); // Read any reports and discard them. We do this to keep the // LED keepAlive going. m_dk2->poll(); } //================================================================== // Convert the image into a format we can use. cv::cvtColor(m_frame, m_imageGray, CV_RGB2GRAY); //================================================================ // Tracking the points // Threshold the image based on the brightness value that is halfway between // the darkest and brightest pixel in the image. double minVal, maxVal; cv::minMaxLoc(m_imageGray, &minVal, &maxVal); double thresholdValue = minVal + (maxVal - minVal) * 0.8; cv::threshold(m_imageGray, m_thresholdImage, thresholdValue, 255, CV_THRESH_BINARY); // Construct a blob detector and find the blobs in the image. // TODO: Determine the maximum size of a trackable blob by seeing // when we're so close that we can't view at least four in the // camera. cv::SimpleBlobDetector::Params params; params.filterByColor = true; // Look for bright blobs params.blobColor = static_cast<uchar>(maxVal); params.filterByInertia = true; // Look for non-elongated blobs params.minInertiaRatio = 0.5; params.maxInertiaRatio = 1.0; cv::SimpleBlobDetector detector(params); std::vector<cv::KeyPoint> keyPoints; detector.detect(m_imageGray, keyPoints); // Draw detected blobs as red circles. cv::drawKeypoints(m_frame, keyPoints, m_imageWithBlobs, cv::Scalar(0, 0, 255), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS); //if (keyPoints.size() > 0) { std::cout << "First keypoint location: " << keyPoints[0].pt.x << ", " << keyPoints[0].pt.y << std::endl; } // TODO: Consider computing the center of mass of a dilated bounding // rectangle around each keypoint to produce a more precise subpixel // localization of each LED. The moments() function may be helpful // with this. // TODO: Estimate the summed brightness of each blob so that we can // detect when they are getting brighter and dimmer. Pass this as // the brightness parameter to the // Locate the closest blob from this frame to each LED found // in the previous frame. If it is close enough to the nearest neighbor from last // time, we assume that it is the same LED and update it. If not, we // delete the LED from the list. Once we have matched a blob to an // LED, we remove it from the list. If there are any blobs leftover, // we create new LEDs from them. // TODO: Include motion estimate based on Kalman filter along with // model of the projection once we have one built. Note that this will // require handling the lens distortion appropriately. std::list<osvr::vbtracker::Led>::iterator led = m_leds.begin(); while (led != m_leds.end()) { double TODO_BLOB_MOVE_THRESHOLD = 10; std::vector<cv::KeyPoint>::iterator nearest; nearest = led->nearest(keyPoints, TODO_BLOB_MOVE_THRESHOLD); if (nearest == keyPoints.end()) { // We have no blob corresponding to this LED, so we need // to delete this LED. led = m_leds.erase(led); } else { // Update the values in this LED and then go on to the // next one. Remove this blob from the list of potential // matches. led->addMeasurement(nearest->pt, nearest->size); keyPoints.erase(nearest); led++; } } // If we have any blobs that have not been associated with an // LED, then we add a new LED for each of them. //std::cout << "Had " << Leds.size() << " LEDs, " << keyPoints.size() << " new ones available" << std::endl; while (keyPoints.size() > 0) { osvr::vbtracker::Led newLed(m_identifier, keyPoints.begin()->pt, keyPoints.begin()->size); m_leds.push_back(newLed); keyPoints.erase(keyPoints.begin()); } // Label the keypoints with their IDs. for (led = m_leds.begin(); led != m_leds.end(); led++) { std::ostringstream label; label << led->getID(); cv::Point where = led->getLocation(); where.x += 1; where.y += 1; cv::putText(m_imageWithBlobs, label.str(), where, cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255)); } //================================================================== // Compute the pose of the HMD w.r.t. the camera frame of reference. OSVR_PoseState pose; osvrPose3SetIdentity(&pose); // XXX Compute pose here. #ifdef VBHMD_DEBUG if (m_camera.isOpened()) { cv::imshow("Debug window", m_frame); int key = cv::waitKey(1); switch (key) { case 'i': // Show the input image. m_shownImage = &m_frame; break; case 't': // Show the thresholded image. m_shownImage = &m_thresholdImage; break; case 'b': // Show the blob image. m_shownImage = &m_imageWithBlobs; break; } } #endif //================================================================== /// Report the new pose, time-stamped with the time we // received the image from the camera. osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker, &pose, 0, &timestamp); return OSVR_RETURN_SUCCESS; } private: osvr::pluginkit::DeviceToken m_dev; OSVR_TrackerDeviceInterface m_tracker; cv::VideoCapture m_camera; int m_channel; cv::Mat m_frame; cv::Mat m_imageGray; cv::Mat m_thresholdImage; cv::Mat m_imageWithBlobs; #ifdef VBHMD_DEBUG cv::Mat *m_shownImage = &m_frame; #endif // What type of HMD are we tracking? enum { Unknown, OSVRHDK, OculusDK2 } m_type; // Structures needed to do the tracking. osvr::vbtracker::LedIdentifier *m_identifier; std::list<osvr::vbtracker::Led> m_leds; osvr::vbtracker::BeaconBasedPoseEstimator *m_estimator; // In case we are using a DK2, we need a pointer to one. std::unique_ptr<osvr::oculus_dk2::Oculus_DK2_HID> m_dk2; }; class HardwareDetection { public: HardwareDetection() : m_found(false) {} OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { if (m_found) { return OSVR_RETURN_SUCCESS; } { // Autodetect camera. This needs to have the same // parameter as the constructor for the VideoBasedHMDTracker // class above or else it will not be looking for the // same camera. This instance of the camera will auto- // delete itself when this block finishes, so should // close the camera -- leaving it to be opened again // in the constructor. cv::VideoCapture cap(0); if (!cap.isOpened()) { // Failed to find camera return OSVR_RETURN_FAILURE; } } m_found = true; /// Create our device object, passing the context. osvr::pluginkit::registerObjectForDeletion(ctx, new VideoBasedHMDTracker(ctx)); return OSVR_RETURN_SUCCESS; } private: /// @brief Have we found our device yet? (this limits the plugin to one /// instance, so that only one tracker will use this camera.) bool m_found; }; } // namespace OSVR_PLUGIN(com_osvr_VideoBasedHMDTracker) { osvr::pluginkit::PluginContext context(ctx); /// Register a detection callback function object. context.registerHardwareDetectCallback(new HardwareDetection()); return OSVR_RETURN_SUCCESS; } <|endoftext|>
<commit_before>/** @file test_kmeans_generate.cpp * @brief generate Kmeans problem and save it to separate files * * @author Lukas Pospisil */ #include "pascinference.h" #include "data/kmeansdata.h" #include "model/kmeansh1fem.h" #ifndef USE_PETSCVECTOR #error 'This example is for PETSCVECTOR' #endif typedef petscvector::PetscVector PetscVector; using namespace pascinference; extern int pascinference::DEBUG_MODE; int solution_get_cluster_id(int t, int T){ int id_cluster; if((t >= ceil(0*T) && t < ceil(0.1*T)) || (t >= ceil(0.35*T) && t < ceil(0.4*T)) || (t >= ceil(0.5*T) && t < ceil(0.52*T)) || (t >= ceil(0.8*T) && t < ceil(0.9*T)) || (t >= ceil(0.2*T) && t < ceil(0.25*T))){ id_cluster = 0; } if((t >= ceil(0.1*T) && t < ceil(0.2*T)) || (t >= ceil(0.4*T) && t < ceil(0.5*T)) || (t >= ceil(0.8*T) && t < ceil(0.8*T)) || (t >= ceil(0.95*T) && t <= ceil(1.0*T)) || (t >= ceil(0.6*T) && t < ceil(0.8*T))){ id_cluster = 1; } if((t >= ceil(0.25*T) && t < ceil(0.35*T)) || (t >= ceil(0.52*T) && t < ceil(0.6*T)) || (t >= ceil(0.9*T) && t < ceil(0.95*T))){ id_cluster = 2; } return id_cluster; } int main( int argc, char *argv[] ) { /* add local program options */ boost::program_options::options_description opt_problem("PROBLEM EXAMPLE", consoleArg.get_console_nmb_cols()); opt_problem.add_options() ("test_Tbegin", boost::program_options::value<int>(), "dimension of the problem") ("test_Tstep", boost::program_options::value<int>(), "dimension of the problem") ("test_Tend", boost::program_options::value<int>(), "dimension of the problem") ("test_Kbegin", boost::program_options::value<int>(), "number of clusters") ("test_Kstep", boost::program_options::value<int>(), "number of clusters") ("test_Kend", boost::program_options::value<int>(), "number of clusters"); consoleArg.get_description()->add(opt_problem); /* call initialize */ if(!Initialize(argc, argv)){ return 0; } /* which times to generate */ int T_begin,T_step, T_end; if(!consoleArg.set_option_value("test_Tbegin", &T_begin)){ std::cout << "test_Tbegin has to be set! Call application with parameter -h to see all parameters" << std::endl; return 0; } consoleArg.set_option_value("test_Tend", &T_end, T_begin); consoleArg.set_option_value("test_Tstep", &T_step, 1); /* gamma0 to which K to generate */ int K_begin,K_step, K_end; if(!consoleArg.set_option_value("test_Kbegin", &K_begin)){ std::cout << "test_Kbegin has to be set! Call application with parameter -h to see all parameters" << std::endl; return 0; } consoleArg.set_option_value("test_Kend", &K_end, K_begin); consoleArg.set_option_value("test_Kstep", &K_step, 1); coutMaster << "- PROBLEM INFO --------------------------------------------------" << std::endl; coutMaster << " T_begin:T_step:T_end = " << std::setw(7) << T_begin << std::setw(7) << T_step << std::setw(7) << T_end << " (length of time-series)" << std::endl; coutMaster << " K_begin:K_step:K_end = " << std::setw(7) << K_begin << std::setw(7) << K_step << std::setw(7) << K_end << " (number of clusters)" << std::endl; coutMaster << "------------------------------------------------------------------" << std::endl; /* start logging */ std::ostringstream oss_name_of_file_log; oss_name_of_file_log << "results/test_kmeans_generate_log_p" << GlobalManager.get_rank() << ".txt"; logging.begin(oss_name_of_file_log.str()); /* say hello */ coutMaster << "- start program" << std::endl; /* parameters of the model */ int xdim = 3; /* data dimension */ /* solution - for generating the problem */ int solution_K = 3; double solution_theta[9] = { 0.0, 0.0, 0.0, /* K=1,n=1,2,3: mu */ 1.0, 0.0, 0.0, /* K=2,n=1,2,3 */ 0.0, 1.0, 0.0 /* K=3,n=1,2,3 */ }; double solution_xstart[3] = { 0.0, 0.0, 0.0 /* n=1,2,3 */ }; double noise_covariance[9] = { 0.05, 0.05, 0.01, 0.05, 0.05, 0.01, 0.05, 0.05, 0.01 }; std::ostringstream oss_name_of_file; /* prepare random generator */ PetscRandom rnd; TRY( PetscRandomCreate(PETSC_COMM_WORLD,&rnd) ); TRY( PetscRandomSetType(rnd,PETSCRAND) ); TRY( PetscRandomSetFromOptions(rnd) ); TRY( PetscRandomSetSeed(rnd,13) ); /* ---- GENERATE THE LARGEST PROBLEM ---- */ /* prepare data */ coutMaster << "- generating largest problem: T = " << T_end << std::endl; KmeansData<PetscVector> mydata(T_end,xdim); KmeansH1FEMModel<PetscVector> mymodel(mydata, xdim, solution_K, 0); mydata.set_model(mymodel); mydata.generate(solution_K, solution_theta, &solution_get_cluster_id, false); mydata.add_noise(noise_covariance); /* save data */ oss_name_of_file << "results/data_kmeans_T" << T_end << ".bin"; coutMaster << "- saving: " << oss_name_of_file.str() << std::endl; mydata.save_datavector(oss_name_of_file.str()); oss_name_of_file.str(""); /* generate gamma0 vector for all K */ SimplexFeasibleSet_Local *feasibleset; Vec *gamma0s_Vec; /* array of vectors */ GeneralVector<PetscVector> *gamma0; /* temp general vector for projection */ int K_num = (K_end - K_begin)/(double)K_step; gamma0s_Vec = (Vec *)(malloc(K_num*sizeof(Vec))); PetscViewer viewer_out; Vec data_Vec = mydata.get_datavector()->get_vector(); int k, ki; for(ki = 0; ki <= K_num; ki++){ k = K_begin + ki*K_step; coutMaster << "- getting subgamma: K = " << k << std::endl; /* create feasible set - we will project */ feasibleset = new SimplexFeasibleSet_Local(T_end,k); /* create general vector */ TRY( VecCreateSeq(PETSC_COMM_SELF, k*T_end, &(gamma0s_Vec[ki])) ); gamma0 = new GeneralVector<PetscVector>(gamma0s_Vec[ki]); /* generate random gamma */ TRY( VecSetRandom(gamma0s_Vec[ki], rnd) ); /* project initial approximation to feasible set */ feasibleset->project(*gamma0); /* store initial approximation */ oss_name_of_file << "results/gamma0_kmeans_T" << T_end << "K" << k << ".bin"; coutMaster << "- saving: " << oss_name_of_file.str() << std::endl; TRY( PetscViewerBinaryOpen(PETSC_COMM_WORLD,oss_name_of_file.str().c_str(),FILE_MODE_WRITE,&viewer_out) ); TRY( VecView( gamma0s_Vec[ki], viewer_out) ); TRY( PetscViewerDestroy(&viewer_out) ); oss_name_of_file.str(""); /* destroy feasible set */ free(feasibleset); } /* ---- GET SUB PROBLEMS ---- */ Vec subdata_Vec; IS *subdata_ISs; subdata_ISs = (IS *)(malloc(xdim*sizeof(IS))); IS subdata_IS; Vec gamma0sum_Vec; IS *gamma0sub_ISs; IS gamma0sub_IS; int t,i; for(t=T_begin;t<T_end;t+=T_step){ coutMaster << "- getting subproblem: T = " << t << std::endl; /* for every dimension of data create stride */ for(i=0;i<xdim;i++){ TRY( ISCreateStride(PETSC_COMM_WORLD, t, i*T_end, T_end/(double)(t), &(subdata_ISs[i])) ); } TRY( ISConcatenate(PETSC_COMM_WORLD, xdim, subdata_ISs, &subdata_IS) ); /* get subvector */ TRY( VecGetSubVector(data_Vec, subdata_IS, &subdata_Vec) ); /* save data */ oss_name_of_file << "results/data_kmeans_T" << t << ".bin"; coutMaster << "- saving: " << oss_name_of_file.str() << std::endl; TRY( PetscViewerBinaryOpen(PETSC_COMM_WORLD,oss_name_of_file.str().c_str(),FILE_MODE_WRITE,&viewer_out) ); TRY( VecView( subdata_Vec, viewer_out) ); TRY( PetscViewerDestroy(&viewer_out) ); oss_name_of_file.str(""); /* restore subvector */ TRY( VecRestoreSubVector(data_Vec, subdata_IS, &subdata_Vec) ); /* destroy indexsets */ for(i=0;i<xdim;i++){ TRY( ISDestroy(&(subdata_ISs[i])) ); } TRY( ISDestroy(&subdata_IS) ); /* subvectors from gamma0 */ for(ki = 0; ki <= K_num; ki++){ k = K_begin + ki*K_step; coutMaster << "- getting subgamma: K = " << k << std::endl; /* get subvectors from gamma0 */ gamma0sub_ISs = (IS*)malloc(k*sizeof(IS)); for(i=0;i<k;i++){ TRY( ISCreateStride(PETSC_COMM_WORLD, t, i*T_end, T_end/(double)(t), &(gamma0sub_ISs[i])) ); } TRY( ISConcatenate(PETSC_COMM_WORLD, k, gamma0sub_ISs, &gamma0sub_IS) ); /* get subvector */ TRY( VecGetSubVector(gamma0s_Vec[ki], gamma0sub_IS, &gamma0sum_Vec) ); /* save data */ oss_name_of_file << "results/gamma0_kmeans_T" << t << "K" << k << ".bin"; coutMaster << "- saving: " << oss_name_of_file.str() << std::endl; TRY( PetscViewerBinaryOpen(PETSC_COMM_WORLD,oss_name_of_file.str().c_str(),FILE_MODE_WRITE,&viewer_out) ); TRY( VecView( gamma0sum_Vec, viewer_out) ); TRY( PetscViewerDestroy(&viewer_out) ); oss_name_of_file.str(""); /* restore subvector */ TRY( VecRestoreSubVector(gamma0s_Vec[ki], gamma0sub_IS, &gamma0sum_Vec) ); for(i=0;i<k;i++){ TRY( ISDestroy(&(gamma0sub_ISs[i])) ); } free(gamma0sub_ISs); TRY( ISDestroy(&gamma0sub_IS) ); } } /* destroy the random generator */ TRY( PetscRandomDestroy(&rnd) ); /* say bye */ coutMaster << "- end program" << std::endl; logging.end(); Finalize(); return 0; } <commit_msg>generator now takes more arguments of T and K and store them into vector<commit_after>/** @file test_kmeans_generate.cpp * @brief generate Kmeans problem and save it to separate files * * @author Lukas Pospisil */ #include <iostream> #include <list> #include <algorithm> #include "pascinference.h" #include "data/kmeansdata.h" #include "model/kmeansh1fem.h" #ifndef USE_PETSCVECTOR #error 'This example is for PETSCVECTOR' #endif typedef petscvector::PetscVector PetscVector; using namespace pascinference; extern int pascinference::DEBUG_MODE; int solution_get_cluster_id(int t, int T){ int id_cluster; if((t >= ceil(0*T) && t < ceil(0.1*T)) || (t >= ceil(0.35*T) && t < ceil(0.4*T)) || (t >= ceil(0.5*T) && t < ceil(0.52*T)) || (t >= ceil(0.8*T) && t < ceil(0.9*T)) || (t >= ceil(0.2*T) && t < ceil(0.25*T))){ id_cluster = 0; } if((t >= ceil(0.1*T) && t < ceil(0.2*T)) || (t >= ceil(0.4*T) && t < ceil(0.5*T)) || (t >= ceil(0.8*T) && t < ceil(0.8*T)) || (t >= ceil(0.95*T) && t <= ceil(1.0*T)) || (t >= ceil(0.6*T) && t < ceil(0.8*T))){ id_cluster = 1; } if((t >= ceil(0.25*T) && t < ceil(0.35*T)) || (t >= ceil(0.52*T) && t < ceil(0.6*T)) || (t >= ceil(0.9*T) && t < ceil(0.95*T))){ id_cluster = 2; } return id_cluster; } int main( int argc, char *argv[] ) { /* add local program options */ boost::program_options::options_description opt_problem("PROBLEM EXAMPLE", consoleArg.get_console_nmb_cols()); opt_problem.add_options() ("test_T", boost::program_options::value<std::vector<int> >()->multitoken(), "dimensions of the problem") ("test_K", boost::program_options::value<std::vector<int> >()->multitoken(), "numbers of clusters"); consoleArg.get_description()->add(opt_problem); /* call initialize */ if(!Initialize(argc, argv)){ return 0; } /* which times to generate */ int T; std::vector<int> T_list; if(!consoleArg.set_option_value("test_T", &T_list)){ std::cout << "test_T has to be set! Call application with parameter -h to see all parameters" << std::endl; return 0; } /* gamma0 to which K to generate */ int K; std::vector<int> K_list; if(!consoleArg.set_option_value("test_K", &K_list)){ std::cout << "test_K has to be set! Call application with parameter -h to see all parameters" << std::endl; return 0; } int i; int T_size = T_list.size(); int K_size = K_list.size(); std::ostringstream oss; int T_max = 0; /* print info about what we will compute */ coutMaster << "- PROBLEM INFO --------------------------------------------------" << std::endl; coutMaster << " T = "; for(i=0;i<T_size;i++){ coutMaster << T_list[i]; if(i < T_size-1){ coutMaster << ", "; } /* store maximum value */ if(T_list[i] > T_max){ T_max = T_list[i]; } } coutMaster << " (length of time-series)" << std::endl; coutMaster << " K = "; for(i=0;i<K_size;i++){ coutMaster << K_list[i]; if(i < K_size-1){ coutMaster << ", "; } } coutMaster << " (number of clusters)" << std::endl; coutMaster << "------------------------------------------------------------------" << std::endl; /* start logging */ std::ostringstream oss_name_of_file_log; oss_name_of_file_log << "results/test_kmeans_generate_log_p" << GlobalManager.get_rank() << ".txt"; logging.begin(oss_name_of_file_log.str()); /* say hello */ coutMaster << "- start program" << std::endl; /* parameters of the model */ int xdim = 3; /* data dimension */ /* solution - for generating the problem */ int solution_K = 3; double solution_theta[9] = { 0.0, 0.0, 0.0, /* K=1,n=1,2,3: mu */ 1.0, 0.0, 0.0, /* K=2,n=1,2,3 */ 0.0, 1.0, 0.0 /* K=3,n=1,2,3 */ }; double solution_xstart[3] = { 0.0, 0.0, 0.0 /* n=1,2,3 */ }; double noise_covariance[9] = { 0.05, 0.05, 0.01, 0.05, 0.05, 0.01, 0.05, 0.05, 0.01 }; std::ostringstream oss_name_of_file; /* prepare random generator */ PetscRandom rnd; TRY( PetscRandomCreate(PETSC_COMM_WORLD,&rnd) ); TRY( PetscRandomSetType(rnd,PETSCRAND) ); TRY( PetscRandomSetFromOptions(rnd) ); TRY( PetscRandomSetSeed(rnd,13) ); /* ---- GENERATE THE LARGEST PROBLEM ---- */ coutMaster << "- generating largest problem: T = " << T_max << std::endl; KmeansData<PetscVector> mydata(T_max,xdim); KmeansH1FEMModel<PetscVector> mymodel(mydata, xdim, solution_K, 0); mydata.set_model(mymodel); mydata.generate(solution_K, solution_theta, &solution_get_cluster_id, false); mydata.add_noise(noise_covariance); /* we will generate gamma0 vector for all K */ SimplexFeasibleSet_Local *feasibleset; Vec *gamma0s_Vec; /* array of vectors */ GeneralVector<PetscVector> *gamma0; /* temp general vector for projection */ gamma0s_Vec = (Vec *)(malloc(K_size*sizeof(Vec))); PetscViewer viewer_out; Vec data_Vec = mydata.get_datavector()->get_vector(); int ki; for(ki = 0; ki < K_size; ki++){ K = K_list[ki]; coutMaster << "- getting subgamma: K = " << K << std::endl; /* create feasible set - we will project */ feasibleset = new SimplexFeasibleSet_Local(T_max,K); ///* create general vector */ TRY( VecCreateSeq(PETSC_COMM_SELF, K*T_max, &(gamma0s_Vec[ki])) ); gamma0 = new GeneralVector<PetscVector>(gamma0s_Vec[ki]); /* generate random gamma */ TRY( VecSetRandom(gamma0s_Vec[ki], rnd) ); ///* project initial approximation to feasible set */ feasibleset->project(*gamma0); ///* destroy feasible set */ free(feasibleset); } /* ---- GET SUB PROBLEMS ---- */ Vec subdata_Vec; IS *subdata_ISs; subdata_ISs = (IS *)(malloc(xdim*sizeof(IS))); IS subdata_IS; Vec gamma0sum_Vec; IS *gamma0sub_ISs; IS gamma0sub_IS; int ti; for(ti=0;ti<T_size;ti++){ T = T_list[ti]; coutMaster << "- getting subproblem: T = " << T << std::endl; /* for every dimension of data create stride */ for(i=0;i<xdim;i++){ TRY( ISCreateStride(PETSC_COMM_WORLD, T, i*T_max, T_max/(double)(T), &(subdata_ISs[i])) ); } TRY( ISConcatenate(PETSC_COMM_WORLD, xdim, subdata_ISs, &subdata_IS) ); /* get subvector */ TRY( VecGetSubVector(data_Vec, subdata_IS, &subdata_Vec) ); /* save data */ oss_name_of_file << "results/data_kmeans_T" << T << ".bin"; coutMaster << "- saving: " << oss_name_of_file.str() << std::endl; TRY( PetscViewerBinaryOpen(PETSC_COMM_WORLD,oss_name_of_file.str().c_str(),FILE_MODE_WRITE,&viewer_out) ); TRY( VecView( subdata_Vec, viewer_out) ); TRY( PetscViewerDestroy(&viewer_out) ); oss_name_of_file.str(""); /* restore subvector */ TRY( VecRestoreSubVector(data_Vec, subdata_IS, &subdata_Vec) ); /* destroy indexsets */ for(i=0;i<xdim;i++){ TRY( ISDestroy(&(subdata_ISs[i])) ); } TRY( ISDestroy(&subdata_IS) ); /* subvectors from gamma0 */ for(ki = 0; ki < K_size; ki++){ K = K_list[K]; coutMaster << "- getting subgamma: K = " << K << std::endl; /* get subvectors from gamma0 */ gamma0sub_ISs = (IS*)malloc(K*sizeof(IS)); for(i=0;i<K;i++){ TRY( ISCreateStride(PETSC_COMM_WORLD, T, i*T_max, T_max/(double)(T), &(gamma0sub_ISs[i])) ); } TRY( ISConcatenate(PETSC_COMM_WORLD, K, gamma0sub_ISs, &gamma0sub_IS) ); /* get subvector */ TRY( VecGetSubVector(gamma0s_Vec[ki], gamma0sub_IS, &gamma0sum_Vec) ); /* save data */ oss_name_of_file << "results/gamma0_kmeans_T" << T << "K" << K << ".bin"; coutMaster << "- saving: " << oss_name_of_file.str() << std::endl; TRY( PetscViewerBinaryOpen(PETSC_COMM_WORLD,oss_name_of_file.str().c_str(),FILE_MODE_WRITE,&viewer_out) ); TRY( VecView( gamma0sum_Vec, viewer_out) ); TRY( PetscViewerDestroy(&viewer_out) ); oss_name_of_file.str(""); /* restore subvector */ TRY( VecRestoreSubVector(gamma0s_Vec[ki], gamma0sub_IS, &gamma0sum_Vec) ); for(i=0;i<K;i++){ TRY( ISDestroy(&(gamma0sub_ISs[i])) ); } free(gamma0sub_ISs); TRY( ISDestroy(&gamma0sub_IS) ); } } /* destroy the random generator */ TRY( PetscRandomDestroy(&rnd) ); /* say bye */ coutMaster << "- end program" << std::endl; logging.end(); Finalize(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* File Name: SMPGCInterface.cpp Author: Xin Cheng Descriptions: Created Time: Tue 06 Mar 2018 10:46:58 AM EST *********************************************************************/ #include "PD2SMPGCOrdering.h" #include <ctime> //clock using namespace std; using namespace ColPack; // ============================================================================ // Construction // ============================================================================ PD2SMPGCOrdering::PD2SMPGCOrdering(const string& graph_name, const string& fmt, double*iotime, const int side, const string& order, double* ordtime) : m_global_ordered_method(order), m_global_ordered_side(side), m_mt(5489u) { if( fmt!=FORMAT_MM) { printf("Error!PD2SMPGCOrdering only support MatrixMarket format (mm). \"%s\" with fmt \"%s\" is under construction... \n", graph_name.c_str(), fmt.c_str()); exit(1); } if(iotime) *(time_t*) iotime=-clock(); ReadMMBipartiteGraphCpp11(graph_name); BipartiteGraphInputOutput::ReadMMBipartiteGraphCpp11(graph_name); if(iotime) { *(time_t*)iotime+=clock(); *iotime= (*(time_t*)iotime)*1.0/CLOCKS_PER_SEC; } global_ordering(side, order, ordtime); } PD2SMPGCOrdering::~PD2SMPGCOrdering(){} // ============================================================================ // // ============================================================================ void PD2SMPGCOrdering::global_ordering(const int side, const string& order, double * ordtime){ if(ordtime) *(time_t*)ordtime=-clock(); if(order == ORDER_STR_NATURAL) global_natural_ordering(side); else if(order == ORDER_STR_RANDOM) global_random_ordering(side); else{ fprintf(stderr, "Err! PD2SMPGCOrdering::Unknow order %s\n",order.c_str()); exit(1); } if(ordtime){ *(time_t*)ordtime+=clock(); *ordtime =(double)(*(time_t*)ordtime)/CLOCKS_PER_SEC; } } // ============================================================================ // Natural is 0 1 2 3 4 5 6 7 ... // ============================================================================ void PD2SMPGCOrdering::global_natural_ordering(const int side){ m_global_ordered_side = side; m_global_ordered_method = ORDER_NATURAL; const int N = (side==L)?GetLeftVertexCount():GetRightVertexCount(); m_global_ordered_vertex.resize(N); for(int i=0; i<N; i++) m_global_ordered_vertex[i]=i; } // ============================================================================ // Random is shuffle to natural // ============================================================================ void PD2SMPGCOrdering::global_random_ordering(const int side) { m_global_ordered_side = side; m_global_ordered_method= ORDER_RANDOM; const int N = (side==L)?GetLeftVertexCount():GetRightVertexCount(); m_global_ordered_vertex.resize(N); for(int i=0; i<N; i++) m_global_ordered_vertex[i]=i; if(N<=1) return; for(int i=0; i<N-1; i++){ uniform_int_distribution<int> dist(i, N-1); swap(m_global_ordered_vertex[i], m_global_ordered_vertex[dist(m_mt)]); } } // ============================================================================ // local Natural is just sort ... // ============================================================================ void PD2SMPGCOrdering::local_natural_ordering(vector<int>&vtxs){ sort(vtxs.begin(), vtxs.end()); } // ============================================================================ // Random is shuffle to natural // ============================================================================ void PD2SMPGCOrdering::local_random_ordering(vector<int>&vtxs) { sort(vtxs.begin(), vtxs.end()); const int N=vtxs.size(); if(N<=1) return; for(int i=0; i<N-1; i++){ uniform_int_distribution<int> dist(i, N-1); swap(vtxs[i], vtxs[dist(m_mt)]); } } // ============================================================================ // Largest Degree First // ============================================================================ void PD2SMPGCOrdering::local_largest_degree_first_ordering(const int side, vector<int>& vtxs){ const int MaxDegreeP1 = (side==L)?(GetMaximumLeftVertexDegree()+1):(GetMaximumRightVertexDegree()+1); //maxDegree const vector<int>& verPtr = (side==L)?(GetLeftVertices()):(GetRightVertices()); vector<vector<int>> GroupedVertexDegree(MaxDegreeP1); for(const auto v : vtxs) { int deg = verPtr[v+1]-verPtr[v]; GroupedVertexDegree[deg].push_back(v); } vtxs.clear(); for(int d=MaxDegreeP1-1, it=MaxDegreeP1; it!=0; it--, d--){ vtxs.insert(vtxs.end(), GroupedVertexDegree[d].begin(), GroupedVertexDegree[d].end()); } GroupedVertexDegree.clear(); } // ============================================================================ // Largest Degree First // ============================================================================ void PD2SMPGCOrdering::local_largest_degree_first_ordering(const int side, vector<int>& vtxs, const int beg, const int end){ const int MaxDegreeP1 = (side==L)?(GetMaximumLeftVertexDegree()+1):(GetMaximumRightVertexDegree()+1); //maxDegree const vector<int>& verPtr = (side==L)?(GetLeftVertices()):(GetRightVertices()); vector<vector<int>> GroupedVertexDegree(MaxDegreeP1); for(auto i=beg; i<end; i++){ auto v = vtxs[i]; int deg = verPtr[v+1]-verPtr[v]; GroupedVertexDegree[deg].push_back(v); } int pos=beg; for(int d=MaxDegreeP1-1, it=MaxDegreeP1; it!=0; it--, d--){ for(auto v : GroupedVertexDegree[d]){ vtxs[pos++]=v; } } GroupedVertexDegree.clear(); } <commit_msg>fixing bug that read files twice<commit_after>/************************************************************************* File Name: SMPGCInterface.cpp Author: Xin Cheng Descriptions: Created Time: Tue 06 Mar 2018 10:46:58 AM EST *********************************************************************/ #include "PD2SMPGCOrdering.h" #include <ctime> //clock using namespace std; using namespace ColPack; // ============================================================================ // Construction // ============================================================================ PD2SMPGCOrdering::PD2SMPGCOrdering(const string& graph_name, const string& fmt, double*iotime, const int side, const string& order, double* ordtime) : m_global_ordered_method(order), m_global_ordered_side(side), m_mt(5489u) { if( fmt!=FORMAT_MM) { printf("Error!PD2SMPGCOrdering only support MatrixMarket format (mm). \"%s\" with fmt \"%s\" is under construction... \n", graph_name.c_str(), fmt.c_str()); exit(1); } if(iotime) *(time_t*) iotime=-clock(); ReadMMBipartiteGraphCpp11(graph_name); if(iotime) { *(time_t*)iotime+=clock(); *iotime= (*(time_t*)iotime)*1.0/CLOCKS_PER_SEC; } global_ordering(side, order, ordtime); } PD2SMPGCOrdering::~PD2SMPGCOrdering(){} // ============================================================================ // // ============================================================================ void PD2SMPGCOrdering::global_ordering(const int side, const string& order, double * ordtime){ if(ordtime) *(time_t*)ordtime=-clock(); if(order == ORDER_STR_NATURAL) global_natural_ordering(side); else if(order == ORDER_STR_RANDOM) global_random_ordering(side); else{ fprintf(stderr, "Err! PD2SMPGCOrdering::Unknow order %s\n",order.c_str()); exit(1); } if(ordtime){ *(time_t*)ordtime+=clock(); *ordtime =(double)(*(time_t*)ordtime)/CLOCKS_PER_SEC; } } // ============================================================================ // Natural is 0 1 2 3 4 5 6 7 ... // ============================================================================ void PD2SMPGCOrdering::global_natural_ordering(const int side){ m_global_ordered_side = side; m_global_ordered_method = ORDER_NATURAL; const int N = (side==L)?GetLeftVertexCount():GetRightVertexCount(); m_global_ordered_vertex.resize(N); for(int i=0; i<N; i++) m_global_ordered_vertex[i]=i; } // ============================================================================ // Random is shuffle to natural // ============================================================================ void PD2SMPGCOrdering::global_random_ordering(const int side) { m_global_ordered_side = side; m_global_ordered_method= ORDER_RANDOM; const int N = (side==L)?GetLeftVertexCount():GetRightVertexCount(); m_global_ordered_vertex.resize(N); for(int i=0; i<N; i++) m_global_ordered_vertex[i]=i; if(N<=1) return; for(int i=0; i<N-1; i++){ uniform_int_distribution<int> dist(i, N-1); swap(m_global_ordered_vertex[i], m_global_ordered_vertex[dist(m_mt)]); } } // ============================================================================ // local Natural is just sort ... // ============================================================================ void PD2SMPGCOrdering::local_natural_ordering(vector<int>&vtxs){ sort(vtxs.begin(), vtxs.end()); } // ============================================================================ // Random is shuffle to natural // ============================================================================ void PD2SMPGCOrdering::local_random_ordering(vector<int>&vtxs) { sort(vtxs.begin(), vtxs.end()); const int N=vtxs.size(); if(N<=1) return; for(int i=0; i<N-1; i++){ uniform_int_distribution<int> dist(i, N-1); swap(vtxs[i], vtxs[dist(m_mt)]); } } // ============================================================================ // Largest Degree First // ============================================================================ void PD2SMPGCOrdering::local_largest_degree_first_ordering(const int side, vector<int>& vtxs){ const int MaxDegreeP1 = (side==L)?(GetMaximumLeftVertexDegree()+1):(GetMaximumRightVertexDegree()+1); //maxDegree const vector<int>& verPtr = (side==L)?(GetLeftVertices()):(GetRightVertices()); vector<vector<int>> GroupedVertexDegree(MaxDegreeP1); for(const auto v : vtxs) { int deg = verPtr[v+1]-verPtr[v]; GroupedVertexDegree[deg].push_back(v); } vtxs.clear(); for(int d=MaxDegreeP1-1, it=MaxDegreeP1; it!=0; it--, d--){ vtxs.insert(vtxs.end(), GroupedVertexDegree[d].begin(), GroupedVertexDegree[d].end()); } GroupedVertexDegree.clear(); } // ============================================================================ // Largest Degree First // ============================================================================ void PD2SMPGCOrdering::local_largest_degree_first_ordering(const int side, vector<int>& vtxs, const int beg, const int end){ const int MaxDegreeP1 = (side==L)?(GetMaximumLeftVertexDegree()+1):(GetMaximumRightVertexDegree()+1); //maxDegree const vector<int>& verPtr = (side==L)?(GetLeftVertices()):(GetRightVertices()); vector<vector<int>> GroupedVertexDegree(MaxDegreeP1); for(auto i=beg; i<end; i++){ auto v = vtxs[i]; int deg = verPtr[v+1]-verPtr[v]; GroupedVertexDegree[deg].push_back(v); } int pos=beg; for(int d=MaxDegreeP1-1, it=MaxDegreeP1; it!=0; it--, d--){ for(auto v : GroupedVertexDegree[d]){ vtxs[pos++]=v; } } GroupedVertexDegree.clear(); } <|endoftext|>
<commit_before> #include "drake/examples/kuka_iiwa_arm/iiwa_simulation.h" #include "drake/examples/kuka_iiwa_arm/iiwa_status.h" #include "drake/Path.h" #include "drake/systems/LCMSystem.h" #include "drake/systems/plants/BotVisualizer.h" #include "drake/systems/plants/RigidBodyTree.h" #include "lcmtypes/drake/lcmt_iiwa_status.hpp" namespace drake { namespace examples { namespace kuka_iiwa_arm { namespace { // This class exists to keep the LCM messages which are passing // through BotVisualizer from being sent back out via LCM again. template <template <typename> class Vector> class SinkSystem { public: template <typename ScalarType> using StateVector = Drake::NullVector<ScalarType>; template <typename ScalarType> using InputVector = Vector<ScalarType>; template <typename ScalarType> using OutputVector = Drake::NullVector<ScalarType>; SinkSystem() {} template <typename ScalarType> StateVector<ScalarType> dynamics(const double &t, const StateVector<ScalarType> &x, const InputVector<ScalarType> &u) const { return StateVector<ScalarType>(); } template <typename ScalarType> OutputVector<ScalarType> output(const double &t, const StateVector<ScalarType> &x, const InputVector<ScalarType> &u) const { return OutputVector<ScalarType>(); } bool isTimeVarying() const { return false; } }; int do_main(int argc, const char* argv[]) { std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>(); const std::shared_ptr<RigidBodyTree> tree = CreateKukaIiwaSystem()->getRigidBodyTree(); auto visualizer = std::make_shared<Drake::BotVisualizer<IiwaStatus>>(lcm, tree); auto sink = std::make_shared<SinkSystem<IiwaStatus>>(); auto sys = Drake::cascade(visualizer, sink); Drake::runLCM(sys, lcm, 0, 1e9); return 0; } } // namespace } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake int main(int argc, const char* argv[]) { return drake::examples::kuka_iiwa_arm::do_main(argc, argv); } <commit_msg>Renamed method do_main() to be DoMain() to conform to style guide.<commit_after> #include "drake/examples/kuka_iiwa_arm/iiwa_simulation.h" #include "drake/examples/kuka_iiwa_arm/iiwa_status.h" #include "drake/Path.h" #include "drake/systems/LCMSystem.h" #include "drake/systems/plants/BotVisualizer.h" #include "drake/systems/plants/RigidBodyTree.h" #include "lcmtypes/drake/lcmt_iiwa_status.hpp" namespace drake { namespace examples { namespace kuka_iiwa_arm { namespace { // This class exists to keep the LCM messages which are passing // through BotVisualizer from being sent back out via LCM again. template <template <typename> class Vector> class SinkSystem { public: template <typename ScalarType> using StateVector = Drake::NullVector<ScalarType>; template <typename ScalarType> using InputVector = Vector<ScalarType>; template <typename ScalarType> using OutputVector = Drake::NullVector<ScalarType>; SinkSystem() {} template <typename ScalarType> StateVector<ScalarType> dynamics(const double &t, const StateVector<ScalarType> &x, const InputVector<ScalarType> &u) const { return StateVector<ScalarType>(); } template <typename ScalarType> OutputVector<ScalarType> output(const double &t, const StateVector<ScalarType> &x, const InputVector<ScalarType> &u) const { return OutputVector<ScalarType>(); } bool isTimeVarying() const { return false; } }; int DoMain(int argc, const char* argv[]) { std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>(); const std::shared_ptr<RigidBodyTree> tree = CreateKukaIiwaSystem()->getRigidBodyTree(); auto visualizer = std::make_shared<Drake::BotVisualizer<IiwaStatus>>(lcm, tree); auto sink = std::make_shared<SinkSystem<IiwaStatus>>(); auto sys = Drake::cascade(visualizer, sink); Drake::runLCM(sys, lcm, 0, 1e9); return 0; } } // namespace } // namespace kuka_iiwa_arm } // namespace examples } // namespace drake int main(int argc, const char* argv[]) { return drake::examples::kuka_iiwa_arm::DoMain(argc, argv); } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <GPIOClass.cpp> using namespace std; int main (void) { string inputstate; GPIOClass* gpio4 = new GPIOClass("4"); //create new GPIO object to be attached to GPIO4 GPIOClass* gpio17 = new GPIOClass("17"); //create new GPIO object to be attached to GPIO17 gpio4->export_gpio(); //export GPIO4 gpio17->export_gpio(); //export GPIO17 cout << " GPIO pins exported" << endl; gpio17->setdir_gpio("in"); //GPIO4 set to output gpio4->setdir_gpio("out"); // GPIO17 set to input cout << " Set GPIO pin directions" << endl; while(1) { usleep(500000); // wait for 0.5 seconds gpio17->getval_gpio(inputstate); //read state of GPIO17 input pin cout << "Current input pin state is " << inputstate <<endl; if(inputstate == "0") // if input pin is at state "0" i.e. button pressed { cout << "input pin state is "Pressed ".n Will check input pin state again in 20ms "<<endl; usleep(20000); cout << "Checking again ....." << endl; gpio17->getval_gpio(inputstate); // checking again to ensure that state "0" is due to button press and not noise if(inputstate == "0") { cout << "input pin state is definitely "Pressed". Turning LED ON" <<endl; gpio4->setval_gpio("1"); // turn LED ON cout << " Waiting until pin is unpressed....." << endl; while (inputstate == "0"){ gpio17->getval_gpio(inputstate); }; cout << "pin is unpressed" << endl; } else cout << "input pin state is definitely "UnPressed". That was just noise." <<endl; } gpio4->setval_gpio("0"); } cout << "Exiting....." << endl; return 0; <commit_msg>Update TestGPIO.cpp<commit_after>#include <iostream> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <GPIOClass.h> using namespace std; int main (void) { string inputstate; GPIOClass* gpio4 = new GPIOClass("4"); //create new GPIO object to be attached to GPIO4 GPIOClass* gpio17 = new GPIOClass("17"); //create new GPIO object to be attached to GPIO17 gpio4->export_gpio(); //export GPIO4 gpio17->export_gpio(); //export GPIO17 cout << " GPIO pins exported" << endl; gpio17->setdir_gpio("in"); //GPIO4 set to output gpio4->setdir_gpio("out"); // GPIO17 set to input cout << " Set GPIO pin directions" << endl; while(1) { usleep(500000); // wait for 0.5 seconds gpio17->getval_gpio(inputstate); //read state of GPIO17 input pin cout << "Current input pin state is " << inputstate <<endl; if(inputstate == "0") // if input pin is at state "0" i.e. button pressed { cout << "input pin state is "Pressed ".n Will check input pin state again in 20ms "<<endl; usleep(20000); cout << "Checking again ....." << endl; gpio17->getval_gpio(inputstate); // checking again to ensure that state "0" is due to button press and not noise if(inputstate == "0") { cout << "input pin state is definitely "Pressed". Turning LED ON" <<endl; gpio4->setval_gpio("1"); // turn LED ON cout << " Waiting until pin is unpressed....." << endl; while (inputstate == "0"){ gpio17->getval_gpio(inputstate); }; cout << "pin is unpressed" << endl; } else cout << "input pin state is definitely "UnPressed". That was just noise." <<endl; } gpio4->setval_gpio("0"); } cout << "Exiting....." << endl; return 0; <|endoftext|>
<commit_before>#pragma once #include <cmath> #include <limits> #include "float.hh" // ---------------------------------------------------------------------- namespace _acmacs_base_internal { template <char Tag> class SizeScale { public: inline SizeScale() : mValue(0) {} inline explicit SizeScale(double aValue) : mValue(aValue) {} // inline SizeScale(const SizeScale& a) = default; inline bool operator==(SizeScale<Tag> a) const { return float_equal(mValue, a.mValue); } inline bool operator<(SizeScale<Tag> a) const { return mValue < a.mValue; } inline SizeScale& operator = (double aValue) { mValue = aValue; return *this; } inline double value() const { return mValue; } inline SizeScale operator / (double a) const { return SizeScale{mValue / a}; } inline SizeScale operator * (double a) const { return SizeScale{mValue * a}; } inline SizeScale& operator *= (double a) { mValue *= a; return *this; } inline SizeScale operator - () const { return SizeScale{- mValue}; } inline SizeScale operator - (SizeScale<Tag> a) const { return SizeScale{mValue - a.mValue}; } inline SizeScale operator + (SizeScale<Tag> a) const { return SizeScale{mValue + a.mValue}; } inline SizeScale& operator += (SizeScale<Tag> a) { mValue += a.mValue; return *this; } inline bool empty() const { return std::isnan(mValue); } static SizeScale make_empty() { return SizeScale(std::numeric_limits<double>::quiet_NaN()); } private: double mValue; }; } using Pixels = _acmacs_base_internal::SizeScale<'P'>; // size in pixels, indepenent from the surface internal coordinate system using Scaled = _acmacs_base_internal::SizeScale<'S'>; // size in the surface internal coordinate system // ---------------------------------------------------------------------- using Aspect = _acmacs_base_internal::SizeScale<'A'>; using Rotation = _acmacs_base_internal::SizeScale<'R'>; #include "acmacs-base/global-constructors-push.hh" const Rotation NoRotation{0.0}; const Aspect AspectNormal{1.0}; #include "acmacs-base/diagnostics-pop.hh" inline Rotation RotationDegrees(double aAngle) { return Rotation{aAngle * M_PI / 180.0}; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg><<(ostream, Pixels, Scaled, Aspect, Rotation)<commit_after>#pragma once #include <cmath> #include <limits> #include "float.hh" // ---------------------------------------------------------------------- namespace _acmacs_base_internal { template <char Tag> class SizeScale { public: inline SizeScale() : mValue(0) {} inline explicit SizeScale(double aValue) : mValue(aValue) {} // inline SizeScale(const SizeScale& a) = default; inline bool operator==(SizeScale<Tag> a) const { return float_equal(mValue, a.mValue); } inline bool operator<(SizeScale<Tag> a) const { return mValue < a.mValue; } inline SizeScale& operator = (double aValue) { mValue = aValue; return *this; } inline double value() const { return mValue; } inline SizeScale operator / (double a) const { return SizeScale{mValue / a}; } inline SizeScale operator * (double a) const { return SizeScale{mValue * a}; } inline SizeScale& operator *= (double a) { mValue *= a; return *this; } inline SizeScale operator - () const { return SizeScale{- mValue}; } inline SizeScale operator - (SizeScale<Tag> a) const { return SizeScale{mValue - a.mValue}; } inline SizeScale operator + (SizeScale<Tag> a) const { return SizeScale{mValue + a.mValue}; } inline SizeScale& operator += (SizeScale<Tag> a) { mValue += a.mValue; return *this; } inline bool empty() const { return std::isnan(mValue); } static SizeScale make_empty() { return SizeScale(std::numeric_limits<double>::quiet_NaN()); } private: double mValue; }; } using Pixels = _acmacs_base_internal::SizeScale<'P'>; // size in pixels, indepenent from the surface internal coordinate system using Scaled = _acmacs_base_internal::SizeScale<'S'>; // size in the surface internal coordinate system // ---------------------------------------------------------------------- using Aspect = _acmacs_base_internal::SizeScale<'A'>; using Rotation = _acmacs_base_internal::SizeScale<'R'>; #include "acmacs-base/global-constructors-push.hh" const Rotation NoRotation{0.0}; const Aspect AspectNormal{1.0}; #include "acmacs-base/diagnostics-pop.hh" inline Rotation RotationDegrees(double aAngle) { return Rotation{aAngle * M_PI / 180.0}; } // ---------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream& out, Pixels aPixels) { return out << "Pixels{" << aPixels.value() << '}'; } inline std::ostream& operator<<(std::ostream& out, Scaled aScaled) { return out << "Scaled{" << aScaled.value() << '}'; } inline std::ostream& operator<<(std::ostream& out, Aspect aAspect) { if (aAspect == AspectNormal) return out << "AspectNormal"; else return out << "Aspect{" << aAspect.value() << '}'; } inline std::ostream& operator<<(std::ostream& out, Rotation aRotation) { if (aRotation == NoRotation) return out << "NoRotation"; else return out << "Rotation{" << aRotation.value() << '}'; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH #define DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH #include <boost/numeric/conversion/cast.hpp> #include <dune/gdt/playground/localevaluation/swipdg.hh> #include <dune/gdt/operators/fluxreconstruction.hh> namespace Dune { namespace GDT { namespace Operators { template< class GridViewType, class DiffusionFactorType, class DiffusionTensorType > class DiffusiveFluxReconstruction { static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!"); static_assert(std::is_base_of< Stuff::IsLocalizableFunction, DiffusionFactorType >::value, "DiffusionFactorType has to be tagged as Stuff::IsLocalizableFunction!"); static_assert(std::is_base_of< Stuff::IsLocalizableFunction, DiffusionTensorType >::value, "DiffusionTensorType has to be tagged as Stuff::IsLocalizableFunction!"); public: typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; typedef typename DiffusionFactorType::RangeFieldType FieldType; typedef typename DiffusionFactorType::DomainType DomainType; private: static_assert(dimDomain == 2, "Not implemented!"); public: DiffusiveFluxReconstruction(const GridViewType& grid_view, const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor, const size_t over_integrate = 0) : grid_view_(grid_view) , diffusion_factor_(diffusion_factor) , diffusion_tensor_(diffusion_tensor) , over_integrate_(over_integrate) {} template< class GV, class V > void apply(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1 >& source, DiscreteFunction< Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >, V >& range) const { const auto& rtn0_space = range.space(); auto& range_vector = range.vector(); const FieldType infinity = std::numeric_limits< FieldType >::infinity(); for (size_t ii = 0; ii < range_vector.size(); ++ii) range_vector[ii] = infinity; const LocalEvaluation::SWIPDG::Inner< DiffusionFactorType, DiffusionTensorType > inner_evaluation(diffusion_factor_, diffusion_tensor_); const LocalEvaluation::SWIPDG::BoundaryLHS< DiffusionFactorType, DiffusionTensorType > boundary_evaluation(diffusion_factor_, diffusion_tensor_); const Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, FieldType, 1 > constant_one(1); DomainType normal(0); DomainType xx_entity(0); DynamicMatrix< FieldType > tmp_matrix(1, 1, 0); DynamicMatrix< FieldType > tmp_matrix_en_en(1, 1, 0); DynamicMatrix< FieldType > tmp_matrix_en_ne(1, 1, 0); std::vector< typename Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType > basis_values(rtn0_space.mapper().maxNumDofs(), typename Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType(0)); // walk the grid const auto entity_it_end = grid_view_.template end< 0 >(); for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity); const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity); assert(global_DoF_indices.size() == local_DoF_indices.size()); const auto local_diffusion_factor = diffusion_factor_.local_function(entity); const auto local_diffusion_tensor = diffusion_tensor_.local_function(entity); const auto local_source = source.local_function(entity); const auto local_basis = rtn0_space.base_function_set(entity); const auto local_constant_one = constant_one.local_function(entity); // walk the intersections const auto intersection_it_end = grid_view_.iend(entity); for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; if (intersection.neighbor() && !intersection.boundary()) { const auto neighbor_ptr = intersection.outside(); const auto& neighbor = *neighbor_ptr; if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) { const auto local_diffusion_factor_neighbor = diffusion_factor_.local_function(neighbor); const auto local_diffusion_tensor_neighbor = diffusion_tensor_.local_function(neighbor); const auto local_source_neighbor = source.local_function(neighbor); const auto local_constant_one_neighbor = constant_one.local_function(neighbor); const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = inner_evaluation.order(*local_diffusion_factor, *local_diffusion_tensor, *local_diffusion_factor_neighbor, *local_diffusion_tensor_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule( intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto& xx_intersection = quadrature_it->position(); xx_entity = intersection.geometryInInside().global(xx_intersection); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; tmp_matrix_en_en *= 0.0; tmp_matrix_en_ne *= 0.0; inner_evaluation.evaluate(*local_diffusion_factor, *local_diffusion_tensor, *local_diffusion_factor_neighbor, *local_diffusion_tensor_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor, intersection, xx_intersection, tmp_matrix_en_en, // <- we are interested in this one tmp_matrix, tmp_matrix_en_ne, // <- and this one tmp_matrix); // compute integrals assert(tmp_matrix_en_en.rows() >= 1); assert(tmp_matrix_en_en.cols() >= 1); assert(tmp_matrix_en_ne.rows() >= 1); assert(tmp_matrix_en_ne.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]); } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; // and make sure we are the first to do so assert(!(range_vector[global_DoF_index] < infinity)); range_vector[global_DoF_index] = rhs / lhs; } } else if (intersection.boundary() && !intersection.neighbor()) { const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = boundary_evaluation.order(*local_diffusion_factor, *local_diffusion_tensor, *local_source, *local_constant_one); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule( intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx_intersection = quadrature_it->position(); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); xx_entity = intersection.geometryInInside().global(xx_intersection); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; boundary_evaluation.evaluate(*local_diffusion_factor, *local_diffusion_tensor, *local_constant_one, *local_source, intersection, xx_intersection, tmp_matrix); // compute integrals assert(tmp_matrix.rows() >= 1); assert(tmp_matrix.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * tmp_matrix[0][0]; } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; assert(!(range_vector[global_DoF_index] < infinity)); // and make sure we are the first to do so range_vector[global_DoF_index] = rhs / lhs; } else DUNE_THROW(Stuff::Exceptions::internal_error, "Unknown intersection type!"); } // walk the intersections } // walk the grid } // ... apply(...) private: const GridViewType& grid_view_; const DiffusionFactorType& diffusion_factor_; const DiffusionTensorType& diffusion_tensor_; const size_t over_integrate_; }; // class DiffusiveFluxReconstruction } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH <commit_msg>[operators.fluxreconstruction] add make_diffusive_flux_reconstruction()<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH #define DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH #include <boost/numeric/conversion/cast.hpp> #include <dune/gdt/playground/localevaluation/swipdg.hh> #include <dune/gdt/operators/fluxreconstruction.hh> namespace Dune { namespace GDT { namespace Operators { template< class GridViewType, class DiffusionFactorType, class DiffusionTensorType > class DiffusiveFluxReconstruction { static_assert(GridViewType::dimension == 2, "Only implemented for dimDomain 2 at the moment!"); static_assert(std::is_base_of< Stuff::IsLocalizableFunction, DiffusionFactorType >::value, "DiffusionFactorType has to be tagged as Stuff::IsLocalizableFunction!"); static_assert(std::is_base_of< Stuff::IsLocalizableFunction, DiffusionTensorType >::value, "DiffusionTensorType has to be tagged as Stuff::IsLocalizableFunction!"); public: typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; typedef typename DiffusionFactorType::RangeFieldType FieldType; typedef typename DiffusionFactorType::DomainType DomainType; private: static_assert(dimDomain == 2, "Not implemented!"); public: DiffusiveFluxReconstruction(const GridViewType& grid_view, const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor, const size_t over_integrate = 0) : grid_view_(grid_view) , diffusion_factor_(diffusion_factor) , diffusion_tensor_(diffusion_tensor) , over_integrate_(over_integrate) {} template< class GV, class V > void apply(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, FieldType, 1 >& source, DiscreteFunction< Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >, V >& range) const { const auto& rtn0_space = range.space(); auto& range_vector = range.vector(); const FieldType infinity = std::numeric_limits< FieldType >::infinity(); for (size_t ii = 0; ii < range_vector.size(); ++ii) range_vector[ii] = infinity; const LocalEvaluation::SWIPDG::Inner< DiffusionFactorType, DiffusionTensorType > inner_evaluation(diffusion_factor_, diffusion_tensor_); const LocalEvaluation::SWIPDG::BoundaryLHS< DiffusionFactorType, DiffusionTensorType > boundary_evaluation(diffusion_factor_, diffusion_tensor_); const Stuff::Functions::Constant< EntityType, DomainFieldType, dimDomain, FieldType, 1 > constant_one(1); DomainType normal(0); DomainType xx_entity(0); DynamicMatrix< FieldType > tmp_matrix(1, 1, 0); DynamicMatrix< FieldType > tmp_matrix_en_en(1, 1, 0); DynamicMatrix< FieldType > tmp_matrix_en_ne(1, 1, 0); std::vector< typename Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType > basis_values(rtn0_space.mapper().maxNumDofs(), typename Spaces::RaviartThomas::PdelabBased< GV, 0, FieldType, dimDomain >::BaseFunctionSetType::RangeType(0)); // walk the grid const auto entity_it_end = grid_view_.template end< 0 >(); for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; const auto local_DoF_indices = rtn0_space.local_DoF_indices(entity); const auto global_DoF_indices = rtn0_space.mapper().globalIndices(entity); assert(global_DoF_indices.size() == local_DoF_indices.size()); const auto local_diffusion_factor = diffusion_factor_.local_function(entity); const auto local_diffusion_tensor = diffusion_tensor_.local_function(entity); const auto local_source = source.local_function(entity); const auto local_basis = rtn0_space.base_function_set(entity); const auto local_constant_one = constant_one.local_function(entity); // walk the intersections const auto intersection_it_end = grid_view_.iend(entity); for (auto intersection_it = grid_view_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { const auto& intersection = *intersection_it; if (intersection.neighbor() && !intersection.boundary()) { const auto neighbor_ptr = intersection.outside(); const auto& neighbor = *neighbor_ptr; if (grid_view_.indexSet().index(entity) < grid_view_.indexSet().index(neighbor)) { const auto local_diffusion_factor_neighbor = diffusion_factor_.local_function(neighbor); const auto local_diffusion_tensor_neighbor = diffusion_tensor_.local_function(neighbor); const auto local_source_neighbor = source.local_function(neighbor); const auto local_constant_one_neighbor = constant_one.local_function(neighbor); const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = inner_evaluation.order(*local_diffusion_factor, *local_diffusion_tensor, *local_diffusion_factor_neighbor, *local_diffusion_tensor_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule( intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto& xx_intersection = quadrature_it->position(); xx_entity = intersection.geometryInInside().global(xx_intersection); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; tmp_matrix_en_en *= 0.0; tmp_matrix_en_ne *= 0.0; inner_evaluation.evaluate(*local_diffusion_factor, *local_diffusion_tensor, *local_diffusion_factor_neighbor, *local_diffusion_tensor_neighbor, *local_constant_one, *local_source, *local_constant_one_neighbor, *local_source_neighbor, intersection, xx_intersection, tmp_matrix_en_en, // <- we are interested in this one tmp_matrix, tmp_matrix_en_ne, // <- and this one tmp_matrix); // compute integrals assert(tmp_matrix_en_en.rows() >= 1); assert(tmp_matrix_en_en.cols() >= 1); assert(tmp_matrix_en_ne.rows() >= 1); assert(tmp_matrix_en_ne.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * (tmp_matrix_en_en[0][0] + tmp_matrix_en_ne[0][0]); } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; // and make sure we are the first to do so assert(!(range_vector[global_DoF_index] < infinity)); range_vector[global_DoF_index] = rhs / lhs; } } else if (intersection.boundary() && !intersection.neighbor()) { const size_t local_intersection_index = intersection.indexInInside(); const size_t local_DoF_index = local_DoF_indices[local_intersection_index]; // do a face quadrature FieldType lhs = 0; FieldType rhs = 0; const size_t integrand_order = boundary_evaluation.order(*local_diffusion_factor, *local_diffusion_tensor, *local_source, *local_constant_one); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain - 1 >::rule( intersection.type(), boost::numeric_cast< int >(integrand_order + over_integrate_)); const auto quadrature_it_end = quadrature.end(); for (auto quadrature_it = quadrature.begin(); quadrature_it != quadrature_it_end; ++quadrature_it) { const auto xx_intersection = quadrature_it->position(); normal = intersection.unitOuterNormal(xx_intersection); const FieldType integration_factor = intersection.geometry().integrationElement(xx_intersection); const FieldType weigth = quadrature_it->weight(); xx_entity = intersection.geometryInInside().global(xx_intersection); // evalaute local_basis.evaluate(xx_entity, basis_values); const auto& basis_value = basis_values[local_DoF_index]; tmp_matrix *= 0.0; boundary_evaluation.evaluate(*local_diffusion_factor, *local_diffusion_tensor, *local_constant_one, *local_source, intersection, xx_intersection, tmp_matrix); // compute integrals assert(tmp_matrix.rows() >= 1); assert(tmp_matrix.cols() >= 1); lhs += integration_factor * weigth * (basis_value * normal); rhs += integration_factor * weigth * tmp_matrix[0][0]; } // do a face quadrature // set DoF const size_t global_DoF_index = global_DoF_indices[local_DoF_index]; assert(!(range_vector[global_DoF_index] < infinity)); // and make sure we are the first to do so range_vector[global_DoF_index] = rhs / lhs; } else DUNE_THROW(Stuff::Exceptions::internal_error, "Unknown intersection type!"); } // walk the intersections } // walk the grid } // ... apply(...) private: const GridViewType& grid_view_; const DiffusionFactorType& diffusion_factor_; const DiffusionTensorType& diffusion_tensor_; const size_t over_integrate_; }; // class DiffusiveFluxReconstruction template< class GV, class DF, class DT > DiffusiveFluxReconstruction< GV, DF, DT > make_diffusive_flux_reconstruction(const GV& grid_view, const DF& diffusion_factor, const DT& diffusion_tensor, const size_t over_integrate = 0) { return DiffusiveFluxReconstruction< GV, DF, DT >(grid_view, diffusion_factor, diffusion_tensor, over_integrate); } } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PLAYGROUND_OPERATORS_RECONSTRUCTIONS_HH <|endoftext|>
<commit_before>/** * \file MouseController.cpp * * \author Volker Ahlers\n * volker.ahlers@hs-hannover.de */ /* * Copyright 2014 Volker Ahlers * * 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 <iostream> #include "scg_glew.h" #include <GLFW/glfw3.h> #include "Camera.h" #include "MouseController.h" #include "scg_glm.h" #include "ViewState.h" namespace scg { MouseController::MouseController(CameraSP camera) : CameraController(camera) { moveVelocity_ = 0.01f; rotateVelocity_ = 0.05f; std::cout << "Mouse camera control enabled" << std::endl; std::cout << "- left button (fly/examine): move forward/backward, rotate around yaw/azimuth axis" << std::endl; std::cout << " + alt: dolly in/out (relative to center point), rotate around yaw/azimuth axis" << std::endl; std::cout << "- right button (fly/examine): rotate around roll and pitch/elevation axes" << std::endl; std::cout << " + alt: rotate around yaw/azimuth and pitch/elevation axes" << std::endl; std::cout << "- middle button: toggle fly/examine mode" << std::endl; std::cout << std::endl; } MouseController::~MouseController() { } MouseControllerSP MouseController::create(CameraSP camera) { return std::make_shared<MouseController>(camera); } void MouseController::checkInput(ViewState* viewState) { // initialize controller state static bool toggleMouseButton(false); GLFWwindow* window = viewState->getWindow(); double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); static double mouseXOld(mouseX), mouseYOld(mouseY); if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { // left mouse button pressed: camera movement and rotation glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwGetCursorPos(window, &mouseX, &mouseY); glfwSetCursorPos(window, mouseXOld, mouseYOld); // move forward/backward or dolly if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS) { camera_->dolly(-moveVelocity_ * static_cast<GLfloat>(mouseY - mouseYOld)); } else { camera_->translate(glm::vec3(0.0f, 0.0f, moveVelocity_ * (mouseY - mouseYOld))); } // rotate around yaw/azimuth axis if (isFlyMode_) { camera_->rotateYaw(-rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } else { // examine mode camera_->rotateAzimuth(rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } toggleMouseButton = true; } else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) { // right mouse button pressed: camera rotation glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwGetCursorPos(window, &mouseX, &mouseY); glfwSetCursorPos(window, mouseXOld, mouseYOld); // rotate around roll or yaw/azimuth axis if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS) { if (isFlyMode_) { camera_->rotateYaw(-rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } else { // examine mode camera_->rotateAzimuth(rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } } else { camera_->rotateRoll(rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } // rotate around pitch/elevation axis if (isFlyMode_) { camera_->rotatePitch(rotateVelocity_ * static_cast<GLfloat>(mouseY - mouseYOld)); } else { // examine mode camera_->rotateElevation(-rotateVelocity_ * static_cast<GLfloat>(mouseY - mouseYOld)); } toggleMouseButton = true; } else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS) { // middle mouse button pressed: toggle fly/examine mode if (!toggleMouseButton) { static bool prevDrawCenterMode = false; isFlyMode_ = !isFlyMode_; if (isFlyMode_) { // fly mode: restore previous draw center point mode camera_->setDrawCenter(prevDrawCenterMode); } else { // examine mode: draw center point, saving current mode prevDrawCenterMode = camera_->isDrawCenter(); camera_->setDrawCenter(true); } } toggleMouseButton = true; } else { // no mouse button pressed: restore mouse cursor glfwGetCursorPos(window, &mouseXOld, &mouseYOld); if (viewState->isMouseCursorVisible()) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); glfwSetCursorPos(window, mouseXOld, mouseYOld); } toggleMouseButton = false; } } } /* namespace scg */ <commit_msg>Fix bug in restoring of mouse position.<commit_after>/** * \file MouseController.cpp * * \author Volker Ahlers\n * volker.ahlers@hs-hannover.de */ /* * Copyright 2014-2019 Volker Ahlers * * 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 <iostream> #include "scg_glew.h" #include <GLFW/glfw3.h> #include "Camera.h" #include "MouseController.h" #include "scg_glm.h" #include "ViewState.h" namespace scg { MouseController::MouseController(CameraSP camera) : CameraController(camera) { moveVelocity_ = 0.01f; rotateVelocity_ = 0.05f; std::cout << "Mouse camera control enabled" << std::endl; std::cout << "- left button (fly/examine): move forward/backward, rotate around yaw/azimuth axis" << std::endl; std::cout << " + alt: dolly in/out (relative to center point), rotate around yaw/azimuth axis" << std::endl; std::cout << "- right button (fly/examine): rotate around roll and pitch/elevation axes" << std::endl; std::cout << " + alt: rotate around yaw/azimuth and pitch/elevation axes" << std::endl; std::cout << "- middle button or right button + cmd: toggle fly/examine mode" << std::endl; std::cout << std::endl; } MouseController::~MouseController() { } MouseControllerSP MouseController::create(CameraSP camera) { return std::make_shared<MouseController>(camera); } void MouseController::checkInput(ViewState* viewState) { // initialize controller state static bool toggleMouseButton(false); GLFWwindow* window = viewState->getWindow(); double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); static double mouseXOld(mouseX), mouseYOld(mouseY); if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { // left mouse button pressed: camera movement and rotation glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwGetCursorPos(window, &mouseX, &mouseY); glfwSetCursorPos(window, mouseXOld, mouseYOld); // move forward/backward or dolly if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS) { camera_->dolly(-moveVelocity_ * static_cast<GLfloat>(mouseY - mouseYOld)); } else { camera_->translate(glm::vec3(0.0f, 0.0f, moveVelocity_ * (mouseY - mouseYOld))); } // rotate around yaw/azimuth axis if (isFlyMode_) { camera_->rotateYaw(-rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } else { // examine mode camera_->rotateAzimuth(rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } toggleMouseButton = true; } else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS && ! (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS)) { // right mouse button pressed: camera rotation glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwGetCursorPos(window, &mouseX, &mouseY); glfwSetCursorPos(window, mouseXOld, mouseYOld); // rotate around roll or yaw/azimuth axis if (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS) { if (isFlyMode_) { camera_->rotateYaw(-rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } else { // examine mode camera_->rotateAzimuth(rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } } else { camera_->rotateRoll(rotateVelocity_ * static_cast<GLfloat>(mouseX - mouseXOld)); } // rotate around pitch/elevation axis if (isFlyMode_) { camera_->rotatePitch(rotateVelocity_ * static_cast<GLfloat>(mouseY - mouseYOld)); } else { // examine mode camera_->rotateElevation(-rotateVelocity_ * static_cast<GLfloat>(mouseY - mouseYOld)); } toggleMouseButton = true; } else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS || (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS && (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS))) { // middle mouse button pressed: toggle fly/examine mode if (!toggleMouseButton) { static bool prevDrawCenterMode = false; isFlyMode_ = !isFlyMode_; if (isFlyMode_) { // fly mode: restore previous draw center point mode camera_->setDrawCenter(prevDrawCenterMode); } else { // examine mode: draw center point, saving current mode prevDrawCenterMode = camera_->isDrawCenter(); camera_->setDrawCenter(true); } } toggleMouseButton = true; } else { // no mouse button pressed: restore mouse cursor glfwGetCursorPos(window, &mouseXOld, &mouseYOld); if (viewState->isMouseCursorVisible()) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } toggleMouseButton = false; } } } /* namespace scg */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: utility.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2005-10-05 14:58:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef UTILITY_HXX #define UTILITY_HXX #ifndef _SFXVARARR_HXX //autogen #include <sfx2/minarray.hxx> #endif #ifndef _FONT_HXX //autogen #include <vcl/font.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _FRACT_HXX //autogen #include <tools/fract.hxx> #endif class SmRect; class String; #define C2S(cChar) String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(cChar)) ///////////////////////////////////////////////////////////////// const ByteString ExportString( const String& rString ); const String ImportString( const ByteString& rByteString ); ///////////////////////////////////////////////////////////////// inline long SmPtsTo100th_mm(long nNumPts) // returns the length (in 100th of mm) that corresponds to the length // 'nNumPts' (in units points). // 72.27 [pt] = 1 [inch] = 2,54 [cm] = 2540 [100th of mm]. // result is being rounded to the nearest integer. { DBG_ASSERT(nNumPts >= 0, "Sm : Ooops..."); // broken into multiple and fraction of 'nNumPts' to reduce chance // of overflow // (7227 / 2) is added in order to round to the nearest integer return 35 * nNumPts + (nNumPts * 1055L + (7227 / 2)) / 7227L; } inline long SmPtsTo100th_mm(const Fraction &rNumPts) // as above but with argument 'rNumPts' as 'Fraction' { Fraction aTmp (254000L, 7227L); return aTmp *= rNumPts; } inline Fraction Sm100th_mmToPts(long nNum100th_mm) // returns the length (in points) that corresponds to the length // 'nNum100th_mm' (in 100th of mm). { DBG_ASSERT(nNum100th_mm >= 0, "Sm : Ooops..."); Fraction aTmp (7227L, 254000L); return aTmp *= Fraction(nNum100th_mm); } inline long SmRoundFraction(const Fraction &rFrac) { DBG_ASSERT(rFrac > Fraction(), "Sm : Ooops..."); return (rFrac.GetNumerator() + rFrac.GetDenominator() / 2) / rFrac.GetDenominator(); } class SmViewShell; SmViewShell * SmGetActiveView(); //////////////////////////////////////////////////////////// // // SmFace // BOOL IsItalic( const Font &rFont ); BOOL IsBold( const Font &rFont ); class SmFace : public Font { long nBorderWidth; void Impl_Init(); public: SmFace() : Font(), nBorderWidth(-1) { Impl_Init(); } SmFace(const Font& rFont) : Font(rFont), nBorderWidth(-1) { Impl_Init(); } SmFace(const String& rName, const Size& rSize) : Font(rName, rSize), nBorderWidth(-1) { Impl_Init(); } SmFace( FontFamily eFamily, const Size& rSize) : Font(eFamily, rSize), nBorderWidth(-1) { Impl_Init(); } SmFace(const SmFace &rFace) : Font(rFace), nBorderWidth(-1) { Impl_Init(); } // overloaded version in order to supply a min value // for font size (height). (Also used in ctor's to do so.) void SetSize(const Size& rSize); void SetBorderWidth(long nWidth) { nBorderWidth = nWidth; } long GetBorderWidth() const; long GetDefaultBorderWidth() const { return GetSize().Height() / 20 ; } void FreezeBorderWidth() { nBorderWidth = GetDefaultBorderWidth(); } SmFace & operator = (const SmFace &rFace); }; SmFace & operator *= (SmFace &rFace, const Fraction &rFrac); #ifdef NEVER //////////////////////////////////////////////////////////// // // SmInfoText // class SmInfoText : public FixedText { protected: USHORT nMaxLen; String aText; public: SmInfoText(Window* pParent, WinBits nWinStyle = 0, USHORT nMax = 128); SmInfoText(Window* pParent, const ResId& rResId, USHORT nMax = 128); void SetText(const String& rStr); XubString GetText() const { return (aText); } }; #endif //////////////////////////////////////////////////////////// // // SmPickList // class SmPickList : public SfxPtrArr { protected: USHORT nSize; virtual void *CreateItem(const String& rString) = 0; virtual void *CreateItem(const void *pItem) = 0; virtual void DestroyItem(void *pItem) = 0; virtual BOOL CompareItem(const void *pFirstItem, const void *pSecondItem) const = 0; virtual String GetStringItem(void *pItem) = 0; void *GetPtr(USHORT nPos) const { return SfxPtrArr::GetObject(nPos); } void *&GetPtr(USHORT nPos) { return SfxPtrArr::GetObject(nPos); } void InsertPtr(USHORT nPos, void *pItem) { SfxPtrArr::Insert(nPos, pItem); } void RemovePtr(USHORT nPos, USHORT nCount = 1) { SfxPtrArr::Remove(nPos, nCount); } public: SmPickList(USHORT nInitSize = 0, USHORT nMaxSize = 5); ~SmPickList(); SmPickList& operator = (const SmPickList& rList); void *Get(USHORT nPos = 0) const { return GetPtr(nPos); } void Insert(const void* pItem); void Update(const void* pItem, const void *pNewItem); void Remove(const void* pItem); void *operator [] (USHORT nPos) const { return GetPtr(nPos); } void SetSize(USHORT nNewSize); USHORT GetSize() const { return nSize; } USHORT Count() const { return SfxPtrArr::Count(); } BOOL Contains(const void *pItem) const; void Clear(); }; //////////////////////////////////////////////////////////// // // SmStringPickList // #ifdef NEVER class SmStringPickList : public SmPickList { protected: virtual void *CreateItem(const String& rString); virtual void *CreateItem(const void *pItem); virtual void DestroyItem(void *pItem); virtual BOOL CompareItem(const void *pFirstItem, const void *pSecondItem) const; virtual String GetStringItem(void *pItem); public: SmStringPickList() : SmPickList(0, 5) {} SmStringPickList(USHORT nInitSize, USHORT nMaxSize) : SmPickList(nInitSize, nMaxSize) {} SmStringPickList(const SmPickList& rOrig ) : SmPickList(rOrig) {} ~SmStringPickList() { Clear(); } virtual void Insert(const String &rString); virtual void Update(const String &rString, const String &rNewString); virtual void Remove(const String &rString); inline BOOL Contains(const String &rString) const; inline String Get(USHORT nPos = 0) const; inline SmStringPickList& operator = (const SmStringPickList& rList); inline String operator [] (USHORT nPos) const; }; inline SmStringPickList& SmStringPickList::operator = (const SmStringPickList& rList) { *(SmPickList *)this = *(SmPickList *)&rList; return *this; } inline String SmStringPickList::operator [] (USHORT nPos) const { return *((String *)SmPickList::operator[](nPos)); } inline String SmStringPickList::Get(USHORT nPos) const { return nPos < Count() ? *((String *)SmPickList::Get(nPos)) : String(); } inline BOOL SmStringPickList::Contains(const String &rString) const { return SmPickList::Contains((void *)&rString); } #endif //////////////////////////////////////////////////////////// // // SmFontPickList // class SmFontDialog; class SmFontPickList : public SmPickList { protected: virtual void *CreateItem(const String& rString); virtual void *CreateItem(const void *pItem); virtual void DestroyItem(void *pItem); virtual BOOL CompareItem(const void *pFirstItem, const void *pSecondItem) const; virtual String GetStringItem(void *pItem); public: SmFontPickList() : SmPickList(0, 5) {} SmFontPickList(USHORT nInitSize, USHORT nMaxSize) : SmPickList(nInitSize, nMaxSize) {} SmFontPickList(const SmPickList& rOrig ) : SmPickList(rOrig) {} ~SmFontPickList() { Clear(); } virtual void Insert(const Font &rFont); virtual void Update(const Font &rFont, const Font &rNewFont); virtual void Remove(const Font &rFont); inline BOOL Contains(const Font &rFont) const; inline Font Get(USHORT nPos = 0) const; inline SmFontPickList& operator = (const SmFontPickList& rList); inline Font operator [] (USHORT nPos) const; void ReadFrom(const SmFontDialog& rDialog); void WriteTo(SmFontDialog& rDialog) const; }; inline SmFontPickList& SmFontPickList::operator = (const SmFontPickList& rList) { *(SmPickList *)this = *(SmPickList *)&rList; return *this; } inline Font SmFontPickList::operator [] (USHORT nPos) const { return *((Font *)SmPickList::operator[](nPos)); } inline Font SmFontPickList::Get(USHORT nPos) const { return nPos < Count() ? *((Font *)SmPickList::Get(nPos)) : Font(); } inline BOOL SmFontPickList::Contains(const Font &rFont) const { return SmPickList::Contains((void *)&rFont); } //////////////////////////////////////////////////////////// // // SmStringPickComboBox // #ifdef NEVER class SmStringPickComboBox : public SmStringPickList, public ComboBox { protected: virtual void LoseFocus(); DECL_LINK(SelectHdl, ComboBox *); public: SmStringPickComboBox(Window* pParent, WinBits nWinStyle = 0, USHORT nMax = 4); SmStringPickComboBox(Window* pParent, const ResId& rResId, USHORT nMax = 4); SmStringPickComboBox& operator = (const SmStringPickList& rList); void SetText(const String& rStr); virtual void Insert(const String &rString); virtual void Update(const String &rString, const String &rNewString); virtual void Remove(const String &rString); }; #endif //////////////////////////////////////////////////////////// // // SmFontPickListBox // class SmFontPickListBox : public SmFontPickList, public ListBox { protected: DECL_LINK(SelectHdl, ListBox *); public: SmFontPickListBox(Window* pParent, WinBits nWinStyle = 0, USHORT nMax = 4); SmFontPickListBox(Window* pParent, const ResId& rResId, USHORT nMax = 4); SmFontPickListBox& operator = (const SmFontPickList& rList); virtual void Insert(const Font &rFont); virtual void Update(const Font &rFont, const Font &rNewFont); virtual void Remove(const Font &rFont); }; #endif <commit_msg>INTEGRATION: CWS tl32 (1.8.138); FILE MERGED 2006/11/02 15:13:53 tl 1.8.138.2: #i69286# make starmath warning-free for unxsols4(.pro) 2006/10/30 10:34:44 tl 1.8.138.1: #i69286# make starmath warning-free<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: utility.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2007-05-25 12:10:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef UTILITY_HXX #define UTILITY_HXX #ifndef _SFXVARARR_HXX //autogen #include <sfx2/minarray.hxx> #endif #ifndef _FONT_HXX //autogen #include <vcl/font.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _FRACT_HXX //autogen #include <tools/fract.hxx> #endif class SmRect; class String; #define C2S(cChar) String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(cChar)) ///////////////////////////////////////////////////////////////// const ByteString ExportString( const String& rString ); const String ImportString( const ByteString& rByteString ); ///////////////////////////////////////////////////////////////// inline long SmPtsTo100th_mm(long nNumPts) // returns the length (in 100th of mm) that corresponds to the length // 'nNumPts' (in units points). // 72.27 [pt] = 1 [inch] = 2,54 [cm] = 2540 [100th of mm]. // result is being rounded to the nearest integer. { DBG_ASSERT(nNumPts >= 0, "Sm : Ooops..."); // broken into multiple and fraction of 'nNumPts' to reduce chance // of overflow // (7227 / 2) is added in order to round to the nearest integer return 35 * nNumPts + (nNumPts * 1055L + (7227 / 2)) / 7227L; } inline long SmPtsTo100th_mm(const Fraction &rNumPts) // as above but with argument 'rNumPts' as 'Fraction' { Fraction aTmp (254000L, 7227L); return aTmp *= rNumPts; } inline Fraction Sm100th_mmToPts(long nNum100th_mm) // returns the length (in points) that corresponds to the length // 'nNum100th_mm' (in 100th of mm). { DBG_ASSERT(nNum100th_mm >= 0, "Sm : Ooops..."); Fraction aTmp (7227L, 254000L); return aTmp *= Fraction(nNum100th_mm); } inline long SmRoundFraction(const Fraction &rFrac) { DBG_ASSERT(rFrac > Fraction(), "Sm : Ooops..."); return (rFrac.GetNumerator() + rFrac.GetDenominator() / 2) / rFrac.GetDenominator(); } class SmViewShell; SmViewShell * SmGetActiveView(); //////////////////////////////////////////////////////////// // // SmFace // BOOL IsItalic( const Font &rFont ); BOOL IsBold( const Font &rFont ); class SmFace : public Font { long nBorderWidth; void Impl_Init(); public: SmFace() : Font(), nBorderWidth(-1) { Impl_Init(); } SmFace(const Font& rFont) : Font(rFont), nBorderWidth(-1) { Impl_Init(); } SmFace(const String& rName, const Size& rSize) : Font(rName, rSize), nBorderWidth(-1) { Impl_Init(); } SmFace( FontFamily eFamily, const Size& rSize) : Font(eFamily, rSize), nBorderWidth(-1) { Impl_Init(); } SmFace(const SmFace &rFace) : Font(rFace), nBorderWidth(-1) { Impl_Init(); } // overloaded version in order to supply a min value // for font size (height). (Also used in ctor's to do so.) void SetSize(const Size& rSize); void SetBorderWidth(long nWidth) { nBorderWidth = nWidth; } long GetBorderWidth() const; long GetDefaultBorderWidth() const { return GetSize().Height() / 20 ; } void FreezeBorderWidth() { nBorderWidth = GetDefaultBorderWidth(); } SmFace & operator = (const SmFace &rFace); }; SmFace & operator *= (SmFace &rFace, const Fraction &rFrac); #ifdef NEVER //////////////////////////////////////////////////////////// // // SmInfoText // class SmInfoText : public FixedText { protected: USHORT nMaxLen; String aText; public: SmInfoText(Window* pParent, WinBits nWinStyle = 0, USHORT nMax = 128); SmInfoText(Window* pParent, const ResId& rResId, USHORT nMax = 128); void SetText(const String& rStr); XubString GetText() const { return (aText); } }; #endif //////////////////////////////////////////////////////////// // // SmPickList // class SmPickList : public SfxPtrArr { protected: USHORT nSize; virtual void *CreateItem(const String& rString) = 0; virtual void *CreateItem(const void *pItem) = 0; virtual void DestroyItem(void *pItem) = 0; virtual BOOL CompareItem(const void *pFirstItem, const void *pSecondItem) const = 0; virtual String GetStringItem(void *pItem) = 0; void *GetPtr(USHORT nPos) const { return SfxPtrArr::GetObject(nPos); } void *&GetPtr(USHORT nPos) { return SfxPtrArr::GetObject(nPos); } void InsertPtr(USHORT nPos, void *pItem) { SfxPtrArr::Insert(nPos, pItem); } void RemovePtr(USHORT nPos, USHORT nCount = 1) { SfxPtrArr::Remove(nPos, nCount); } public: SmPickList(USHORT nInitSize = 0, USHORT nMaxSize = 5); virtual ~SmPickList(); SmPickList& operator = (const SmPickList& rList); void *Get(USHORT nPos = 0) const { return GetPtr(nPos); } using SfxPtrArr::Insert; void Insert(const void* pItem); void Update(const void* pItem, const void *pNewItem); using SfxPtrArr::Remove; void Remove(const void* pItem); using SfxPtrArr::operator []; void *operator [] (USHORT nPos) const { return GetPtr(nPos); } void SetSize(USHORT nNewSize); USHORT GetSize() const { return nSize; } USHORT Count() const { return SfxPtrArr::Count(); } BOOL Contains(const void *pItem) const; void Clear(); }; //////////////////////////////////////////////////////////// // // SmStringPickList // #ifdef NEVER class SmStringPickList : public SmPickList { protected: virtual void *CreateItem(const String& rString); virtual void *CreateItem(const void *pItem); virtual void DestroyItem(void *pItem); virtual BOOL CompareItem(const void *pFirstItem, const void *pSecondItem) const; virtual String GetStringItem(void *pItem); public: SmStringPickList() : SmPickList(0, 5) {} SmStringPickList(USHORT nInitSize, USHORT nMaxSize) : SmPickList(nInitSize, nMaxSize) {} SmStringPickList(const SmPickList& rOrig ) : SmPickList(rOrig) {} virtual ~SmStringPickList() { Clear(); } virtual void Insert(const String &rString); virtual void Update(const String &rString, const String &rNewString); virtual void Remove(const String &rString); inline BOOL Contains(const String &rString) const; inline String Get(USHORT nPos = 0) const; inline SmStringPickList& operator = (const SmStringPickList& rList); inline String operator [] (USHORT nPos) const; }; inline SmStringPickList& SmStringPickList::operator = (const SmStringPickList& rList) { *(SmPickList *)this = *(SmPickList *)&rList; return *this; } inline String SmStringPickList::operator [] (USHORT nPos) const { return *((String *)SmPickList::operator[](nPos)); } inline String SmStringPickList::Get(USHORT nPos) const { return nPos < Count() ? *((String *)SmPickList::Get(nPos)) : String(); } inline BOOL SmStringPickList::Contains(const String &rString) const { return SmPickList::Contains((void *)&rString); } #endif //////////////////////////////////////////////////////////// // // SmFontPickList // class SmFontDialog; class SmFontPickList : public SmPickList { protected: virtual void *CreateItem(const String& rString); virtual void *CreateItem(const void *pItem); virtual void DestroyItem(void *pItem); virtual BOOL CompareItem(const void *pFirstItem, const void *pSecondItem) const; virtual String GetStringItem(void *pItem); public: SmFontPickList() : SmPickList(0, 5) {} SmFontPickList(USHORT nInitSize, USHORT nMaxSize) : SmPickList(nInitSize, nMaxSize) {} SmFontPickList(const SmPickList& rOrig ) : SmPickList(rOrig) {} virtual ~SmFontPickList() { Clear(); } using SfxPtrArr::Insert; virtual void Insert(const Font &rFont); using SmPickList::Update; virtual void Update(const Font &rFont, const Font &rNewFont); using SfxPtrArr::Remove; virtual void Remove(const Font &rFont); using SmPickList::Contains; inline BOOL Contains(const Font &rFont) const; inline Font Get(USHORT nPos = 0) const; inline SmFontPickList& operator = (const SmFontPickList& rList); using SfxPtrArr::operator []; inline Font operator [] (USHORT nPos) const; void ReadFrom(const SmFontDialog& rDialog); void WriteTo(SmFontDialog& rDialog) const; }; inline SmFontPickList& SmFontPickList::operator = (const SmFontPickList& rList) { *(SmPickList *)this = *(SmPickList *)&rList; return *this; } inline Font SmFontPickList::operator [] (USHORT nPos) const { return *((Font *)SmPickList::operator[](nPos)); } inline Font SmFontPickList::Get(USHORT nPos) const { return nPos < Count() ? *((Font *)SmPickList::Get(nPos)) : Font(); } inline BOOL SmFontPickList::Contains(const Font &rFont) const { return SmPickList::Contains((void *)&rFont); } //////////////////////////////////////////////////////////// // // SmStringPickComboBox // #ifdef NEVER class SmStringPickComboBox : public SmStringPickList, public ComboBox { protected: virtual void LoseFocus(); DECL_LINK(SelectHdl, ComboBox *); public: SmStringPickComboBox(Window* pParent, WinBits nWinStyle = 0, USHORT nMax = 4); SmStringPickComboBox(Window* pParent, const ResId& rResId, USHORT nMax = 4); SmStringPickComboBox& operator = (const SmStringPickList& rList); void SetText(const String& rStr); virtual void Insert(const String &rString); virtual void Update(const String &rString, const String &rNewString); virtual void Remove(const String &rString); }; #endif //////////////////////////////////////////////////////////// // // SmFontPickListBox // class SmFontPickListBox : public SmFontPickList, public ListBox { protected: DECL_LINK(SelectHdl, ListBox *); public: SmFontPickListBox(Window* pParent, WinBits nWinStyle = 0, USHORT nMax = 4); SmFontPickListBox(Window* pParent, const ResId& rResId, USHORT nMax = 4); SmFontPickListBox& operator = (const SmFontPickList& rList); using SfxPtrArr::Insert; virtual void Insert(const Font &rFont); using Window::Update; virtual void Update(const Font &rFont, const Font &rNewFont); using SfxPtrArr::Remove; virtual void Remove(const Font &rFont); }; #endif <|endoftext|>
<commit_before> <commit_msg>Delete 1.cpp<commit_after><|endoftext|>
<commit_before>#include "../includes/win32/Controller.h" static std::wstring convertMultiByteToWideChar(const std::string &multiByte) { const int wlen = MultiByteToWideChar(CP_UTF8, 0, multiByte.data(), -1, 0, 0); if (wlen == 0) { return std::wstring(); } std::wstring wideString; wideString.resize(wlen-1); int failureToResolveUTF8 = MultiByteToWideChar(CP_UTF8, 0, multiByte.data(), -1, &(wideString[0]), wlen); if (failureToResolveUTF8 == 0) { return std::wstring(); } return wideString; } HANDLE Controller::openDirectory(const std::wstring &path) { return CreateFileW( path.data(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL ); } Controller::Controller(std::shared_ptr<EventQueue> queue, const std::string &path) : mDirectoryHandle(INVALID_HANDLE_VALUE) { auto widePath = convertMultiByteToWideChar(path); mDirectoryHandle = openDirectory(widePath); if (mDirectoryHandle == INVALID_HANDLE_VALUE) { return; } mWatcher.reset(new Watcher(queue, mDirectoryHandle, widePath)); } Controller::~Controller() { mWatcher.reset(); CancelIo(mDirectoryHandle); CloseHandle(mDirectoryHandle); mDirectoryHandle = INVALID_HANDLE_VALUE; } std::string Controller::getError() { if (mDirectoryHandle == INVALID_HANDLE_VALUE) { return "Failed to open directory"; } return mWatcher->getError(); } bool Controller::hasErrored() { return mDirectoryHandle == INVALID_HANDLE_VALUE || !mWatcher->getError().empty(); } bool Controller::isWatching() { return mWatcher->isRunning(); } <commit_msg>Verify watcher has not errored before isRunning check<commit_after>#include "../includes/win32/Controller.h" static std::wstring convertMultiByteToWideChar(const std::string &multiByte) { const int wlen = MultiByteToWideChar(CP_UTF8, 0, multiByte.data(), -1, 0, 0); if (wlen == 0) { return std::wstring(); } std::wstring wideString; wideString.resize(wlen-1); int failureToResolveUTF8 = MultiByteToWideChar(CP_UTF8, 0, multiByte.data(), -1, &(wideString[0]), wlen); if (failureToResolveUTF8 == 0) { return std::wstring(); } return wideString; } HANDLE Controller::openDirectory(const std::wstring &path) { return CreateFileW( path.data(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL ); } Controller::Controller(std::shared_ptr<EventQueue> queue, const std::string &path) : mDirectoryHandle(INVALID_HANDLE_VALUE) { auto widePath = convertMultiByteToWideChar(path); mDirectoryHandle = openDirectory(widePath); if (mDirectoryHandle == INVALID_HANDLE_VALUE) { return; } mWatcher.reset(new Watcher(queue, mDirectoryHandle, widePath)); } Controller::~Controller() { mWatcher.reset(); CancelIo(mDirectoryHandle); CloseHandle(mDirectoryHandle); mDirectoryHandle = INVALID_HANDLE_VALUE; } std::string Controller::getError() { if (mDirectoryHandle == INVALID_HANDLE_VALUE) { return "Failed to open directory"; } return mWatcher->getError(); } bool Controller::hasErrored() { return mDirectoryHandle == INVALID_HANDLE_VALUE || !mWatcher->getError().empty(); } bool Controller::isWatching() { return !hasErrored() && mWatcher->isRunning(); } <|endoftext|>
<commit_before>#pragma once #include "math.hpp" #include <math.h> namespace matrix { template<typename Type> Type wrap_pi(Type x) { if (!isfinite(float(x))) { return x; } while (x >= (Type)M_PI) { x -= (Type)(2.0 * M_PI); } while (x < (Type)(-M_PI)) { x += (Type)(2.0 * M_PI); } return x; } }; <commit_msg>Fix cast<commit_after>#pragma once #include "math.hpp" #include <math.h> namespace matrix { template<typename Type> Type wrap_pi(Type x) { if (!isfinite(Type(x))) { return x; } while (x >= (Type)M_PI) { x -= (Type)(2.0 * M_PI); } while (x < (Type)(-M_PI)) { x += (Type)(2.0 * M_PI); } return x; } }; <|endoftext|>
<commit_before>// Copyright 2012-2013 Samplecount S.L. // // 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 "methc.la/plugins/sampler/sampler.h" #include <iostream> #include <oscpp/server.hpp> #include <unistd.h> typedef enum { kSampler_amp, kSampler_output_0, kSampler_output_1, kSamplerPorts } PortIndex; typedef struct { float* ports[kSamplerPorts]; float* buffer; size_t channels; size_t frames; bool loop; size_t pos; } Synth; static bool port_descriptor( const Methcla_SynthOptions* options , size_t index , Methcla_PortDescriptor* port ) { switch ((PortIndex)index) { case kSampler_amp: *port = { .type = kMethcla_ControlPort, .direction = kMethcla_Input, .flags = kMethcla_PortFlags }; return true; case kSampler_output_0: case kSampler_output_1: *port = { .type = kMethcla_AudioPort, .direction = kMethcla_Output, .flags = kMethcla_PortFlags }; return true; default: return false; } } struct Options { const char* path; bool loop; int32_t numFrames; }; static void configure(const void* tags, size_t tags_size, const void* args, size_t args_size, Methcla_SynthOptions* outOptions) { OSC::Server::ArgStream argStream(OSC::ReadStream(tags, tags_size), OSC::ReadStream(args, args_size)); Options* options = (Options*)outOptions; options->path = argStream.string(); options->loop = argStream.atEnd() ? false : argStream.int32(); options->numFrames = argStream.atEnd() ? -1 : argStream.int32(); // std::cout << "Sampler: " // << options->path << " " // << options->loop << " " // << options->numFrames << "\n"; } struct LoadMessage { Synth* synth; size_t numChannels; int64_t numFrames; float* buffer; char path[]; }; static void set_buffer(const Methcla_World* world, void* data) { // std::cout << "set_buffer\n"; LoadMessage* msg = (LoadMessage*)data; msg->synth->buffer = msg->buffer; msg->synth->channels = msg->numChannels; msg->synth->frames = msg->numFrames; methcla_world_free(world, msg); } static void load_sound_file(const Methcla_Host* host, void* data) { // std::cout << "load_sound_file\n"; LoadMessage* msg = (LoadMessage*)data; Methcla_SoundFile* file; Methcla_SoundFileInfo info; Methcla_FileError err = methcla_host_soundfile_open(host, msg->path, kMethcla_Read, &file, &info); if (err == kMethcla_FileNoError) { msg->numFrames = msg->numFrames < 0 ? info.frames : std::min<int64_t>(msg->numFrames, info.frames); msg->numChannels = info.channels; msg->buffer = (float*)malloc(msg->numChannels * msg->numFrames * sizeof(float)); // std::cout << "load_sound_file: " << msg->path << " " << info.channels << " " << info.frames << "\n"; // TODO: error handling if (msg->buffer != nullptr) { size_t numFrames; err = methcla_soundfile_read_float(file, msg->buffer, msg->numFrames, &numFrames); } methcla_soundfile_close(file); } methcla_host_perform_command(host, set_buffer, msg); } static void free_buffer_cb(const Methcla_Host*, void* data) { // std::cout << "free_buffer\n"; free(data); } static void freeBuffer(const Methcla_World* world, Synth* self) { if (self->buffer) { methcla_world_perform_command(world, free_buffer_cb, self->buffer); self->buffer = nullptr; } } static void construct( const Methcla_World* world , const Methcla_SynthDef* synthDef , const Methcla_SynthOptions* inOptions , Methcla_Synth* synth ) { const Options* options = (const Options*)inOptions; Synth* self = (Synth*)synth; self->buffer = nullptr; self->channels = 0; self->frames = 0; self->loop = options->loop; self->pos = 0; LoadMessage* msg = (LoadMessage*)methcla_world_alloc(world, sizeof(LoadMessage) + strlen(options->path)+1); msg->synth = self; msg->numFrames = options->numFrames; strcpy(msg->path, options->path); methcla_world_perform_command(world, load_sound_file, msg); } static void destroy(const Methcla_World* world, Methcla_Synth* synth) { Synth* self = (Synth*)synth; freeBuffer(world, self); } static void connect( Methcla_Synth* synth , size_t index , void* data ) { ((Synth*)synth)->ports[index] = (float*)data; } static void process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames) { Synth* self = (Synth*)synth; const float amp = *self->ports[kSampler_amp]; float* out0 = self->ports[kSampler_output_0]; float* out1 = self->ports[kSampler_output_1]; float* buffer = self->buffer; if (buffer) { size_t pos = self->pos; const size_t left = self->frames - pos; const size_t channels = self->channels; if (left >= numFrames) { if (channels == 1) { for (size_t k = 0; k < numFrames; k++) { out0[k] = out1[k] = amp * buffer[(pos+k)*channels]; } } else { for (size_t k = 0; k < numFrames; k++) { const size_t j = (pos+k)*channels; out0[k] = amp * buffer[j]; out1[k] = amp * buffer[j+1]; } } if (left == numFrames) { if (self->loop) self->pos = 0; else freeBuffer(world, self); } else { self->pos = pos + numFrames; }; } else if (self->loop) { size_t played = 0; size_t toPlay = left; while (played < numFrames) { if (channels == 1) { for (size_t k = 0; k < toPlay; k++) { const size_t m = played+k; const size_t j = (pos+k)*channels; out0[m] = out1[m] = amp * buffer[j]; } } else { for (size_t k = 0; k < toPlay; k++) { const size_t m = played+k; const size_t j = (pos+k)*channels; out0[m] = amp * buffer[j]; out1[m] = amp * buffer[j+1]; } } played += toPlay; pos += toPlay; if (pos >= self->frames) pos = 0; toPlay = std::min(numFrames - played, self->frames); } self->pos = pos; } else { if (channels == 1) { for (size_t k = 0; k < left; k++) { const size_t j = (pos+k)*channels; out0[k] = out1[k] = amp * buffer[j]; } } else { for (size_t k = 0; k < left; k++) { const size_t j = (pos+k)*channels; out0[k] = amp * buffer[j]; out1[k] = amp * buffer[j+1]; } } for (size_t k = left; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } freeBuffer(world, self); } } else { for (size_t k = 0; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } } } static const Methcla_SynthDef descriptor = { METHCLA_PLUGINS_SAMPLER_URI, sizeof(Synth), sizeof(Options), configure, port_descriptor, construct, connect, nullptr, process, destroy }; static const Methcla_Library library = { NULL, NULL }; METHCLA_EXPORT const Methcla_Library* methcla_plugins_sampler(const Methcla_Host* host, const char* bundlePath) { methcla_host_register_synthdef(host, &descriptor); return &library; } <commit_msg>Store pointer to path in LoadMessage<commit_after>// Copyright 2012-2013 Samplecount S.L. // // 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 "methc.la/plugins/sampler/sampler.h" #include <iostream> #include <oscpp/server.hpp> #include <unistd.h> typedef enum { kSampler_amp, kSampler_output_0, kSampler_output_1, kSamplerPorts } PortIndex; typedef struct { float* ports[kSamplerPorts]; float* buffer; size_t channels; size_t frames; bool loop; size_t pos; } Synth; static bool port_descriptor( const Methcla_SynthOptions* options , size_t index , Methcla_PortDescriptor* port ) { switch ((PortIndex)index) { case kSampler_amp: *port = { .type = kMethcla_ControlPort, .direction = kMethcla_Input, .flags = kMethcla_PortFlags }; return true; case kSampler_output_0: case kSampler_output_1: *port = { .type = kMethcla_AudioPort, .direction = kMethcla_Output, .flags = kMethcla_PortFlags }; return true; default: return false; } } struct Options { const char* path; bool loop; int32_t numFrames; }; static void configure(const void* tags, size_t tags_size, const void* args, size_t args_size, Methcla_SynthOptions* outOptions) { OSC::Server::ArgStream argStream(OSC::ReadStream(tags, tags_size), OSC::ReadStream(args, args_size)); Options* options = (Options*)outOptions; options->path = argStream.string(); options->loop = argStream.atEnd() ? false : argStream.int32(); options->numFrames = argStream.atEnd() ? -1 : argStream.int32(); // std::cout << "Sampler: " // << options->path << " " // << options->loop << " " // << options->numFrames << "\n"; } struct LoadMessage { Synth* synth; size_t numChannels; int64_t numFrames; float* buffer; char* path; }; static void set_buffer(const Methcla_World* world, void* data) { // std::cout << "set_buffer\n"; LoadMessage* msg = (LoadMessage*)data; msg->synth->buffer = msg->buffer; msg->synth->channels = msg->numChannels; msg->synth->frames = msg->numFrames; methcla_world_free(world, msg); } static void load_sound_file(const Methcla_Host* host, void* data) { // std::cout << "load_sound_file\n"; LoadMessage* msg = (LoadMessage*)data; assert( msg != nullptr ); Methcla_SoundFile* file = nullptr; Methcla_SoundFileInfo info; memset(&info, 0, sizeof(info)); Methcla_FileError err = methcla_host_soundfile_open(host, msg->path, kMethcla_Read, &file, &info); if (err == kMethcla_FileNoError) { msg->numFrames = msg->numFrames < 0 ? info.frames : std::min<int64_t>(msg->numFrames, info.frames); msg->numChannels = info.channels; msg->buffer = (float*)malloc(msg->numChannels * msg->numFrames * sizeof(float)); // std::cout << "load_sound_file: " << msg->path << " " << info.channels << " " << info.frames << "\n"; // TODO: error handling if (msg->buffer != nullptr) { size_t numFrames; err = methcla_soundfile_read_float(file, msg->buffer, msg->numFrames, &numFrames); } methcla_soundfile_close(file); } methcla_host_perform_command(host, set_buffer, msg); } static void free_buffer_cb(const Methcla_Host*, void* data) { // std::cout << "free_buffer\n"; free(data); } static void freeBuffer(const Methcla_World* world, Synth* self) { if (self->buffer) { methcla_world_perform_command(world, free_buffer_cb, self->buffer); self->buffer = nullptr; } } static void construct( const Methcla_World* world , const Methcla_SynthDef* synthDef , const Methcla_SynthOptions* inOptions , Methcla_Synth* synth ) { const Options* options = (const Options*)inOptions; Synth* self = (Synth*)synth; self->buffer = nullptr; self->channels = 0; self->frames = 0; self->loop = options->loop; self->pos = 0; LoadMessage* msg = (LoadMessage*)methcla_world_alloc(world, sizeof(LoadMessage) + strlen(options->path)+1); msg->synth = self; msg->numChannels = 0; msg->numFrames = options->numFrames; msg->path = (char*)msg + sizeof(LoadMessage); strcpy(msg->path, options->path); methcla_world_perform_command(world, load_sound_file, msg); } static void destroy(const Methcla_World* world, Methcla_Synth* synth) { Synth* self = (Synth*)synth; freeBuffer(world, self); } static void connect( Methcla_Synth* synth , size_t index , void* data ) { ((Synth*)synth)->ports[index] = (float*)data; } static void process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames) { Synth* self = (Synth*)synth; const float amp = *self->ports[kSampler_amp]; float* out0 = self->ports[kSampler_output_0]; float* out1 = self->ports[kSampler_output_1]; float* buffer = self->buffer; if (buffer) { size_t pos = self->pos; const size_t left = self->frames - pos; const size_t channels = self->channels; if (left >= numFrames) { if (channels == 1) { for (size_t k = 0; k < numFrames; k++) { out0[k] = out1[k] = amp * buffer[(pos+k)*channels]; } } else { for (size_t k = 0; k < numFrames; k++) { const size_t j = (pos+k)*channels; out0[k] = amp * buffer[j]; out1[k] = amp * buffer[j+1]; } } if (left == numFrames) { if (self->loop) self->pos = 0; else freeBuffer(world, self); } else { self->pos = pos + numFrames; }; } else if (self->loop) { size_t played = 0; size_t toPlay = left; while (played < numFrames) { if (channels == 1) { for (size_t k = 0; k < toPlay; k++) { const size_t m = played+k; const size_t j = (pos+k)*channels; out0[m] = out1[m] = amp * buffer[j]; } } else { for (size_t k = 0; k < toPlay; k++) { const size_t m = played+k; const size_t j = (pos+k)*channels; out0[m] = amp * buffer[j]; out1[m] = amp * buffer[j+1]; } } played += toPlay; pos += toPlay; if (pos >= self->frames) pos = 0; toPlay = std::min(numFrames - played, self->frames); } self->pos = pos; } else { if (channels == 1) { for (size_t k = 0; k < left; k++) { const size_t j = (pos+k)*channels; out0[k] = out1[k] = amp * buffer[j]; } } else { for (size_t k = 0; k < left; k++) { const size_t j = (pos+k)*channels; out0[k] = amp * buffer[j]; out1[k] = amp * buffer[j+1]; } } for (size_t k = left; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } freeBuffer(world, self); } } else { for (size_t k = 0; k < numFrames; k++) { out0[k] = out1[k] = 0.f; } } } static const Methcla_SynthDef descriptor = { METHCLA_PLUGINS_SAMPLER_URI, sizeof(Synth), sizeof(Options), configure, port_descriptor, construct, connect, nullptr, process, destroy }; static const Methcla_Library library = { NULL, NULL }; METHCLA_EXPORT const Methcla_Library* methcla_plugins_sampler(const Methcla_Host* host, const char* bundlePath) { methcla_host_register_synthdef(host, &descriptor); return &library; } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/roudi/roudi_cmd_line_parser.hpp" #include "iceoryx_posh/internal/log/posh_logging.hpp" #include "iceoryx_utils/cxx/convert.hpp" #include "iceoryx_versions.hpp" #include "iceoryx_utils/platform/getopt.hpp" #include <iostream> namespace iox { namespace config { void CmdLineParser::parse(int argc, char* argv[], const CmdLineArgumentParsingMode cmdLineParsingMode) noexcept { constexpr option longOptions[] = {{"help", no_argument, nullptr, 'h'}, {"version", no_argument, nullptr, 'v'}, {"monitoring-mode", required_argument, nullptr, 'm'}, {"log-level", required_argument, nullptr, 'l'}, {"ignore-version", required_argument, nullptr, 'i'}, {"unique-roudi-id", required_argument, nullptr, 'u'}, {"compatibility", required_argument, nullptr, 'c'}, {"kill-delay", required_argument, nullptr, 'k'}, {nullptr, 0, nullptr, 0}}; // colon after shortOption means it requires an argument, two colons mean optional argument constexpr const char* shortOptions = "hvm:l:u:c:k:"; int32_t index; int32_t opt{-1}; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, &index), opt != -1)) { switch (opt) { case 'h': std::cout << "Usage: " << argv[0] << " [options]" << std::endl; std::cout << "Options:" << std::endl; std::cout << "-h, --help Display help." << std::endl; std::cout << "-v, --version Display version." << std::endl; std::cout << "-u, --unique-roudi-id <INT> Set the unique RouDi id." << std::endl; std::cout << "-m, --monitoring-mode <MODE> Set process alive monitoring mode." << std::endl; std::cout << " <MODE> {on, off}" << std::endl; std::cout << " default = 'on'" << std::endl; std::cout << " on: enables monitoring for all processes" << std::endl; std::cout << " off: disables monitoring for all processes" << std::endl; std::cout << "-l, --log-level <LEVEL> Set log level." << std::endl; std::cout << " <LEVEL> {off, fatal, error, warning, info, debug, verbose}" << std::endl; std::cout << "-c, --compatibility Set compatibility check level between runtime and RouDi." << std::endl; std::cout << " off: no check" << std::endl; std::cout << " major: same major version " << std::endl; std::cout << " minor: same minor version + major check" << std::endl; std::cout << " patch: same patch version + minor check" << std::endl; std::cout << " commitId: same commit ID + patch check" << std::endl; std::cout << " buildDate: same build date + commId check" << std::endl; std::cout << "-k, --kill-delay <UINT> Sets the delay when RouDi sends SIG_KILL, if apps" << std::endl; std::cout << " have't responded after trying SIG_TERM first, in seconds." << std::endl; m_run = false; break; case 'v': std::cout << "RouDi version: " << ICEORYX_LATEST_RELEASE_VERSION << std::endl; std::cout << "Build date: " << ICEORYX_BUILDDATE << std::endl; std::cout << "Commit ID: " << ICEORYX_SHA1 << std::endl; m_run = false; break; case 'u': { uint16_t roudiId{0u}; constexpr uint64_t MAX_ROUDI_ID = ((1 << 16) - 1); if (!cxx::convert::fromString(optarg, roudiId)) { LogError() << "The RouDi id must be in the range of [0, " << MAX_ROUDI_ID << "]"; m_run = false; } m_uniqueRouDiId.emplace(roudiId); break; } case 'm': { if (strcmp(optarg, "on") == 0) { m_monitoringMode = roudi::MonitoringMode::ON; } else if (strcmp(optarg, "off") == 0) { m_monitoringMode = roudi::MonitoringMode::OFF; } else { m_run = false; LogError() << "Options for monitoring-mode are 'on' and 'off'!"; } break; } case 'l': { if (strcmp(optarg, "off") == 0) { m_logLevel = iox::log::LogLevel::kOff; } else if (strcmp(optarg, "fatal") == 0) { m_logLevel = iox::log::LogLevel::kFatal; } else if (strcmp(optarg, "error") == 0) { m_logLevel = iox::log::LogLevel::kError; } else if (strcmp(optarg, "warning") == 0) { m_logLevel = iox::log::LogLevel::kWarn; } else if (strcmp(optarg, "info") == 0) { m_logLevel = iox::log::LogLevel::kInfo; } else if (strcmp(optarg, "debug") == 0) { m_logLevel = iox::log::LogLevel::kDebug; } else if (strcmp(optarg, "verbose") == 0) { m_logLevel = iox::log::LogLevel::kVerbose; } else { m_run = false; LogError() << "Options for log-level are 'off', 'fatal', 'error', 'warning', 'info', 'debug' and " "'verbose'!"; } break; } case 'k': { uint32_t processKillDelayInSeconds{0u}; constexpr uint64_t MAX_PROCESS_KILL_DELAY = std::numeric_limits<uint32_t>::max(); if (!cxx::convert::fromString(optarg, processKillDelayInSeconds)) { LogError() << "The process kill delay must be in the range of [0, " << MAX_PROCESS_KILL_DELAY << "]"; m_run = false; } else { m_processKillDelay = units::Duration::seconds(static_cast<unsigned long long int>(processKillDelayInSeconds)); } break; } case 'x': { if (strcmp(optarg, "off") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::OFF; } else if (strcmp(optarg, "major") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::MAJOR; } else if (strcmp(optarg, "minor") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::MINOR; } else if (strcmp(optarg, "patch") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::PATCH; } else if (strcmp(optarg, "commitId") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::COMMIT_ID; } else if (strcmp(optarg, "buildDate") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::BUILD_DATE; } else { m_run = false; LogError() << "Options for compatibility are 'off', 'major', 'minor', 'patch', 'commitId' and 'buildDate'!"; } break; } default: { // CmdLineParser did not understand the parameters, don't run m_run = false; } }; if (cmdLineParsingMode == CmdLineArgumentParsingMode::ONE) { break; } } } // namespace roudi bool CmdLineParser::getRun() const noexcept { return m_run; } iox::log::LogLevel CmdLineParser::getLogLevel() const noexcept { return m_logLevel; } roudi::MonitoringMode CmdLineParser::getMonitoringMode() const noexcept { return m_monitoringMode; } version::CompatibilityCheckLevel CmdLineParser::getCompatibilityCheckLevel() const noexcept { return m_compatibilityCheckLevel; } cxx::optional<uint16_t> CmdLineParser::getUniqueRouDiId() const noexcept { return m_uniqueRouDiId; } units::Duration CmdLineParser::getProcessKillDelay() const noexcept { return m_processKillDelay; } void CmdLineParser::printParameters() const noexcept { LogVerbose() << "Command line parameters are.."; LogVerbose() << "Log level: " << m_logLevel; LogVerbose() << "Monitoring mode: " << m_monitoringMode; LogVerbose() << "Compatibility check level: " << m_compatibilityCheckLevel; LogVerbose() << "Unique RouDi ID: " << m_uniqueRouDiId.value(); LogVerbose() << "Process kill delay: " << m_processKillDelay.seconds<uint64_t>() << " ms" ; } } // namespace config } // namespace iox <commit_msg>iox-#447 using and_then or_else pattern to read unique roudi id<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/roudi/roudi_cmd_line_parser.hpp" #include "iceoryx_posh/internal/log/posh_logging.hpp" #include "iceoryx_utils/cxx/convert.hpp" #include "iceoryx_versions.hpp" #include "iceoryx_utils/platform/getopt.hpp" #include <iostream> namespace iox { namespace config { void CmdLineParser::parse(int argc, char* argv[], const CmdLineArgumentParsingMode cmdLineParsingMode) noexcept { constexpr option longOptions[] = {{"help", no_argument, nullptr, 'h'}, {"version", no_argument, nullptr, 'v'}, {"monitoring-mode", required_argument, nullptr, 'm'}, {"log-level", required_argument, nullptr, 'l'}, {"ignore-version", required_argument, nullptr, 'i'}, {"unique-roudi-id", required_argument, nullptr, 'u'}, {"compatibility", required_argument, nullptr, 'c'}, {"kill-delay", required_argument, nullptr, 'k'}, {nullptr, 0, nullptr, 0}}; // colon after shortOption means it requires an argument, two colons mean optional argument constexpr const char* shortOptions = "hvm:l:u:c:k:"; int32_t index; int32_t opt{-1}; while ((opt = getopt_long(argc, argv, shortOptions, longOptions, &index), opt != -1)) { switch (opt) { case 'h': std::cout << "Usage: " << argv[0] << " [options]" << std::endl; std::cout << "Options:" << std::endl; std::cout << "-h, --help Display help." << std::endl; std::cout << "-v, --version Display version." << std::endl; std::cout << "-u, --unique-roudi-id <INT> Set the unique RouDi id." << std::endl; std::cout << "-m, --monitoring-mode <MODE> Set process alive monitoring mode." << std::endl; std::cout << " <MODE> {on, off}" << std::endl; std::cout << " default = 'on'" << std::endl; std::cout << " on: enables monitoring for all processes" << std::endl; std::cout << " off: disables monitoring for all processes" << std::endl; std::cout << "-l, --log-level <LEVEL> Set log level." << std::endl; std::cout << " <LEVEL> {off, fatal, error, warning, info, debug, verbose}" << std::endl; std::cout << "-c, --compatibility Set compatibility check level between runtime and RouDi." << std::endl; std::cout << " off: no check" << std::endl; std::cout << " major: same major version " << std::endl; std::cout << " minor: same minor version + major check" << std::endl; std::cout << " patch: same patch version + minor check" << std::endl; std::cout << " commitId: same commit ID + patch check" << std::endl; std::cout << " buildDate: same build date + commId check" << std::endl; std::cout << "-k, --kill-delay <UINT> Sets the delay when RouDi sends SIG_KILL, if apps" << std::endl; std::cout << " have't responded after trying SIG_TERM first, in seconds." << std::endl; m_run = false; break; case 'v': std::cout << "RouDi version: " << ICEORYX_LATEST_RELEASE_VERSION << std::endl; std::cout << "Build date: " << ICEORYX_BUILDDATE << std::endl; std::cout << "Commit ID: " << ICEORYX_SHA1 << std::endl; m_run = false; break; case 'u': { uint16_t roudiId{0u}; constexpr uint64_t MAX_ROUDI_ID = ((1 << 16) - 1); if (!cxx::convert::fromString(optarg, roudiId)) { LogError() << "The RouDi id must be in the range of [0, " << MAX_ROUDI_ID << "]"; m_run = false; } m_uniqueRouDiId.emplace(roudiId); break; } case 'm': { if (strcmp(optarg, "on") == 0) { m_monitoringMode = roudi::MonitoringMode::ON; } else if (strcmp(optarg, "off") == 0) { m_monitoringMode = roudi::MonitoringMode::OFF; } else { m_run = false; LogError() << "Options for monitoring-mode are 'on' and 'off'!"; } break; } case 'l': { if (strcmp(optarg, "off") == 0) { m_logLevel = iox::log::LogLevel::kOff; } else if (strcmp(optarg, "fatal") == 0) { m_logLevel = iox::log::LogLevel::kFatal; } else if (strcmp(optarg, "error") == 0) { m_logLevel = iox::log::LogLevel::kError; } else if (strcmp(optarg, "warning") == 0) { m_logLevel = iox::log::LogLevel::kWarn; } else if (strcmp(optarg, "info") == 0) { m_logLevel = iox::log::LogLevel::kInfo; } else if (strcmp(optarg, "debug") == 0) { m_logLevel = iox::log::LogLevel::kDebug; } else if (strcmp(optarg, "verbose") == 0) { m_logLevel = iox::log::LogLevel::kVerbose; } else { m_run = false; LogError() << "Options for log-level are 'off', 'fatal', 'error', 'warning', 'info', 'debug' and " "'verbose'!"; } break; } case 'k': { uint32_t processKillDelayInSeconds{0u}; constexpr uint64_t MAX_PROCESS_KILL_DELAY = std::numeric_limits<uint32_t>::max(); if (!cxx::convert::fromString(optarg, processKillDelayInSeconds)) { LogError() << "The process kill delay must be in the range of [0, " << MAX_PROCESS_KILL_DELAY << "]"; m_run = false; } else { m_processKillDelay = units::Duration::seconds(static_cast<unsigned long long int>(processKillDelayInSeconds)); } break; } case 'x': { if (strcmp(optarg, "off") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::OFF; } else if (strcmp(optarg, "major") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::MAJOR; } else if (strcmp(optarg, "minor") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::MINOR; } else if (strcmp(optarg, "patch") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::PATCH; } else if (strcmp(optarg, "commitId") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::COMMIT_ID; } else if (strcmp(optarg, "buildDate") == 0) { m_compatibilityCheckLevel = iox::version::CompatibilityCheckLevel::BUILD_DATE; } else { m_run = false; LogError() << "Options for compatibility are 'off', 'major', 'minor', 'patch', 'commitId' and 'buildDate'!"; } break; } default: { // CmdLineParser did not understand the parameters, don't run m_run = false; } }; if (cmdLineParsingMode == CmdLineArgumentParsingMode::ONE) { break; } } } // namespace roudi bool CmdLineParser::getRun() const noexcept { return m_run; } iox::log::LogLevel CmdLineParser::getLogLevel() const noexcept { return m_logLevel; } roudi::MonitoringMode CmdLineParser::getMonitoringMode() const noexcept { return m_monitoringMode; } version::CompatibilityCheckLevel CmdLineParser::getCompatibilityCheckLevel() const noexcept { return m_compatibilityCheckLevel; } cxx::optional<uint16_t> CmdLineParser::getUniqueRouDiId() const noexcept { return m_uniqueRouDiId; } units::Duration CmdLineParser::getProcessKillDelay() const noexcept { return m_processKillDelay; } void CmdLineParser::printParameters() const noexcept { LogVerbose() << "Command line parameters are.."; LogVerbose() << "Log level: " << m_logLevel; LogVerbose() << "Monitoring mode: " << m_monitoringMode; LogVerbose() << "Compatibility check level: " << m_compatibilityCheckLevel; m_uniqueRouDiId.and_then([](auto& id) { LogVerbose() << "Unique RouDi ID: " << id; }).or_else([] { LogVerbose() << "Unique RouDi ID: < unset >"; }); LogVerbose() << "Process kill delay: " << m_processKillDelay.seconds<uint64_t>() << " ms"; } } // namespace config } // namespace iox <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp" #include "iceoryx_posh/popo/condition.hpp" #include "iceoryx_posh/popo/guard_condition.hpp" #include "iceoryx_posh/popo/wait_set.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "test.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::units::duration_literals; class MockSubscriber : public Condition { public: bool setConditionVariable(ConditionVariableData* const ConditionVariableDataPtr) noexcept override { m_condVarPtr = ConditionVariableDataPtr; return true; } bool hasTriggered() const noexcept override { return m_wasTriggered; } bool unsetConditionVariable() noexcept override { m_condVarPtr = nullptr; return true; } /// @note done in ChunkQueuePusher void notify() { // We don't need to check if the WaitSet is still alive as it follows RAII and will inform every Condition about // a possible destruction m_wasTriggered = true; ConditionVariableSignaler signaler{m_condVarPtr}; signaler.notifyOne(); } /// @note members reside in ChunkQueueData in SHM bool m_wasTriggered{false}; ConditionVariableData* m_condVarPtr{nullptr}; }; class WaitSet_test : public Test { public: ConditionVariableData m_condVarData; WaitSet m_sut{&m_condVarData}; vector<MockSubscriber, iox::MAX_NUMBER_OF_CONDITIONS> m_subscriberVector; iox::posix::Semaphore m_syncSemaphore = iox::posix::Semaphore::create(0u).get_value(); void SetUp() { MockSubscriber subscriber; while (m_subscriberVector.size() != m_subscriberVector.capacity()) { m_subscriberVector.push_back(subscriber); } }; void TearDown() { m_sut.detachAllConditions(); m_subscriberVector.clear(); ConditionVariableWaiter waiter{&m_condVarData}; waiter.reset(); }; }; TEST_F(WaitSet_test, AttachSingleConditionSuccessful) { EXPECT_FALSE(m_sut.attachCondition(m_subscriberVector.front()).has_error()); } TEST_F(WaitSet_test, AttachSameConditionTwiceResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_THAT(m_sut.attachCondition(m_subscriberVector.front()).get_error(), Eq(WaitSetError::CONDITION_VARIABLE_ALREADY_SET)); } TEST_F(WaitSet_test, AttachConditionAndDestroyResultsInLifetimeFailure) { auto errorHandlerCalled{false}; iox::Error receivedError; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&errorHandlerCalled, &receivedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerCalled = true; receivedError = error; }); { MockSubscriber scopedCondition; m_sut.attachCondition(scopedCondition); } EXPECT_TRUE(errorHandlerCalled); EXPECT_THAT(receivedError, Eq(iox::Error::kPOPO__WAITSET_CONDITION_LIFETIME_ISSUE)); m_sut.detachAllConditions(); } TEST_F(WaitSet_test, AttachConditionAndDestroyWaitSetResultsInDetach) { { WaitSet m_sut2{&m_condVarData}; m_sut2.attachCondition(m_subscriberVector.front()); } EXPECT_FALSE(m_subscriberVector.front().isConditionVariableAttached()); } /// @todo Add test cases for move c'tor and move assignment TEST_F(WaitSet_test, AttachMaximumAllowedConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { EXPECT_FALSE(m_sut.attachCondition(currentSubscriber).has_error()); } } TEST_F(WaitSet_test, AttachTooManyConditionsResultsInFailure) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } MockSubscriber extraCondition; EXPECT_THAT(m_sut.attachCondition(extraCondition).get_error(), Eq(WaitSetError::CONDITION_VECTOR_OVERFLOW)); } TEST_F(WaitSet_test, DetachSingleConditionSuccessful) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_TRUE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachMultipleConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } for (auto& currentSubscriber : m_subscriberVector) { EXPECT_TRUE(m_sut.detachCondition(currentSubscriber)); } } TEST_F(WaitSet_test, DetachConditionNotInListResultsInFailure) { EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachUnknownConditionResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.back())); } TEST_F(WaitSet_test, AttachConditionInTwoWaitSetsResultsInAlreadySetError) { WaitSet m_sut2{&m_condVarData}; m_sut.attachCondition(m_subscriberVector.front()); EXPECT_THAT(m_sut2.attachCondition(m_subscriberVector.front()).get_error(), Eq(WaitSetError::CONDITION_VARIABLE_ALREADY_SET)); } TEST_F(WaitSet_test, TimedWaitWithInvalidTimeResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(0_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, NoAttachTimedWaitResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(1_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, TimedWaitWithMaximumNumberOfConditionsResultsInReturnOfMaximumNumberOfConditions) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); currentSubscriber.notify(); } auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(iox::MAX_NUMBER_OF_CONDITIONS)); } TEST_F(WaitSet_test, TimedWaitWithNotificationResultsInImmediateTrigger) { m_sut.attachCondition(m_subscriberVector.front()); m_subscriberVector.front().notify(); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); } TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInEmptyVector) { m_sut.attachCondition(m_subscriberVector.front()); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(0)); } TEST_F(WaitSet_test, NotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector[0]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector[0].notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyManyBeforeWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); m_syncSemaphore.wait(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; m_syncSemaphore.post(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyManyWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; waiter.join(); } TEST_F(WaitSet_test, WaitWithoutNotifyResultsInBlockingMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); m_sut.wait(); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, NotifyGuardConditionWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; GuardCondition guardCond; m_sut.attachCondition(guardCond); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &guardCond); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; guardCond.setTrigger(); waiter.join(); m_sut.detachCondition(guardCond); } TEST_F(WaitSet_test, NotifyGuardConditionOnceTimedWaitResultsInResetOfTrigger) { GuardCondition guardCond; m_sut.attachCondition(guardCond); guardCond.setTrigger(); auto fulfilledConditions1 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions1.size(), Eq(1)); EXPECT_THAT(fulfilledConditions1.front(), &guardCond); guardCond.resetTrigger(); auto fulfilledConditions2 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions2.size(), Eq(0)); m_sut.detachCondition(guardCond); } <commit_msg>iox-#25 Another try to fix AttachConditionAndDestroyResultsInLifetimeFailure<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iceoryx_posh/internal/popo/building_blocks/condition_variable_data.hpp" #include "iceoryx_posh/popo/condition.hpp" #include "iceoryx_posh/popo/guard_condition.hpp" #include "iceoryx_posh/popo/wait_set.hpp" #include "iceoryx_utils/cxx/vector.hpp" #include "test.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::popo; using namespace iox::cxx; using namespace iox::units::duration_literals; class MockSubscriber : public Condition { public: bool setConditionVariable(ConditionVariableData* const ConditionVariableDataPtr) noexcept override { m_condVarPtr = ConditionVariableDataPtr; return true; } bool hasTriggered() const noexcept override { return m_wasTriggered; } bool unsetConditionVariable() noexcept override { m_condVarPtr = nullptr; return true; } /// @note done in ChunkQueuePusher void notify() { // We don't need to check if the WaitSet is still alive as it follows RAII and will inform every Condition about // a possible destruction m_wasTriggered = true; ConditionVariableSignaler signaler{m_condVarPtr}; signaler.notifyOne(); } /// @note members reside in ChunkQueueData in SHM bool m_wasTriggered{false}; ConditionVariableData* m_condVarPtr{nullptr}; }; class WaitSet_test : public Test { public: ConditionVariableData m_condVarData; WaitSet m_sut{&m_condVarData}; vector<MockSubscriber, iox::MAX_NUMBER_OF_CONDITIONS> m_subscriberVector; iox::posix::Semaphore m_syncSemaphore = iox::posix::Semaphore::create(0u).get_value(); void SetUp() { MockSubscriber subscriber; while (m_subscriberVector.size() != m_subscriberVector.capacity()) { m_subscriberVector.push_back(subscriber); } }; void TearDown() { m_sut.detachAllConditions(); m_subscriberVector.clear(); ConditionVariableWaiter waiter{&m_condVarData}; waiter.reset(); }; }; TEST_F(WaitSet_test, AttachSingleConditionSuccessful) { EXPECT_FALSE(m_sut.attachCondition(m_subscriberVector.front()).has_error()); } TEST_F(WaitSet_test, AttachSameConditionTwiceResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_THAT(m_sut.attachCondition(m_subscriberVector.front()).get_error(), Eq(WaitSetError::CONDITION_VARIABLE_ALREADY_SET)); } TEST_F(WaitSet_test, AttachConditionAndDestroyResultsInLifetimeFailure) { auto errorHandlerCalled{false}; iox::Error receivedError; WaitSet* m_sut2 = static_cast<WaitSet*>(malloc(sizeof(WaitSet))); new (m_sut2) WaitSet{&m_condVarData}; auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler( [&errorHandlerCalled, &receivedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel) { errorHandlerCalled = true; receivedError = error; }); { MockSubscriber scopedCondition; m_sut2->attachCondition(scopedCondition); } EXPECT_TRUE(errorHandlerCalled); EXPECT_THAT(receivedError, Eq(iox::Error::kPOPO__WAITSET_CONDITION_LIFETIME_ISSUE)); free(m_sut2); } TEST_F(WaitSet_test, AttachConditionAndDestroyWaitSetResultsInDetach) { { WaitSet m_sut2{&m_condVarData}; m_sut2.attachCondition(m_subscriberVector.front()); } EXPECT_FALSE(m_subscriberVector.front().isConditionVariableAttached()); } /// @todo Add test cases for move c'tor and move assignment TEST_F(WaitSet_test, AttachMaximumAllowedConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { EXPECT_FALSE(m_sut.attachCondition(currentSubscriber).has_error()); } } TEST_F(WaitSet_test, AttachTooManyConditionsResultsInFailure) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } MockSubscriber extraCondition; EXPECT_THAT(m_sut.attachCondition(extraCondition).get_error(), Eq(WaitSetError::CONDITION_VECTOR_OVERFLOW)); } TEST_F(WaitSet_test, DetachSingleConditionSuccessful) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_TRUE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachMultipleConditionsSuccessful) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); } for (auto& currentSubscriber : m_subscriberVector) { EXPECT_TRUE(m_sut.detachCondition(currentSubscriber)); } } TEST_F(WaitSet_test, DetachConditionNotInListResultsInFailure) { EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.front())); } TEST_F(WaitSet_test, DetachUnknownConditionResultsInFailure) { m_sut.attachCondition(m_subscriberVector.front()); EXPECT_FALSE(m_sut.detachCondition(m_subscriberVector.back())); } TEST_F(WaitSet_test, AttachConditionInTwoWaitSetsResultsInAlreadySetError) { WaitSet m_sut2{&m_condVarData}; m_sut.attachCondition(m_subscriberVector.front()); EXPECT_THAT(m_sut2.attachCondition(m_subscriberVector.front()).get_error(), Eq(WaitSetError::CONDITION_VARIABLE_ALREADY_SET)); } TEST_F(WaitSet_test, TimedWaitWithInvalidTimeResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(0_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, NoAttachTimedWaitResultsInEmptyVector) { auto emptyVector = m_sut.timedWait(1_ms); EXPECT_TRUE(emptyVector.empty()); } TEST_F(WaitSet_test, TimedWaitWithMaximumNumberOfConditionsResultsInReturnOfMaximumNumberOfConditions) { for (auto& currentSubscriber : m_subscriberVector) { m_sut.attachCondition(currentSubscriber); currentSubscriber.notify(); } auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(iox::MAX_NUMBER_OF_CONDITIONS)); } TEST_F(WaitSet_test, TimedWaitWithNotificationResultsInImmediateTrigger) { m_sut.attachCondition(m_subscriberVector.front()); m_subscriberVector.front().notify(); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); } TEST_F(WaitSet_test, TimeoutOfTimedWaitResultsInEmptyVector) { m_sut.attachCondition(m_subscriberVector.front()); auto fulfilledConditions = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions.size(), Eq(0)); } TEST_F(WaitSet_test, NotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector.front()); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyOneWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &m_subscriberVector[0]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector[0].notify(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyManyBeforeWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); m_syncSemaphore.wait(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; m_syncSemaphore.post(); waiter.join(); } TEST_F(WaitSet_test, AttachManyNotifyManyWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector[0]); m_sut.attachCondition(m_subscriberVector[1]); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(2)); EXPECT_THAT(fulfilledConditions[0], &m_subscriberVector[0]); EXPECT_THAT(fulfilledConditions[1], &m_subscriberVector[1]); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); m_subscriberVector[0].notify(); m_subscriberVector[1].notify(); counter++; waiter.join(); } TEST_F(WaitSet_test, WaitWithoutNotifyResultsInBlockingMultiThreaded) { std::atomic<int> counter{0}; m_sut.attachCondition(m_subscriberVector.front()); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); m_sut.wait(); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; m_subscriberVector.front().notify(); waiter.join(); } TEST_F(WaitSet_test, NotifyGuardConditionWhileWaitingResultsInTriggerMultiThreaded) { std::atomic<int> counter{0}; GuardCondition guardCond; m_sut.attachCondition(guardCond); std::thread waiter([&] { EXPECT_THAT(counter, Eq(0)); m_syncSemaphore.post(); auto fulfilledConditions = m_sut.wait(); EXPECT_THAT(fulfilledConditions.size(), Eq(1)); EXPECT_THAT(fulfilledConditions.front(), &guardCond); EXPECT_THAT(counter, Eq(1)); }); m_syncSemaphore.wait(); counter++; guardCond.setTrigger(); waiter.join(); m_sut.detachCondition(guardCond); } TEST_F(WaitSet_test, NotifyGuardConditionOnceTimedWaitResultsInResetOfTrigger) { GuardCondition guardCond; m_sut.attachCondition(guardCond); guardCond.setTrigger(); auto fulfilledConditions1 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions1.size(), Eq(1)); EXPECT_THAT(fulfilledConditions1.front(), &guardCond); guardCond.resetTrigger(); auto fulfilledConditions2 = m_sut.timedWait(1_ms); EXPECT_THAT(fulfilledConditions2.size(), Eq(0)); m_sut.detachCondition(guardCond); } <|endoftext|>
<commit_before>// // Copyright (c) 2008-2014 the Urho3D project. // // 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 "Precompiled.h" #include "Context.h" #include "Scene.h" #include "Sprite2D.h" #include "StaticSprite2D.h" #include "Texture2D.h" #include "DebugNew.h" namespace Urho3D { extern const char* URHO2D_CATEGORY; StaticSprite2D::StaticSprite2D(Context* context) : Drawable2D(context), flipX_(false), flipY_(false), color_(Color::WHITE), useHotSpot_(false), hotSpot_(0.5f, 0.5f) { vertices_.Reserve(6); } StaticSprite2D::~StaticSprite2D() { } void StaticSprite2D::RegisterObject(Context* context) { context->RegisterFactory<StaticSprite2D>(URHO2D_CATEGORY); MIXED_ACCESSOR_ATTRIBUTE("Sprite", GetSpriteAttr, SetSpriteAttr, ResourceRef, ResourceRef(Sprite2D::GetTypeStatic()), AM_DEFAULT); ACCESSOR_ATTRIBUTE("Flip X", GetFlipX, SetFlipX, bool, false, AM_DEFAULT); ACCESSOR_ATTRIBUTE("Flip Y", GetFlipY, SetFlipY, bool, false, AM_DEFAULT); ACCESSOR_ATTRIBUTE("Color", GetColor, SetColor, Color, Color::WHITE, AM_DEFAULT); COPY_BASE_ATTRIBUTES(Drawable2D); } void StaticSprite2D::SetSprite(Sprite2D* sprite) { if (sprite == sprite_) return; sprite_ = sprite; SetTexture(sprite_ ? sprite_->GetTexture() : 0); } void StaticSprite2D::SetFlip(bool flipX, bool flipY) { if (flipX == flipX_ && flipY == flipY_) return; flipX_ = flipX; flipY_ = flipY; verticesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetFlipX(bool flipX) { SetFlip(flipX, flipY_); } void StaticSprite2D::SetFlipY(bool flipY) { SetFlip(flipX_, flipY); } void StaticSprite2D::SetColor(const Color& color) { if (color == color_) return; color_ = color; verticesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetUseHotSpot(bool useHotSpot) { if (useHotSpot == useHotSpot_) return; useHotSpot_ = useHotSpot; verticesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetHotSpot(const Vector2& hotspot) { if (hotspot == hotSpot_) return; hotSpot_ = hotspot; if (useHotSpot_) { verticesDirty_ = true; MarkNetworkUpdate(); } } Sprite2D* StaticSprite2D::GetSprite() const { return sprite_; } void StaticSprite2D::SetSpriteAttr(const ResourceRef& value) { Sprite2D* sprite = Sprite2D::LoadFromResourceRef(this, value); if (sprite) SetSprite(sprite); } ResourceRef StaticSprite2D::GetSpriteAttr() const { return Sprite2D::SaveToResourceRef(sprite_); } void StaticSprite2D::OnWorldBoundingBoxUpdate() { boundingBox_.Clear(); if (sprite_) { const IntRect& rectangle_ = sprite_->GetRectangle(); float width = (float)rectangle_.Width() * PIXEL_SIZE; // Compute width and height in pixels float height = (float)rectangle_.Height() * PIXEL_SIZE; const Vector2& hotSpot = sprite_->GetHotSpot(); float hotSpotX = flipX_ ? (1.0f - hotSpot.x_) : hotSpot.x_; float hotSpotY = flipY_ ? (1.0f - hotSpot.y_) : hotSpot.y_; float leftX = -width * hotSpotX; float rightX = width * (1.0f - hotSpotX); float bottomY = -height * hotSpotY; float topY = height * (1.0f - hotSpotY); boundingBox_.Merge(Vector3(leftX, bottomY, 0.0f)); boundingBox_.Merge(Vector3(rightX, topY, 0.0f)); } worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform()); } void StaticSprite2D::UpdateVertices() { if (!verticesDirty_) return; vertices_.Clear(); Texture2D* texture = GetTexture(); if (!texture) return; const IntRect& rectangle_ = sprite_->GetRectangle(); if (rectangle_.Width() == 0 || rectangle_.Height() == 0) return; /* V1---------V2 | / | | / | | / | | / | | / | V0---------V3 */ Vertex2D vertex0; Vertex2D vertex1; Vertex2D vertex2; Vertex2D vertex3; float width = (float)rectangle_.Width() * PIXEL_SIZE; // Compute width and height in pixels float height = (float)rectangle_.Height() * PIXEL_SIZE; float hotSpotX; float hotSpotY; if (useHotSpot_) { hotSpotX = flipX_ ? (1.0f - hotSpot_.x_) : hotSpot_.x_; hotSpotY = flipY_ ? (1.0f - hotSpot_.y_) : hotSpot_.y_; } else { const Vector2& hotSpot = sprite_->GetHotSpot(); hotSpotX = flipX_ ? (1.0f - hotSpot.x_) : hotSpot.x_; hotSpotY = flipY_ ? (1.0f - hotSpot.y_) : hotSpot.y_; } #ifdef URHO3D_OPENGL float leftX = -width * hotSpotX; float rightX = width * (1.0f - hotSpotX); float bottomY = -height * hotSpotY; float topY = height * (1.0f - hotSpotY); #else const float halfPixelOffset = 0.5f * PIXEL_SIZE; float leftX = -width * hotSpotX + halfPixelOffset; float rightX = width * (1.0f - hotSpotX) + halfPixelOffset; float bottomY = -height * hotSpotY + halfPixelOffset; float topY = height * (1.0f - hotSpotY) + halfPixelOffset; #endif const Matrix3x4& worldTransform = node_->GetWorldTransform(); vertex0.position_ = worldTransform * Vector3(leftX, bottomY, 0.0f); vertex1.position_ = worldTransform * Vector3(leftX, topY, 0.0f); vertex2.position_ = worldTransform * Vector3(rightX, topY, 0.0f); vertex3.position_ = worldTransform * Vector3(rightX, bottomY, 0.0f); float invTexW = 1.0f / (float)texture->GetWidth(); float invTexH = 1.0f / (float)texture->GetHeight(); float leftU = rectangle_.left_ * invTexW; float rightU = rectangle_.right_ * invTexW; float topV = rectangle_.top_ * invTexH; float bottomV = rectangle_.bottom_ * invTexH; vertex0.uv_ = Vector2(leftU, bottomV); vertex1.uv_ = Vector2(leftU, topV); vertex2.uv_ = Vector2(rightU, topV); vertex3.uv_ = Vector2(rightU, bottomV); if (flipX_) { Swap(vertex0.uv_.x_, vertex3.uv_.x_); Swap(vertex1.uv_.x_, vertex2.uv_.x_); } if (flipY_) { Swap(vertex0.uv_.y_, vertex1.uv_.y_); Swap(vertex2.uv_.y_, vertex3.uv_.y_); } vertex0.color_ = vertex1.color_ = vertex2.color_ = vertex3.color_ = color_.ToUInt(); vertices_.Push(vertex0); vertices_.Push(vertex1); vertices_.Push(vertex2); vertices_.Push(vertex3); verticesDirty_ = false; } } <commit_msg>When setting a new sprite, have to mark vertices dirty to pick up changes in rectangle, hotspot, etc<commit_after>// // Copyright (c) 2008-2014 the Urho3D project. // // 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 "Precompiled.h" #include "Context.h" #include "Scene.h" #include "Sprite2D.h" #include "StaticSprite2D.h" #include "Texture2D.h" #include "DebugNew.h" namespace Urho3D { extern const char* URHO2D_CATEGORY; StaticSprite2D::StaticSprite2D(Context* context) : Drawable2D(context), flipX_(false), flipY_(false), color_(Color::WHITE), useHotSpot_(false), hotSpot_(0.5f, 0.5f) { vertices_.Reserve(6); } StaticSprite2D::~StaticSprite2D() { } void StaticSprite2D::RegisterObject(Context* context) { context->RegisterFactory<StaticSprite2D>(URHO2D_CATEGORY); MIXED_ACCESSOR_ATTRIBUTE("Sprite", GetSpriteAttr, SetSpriteAttr, ResourceRef, ResourceRef(Sprite2D::GetTypeStatic()), AM_DEFAULT); ACCESSOR_ATTRIBUTE("Flip X", GetFlipX, SetFlipX, bool, false, AM_DEFAULT); ACCESSOR_ATTRIBUTE("Flip Y", GetFlipY, SetFlipY, bool, false, AM_DEFAULT); ACCESSOR_ATTRIBUTE("Color", GetColor, SetColor, Color, Color::WHITE, AM_DEFAULT); COPY_BASE_ATTRIBUTES(Drawable2D); } void StaticSprite2D::SetSprite(Sprite2D* sprite) { if (sprite == sprite_) return; sprite_ = sprite; if (sprite) verticesDirty_ = true; SetTexture(sprite_ ? sprite_->GetTexture() : 0); } void StaticSprite2D::SetFlip(bool flipX, bool flipY) { if (flipX == flipX_ && flipY == flipY_) return; flipX_ = flipX; flipY_ = flipY; verticesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetFlipX(bool flipX) { SetFlip(flipX, flipY_); } void StaticSprite2D::SetFlipY(bool flipY) { SetFlip(flipX_, flipY); } void StaticSprite2D::SetColor(const Color& color) { if (color == color_) return; color_ = color; verticesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetUseHotSpot(bool useHotSpot) { if (useHotSpot == useHotSpot_) return; useHotSpot_ = useHotSpot; verticesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetHotSpot(const Vector2& hotspot) { if (hotspot == hotSpot_) return; hotSpot_ = hotspot; if (useHotSpot_) { verticesDirty_ = true; MarkNetworkUpdate(); } } Sprite2D* StaticSprite2D::GetSprite() const { return sprite_; } void StaticSprite2D::SetSpriteAttr(const ResourceRef& value) { Sprite2D* sprite = Sprite2D::LoadFromResourceRef(this, value); if (sprite) SetSprite(sprite); } ResourceRef StaticSprite2D::GetSpriteAttr() const { return Sprite2D::SaveToResourceRef(sprite_); } void StaticSprite2D::OnWorldBoundingBoxUpdate() { boundingBox_.Clear(); if (sprite_) { const IntRect& rectangle_ = sprite_->GetRectangle(); float width = (float)rectangle_.Width() * PIXEL_SIZE; // Compute width and height in pixels float height = (float)rectangle_.Height() * PIXEL_SIZE; const Vector2& hotSpot = sprite_->GetHotSpot(); float hotSpotX = flipX_ ? (1.0f - hotSpot.x_) : hotSpot.x_; float hotSpotY = flipY_ ? (1.0f - hotSpot.y_) : hotSpot.y_; float leftX = -width * hotSpotX; float rightX = width * (1.0f - hotSpotX); float bottomY = -height * hotSpotY; float topY = height * (1.0f - hotSpotY); boundingBox_.Merge(Vector3(leftX, bottomY, 0.0f)); boundingBox_.Merge(Vector3(rightX, topY, 0.0f)); } worldBoundingBox_ = boundingBox_.Transformed(node_->GetWorldTransform()); } void StaticSprite2D::UpdateVertices() { if (!verticesDirty_) return; vertices_.Clear(); Texture2D* texture = GetTexture(); if (!texture) return; const IntRect& rectangle_ = sprite_->GetRectangle(); if (rectangle_.Width() == 0 || rectangle_.Height() == 0) return; /* V1---------V2 | / | | / | | / | | / | | / | V0---------V3 */ Vertex2D vertex0; Vertex2D vertex1; Vertex2D vertex2; Vertex2D vertex3; float width = (float)rectangle_.Width() * PIXEL_SIZE; // Compute width and height in pixels float height = (float)rectangle_.Height() * PIXEL_SIZE; float hotSpotX; float hotSpotY; if (useHotSpot_) { hotSpotX = flipX_ ? (1.0f - hotSpot_.x_) : hotSpot_.x_; hotSpotY = flipY_ ? (1.0f - hotSpot_.y_) : hotSpot_.y_; } else { const Vector2& hotSpot = sprite_->GetHotSpot(); hotSpotX = flipX_ ? (1.0f - hotSpot.x_) : hotSpot.x_; hotSpotY = flipY_ ? (1.0f - hotSpot.y_) : hotSpot.y_; } #ifdef URHO3D_OPENGL float leftX = -width * hotSpotX; float rightX = width * (1.0f - hotSpotX); float bottomY = -height * hotSpotY; float topY = height * (1.0f - hotSpotY); #else const float halfPixelOffset = 0.5f * PIXEL_SIZE; float leftX = -width * hotSpotX + halfPixelOffset; float rightX = width * (1.0f - hotSpotX) + halfPixelOffset; float bottomY = -height * hotSpotY + halfPixelOffset; float topY = height * (1.0f - hotSpotY) + halfPixelOffset; #endif const Matrix3x4& worldTransform = node_->GetWorldTransform(); vertex0.position_ = worldTransform * Vector3(leftX, bottomY, 0.0f); vertex1.position_ = worldTransform * Vector3(leftX, topY, 0.0f); vertex2.position_ = worldTransform * Vector3(rightX, topY, 0.0f); vertex3.position_ = worldTransform * Vector3(rightX, bottomY, 0.0f); float invTexW = 1.0f / (float)texture->GetWidth(); float invTexH = 1.0f / (float)texture->GetHeight(); float leftU = rectangle_.left_ * invTexW; float rightU = rectangle_.right_ * invTexW; float topV = rectangle_.top_ * invTexH; float bottomV = rectangle_.bottom_ * invTexH; vertex0.uv_ = Vector2(leftU, bottomV); vertex1.uv_ = Vector2(leftU, topV); vertex2.uv_ = Vector2(rightU, topV); vertex3.uv_ = Vector2(rightU, bottomV); if (flipX_) { Swap(vertex0.uv_.x_, vertex3.uv_.x_); Swap(vertex1.uv_.x_, vertex2.uv_.x_); } if (flipY_) { Swap(vertex0.uv_.y_, vertex1.uv_.y_); Swap(vertex2.uv_.y_, vertex3.uv_.y_); } vertex0.color_ = vertex1.color_ = vertex2.color_ = vertex3.color_ = color_.ToUInt(); vertices_.Push(vertex0); vertices_.Push(vertex1); vertices_.Push(vertex2); vertices_.Push(vertex3); verticesDirty_ = false; } } <|endoftext|>
<commit_before>// MediaInfo_Internal - All info about media files // Copyright (C) 2002-2011 MediaArea.net SARL, Info@MediaArea.net // // This library is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library. If not, see <http://www.gnu.org/licenses/>. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // For user: you can disable or enable it //#define MEDIAINFO_DEBUG //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Compilation conditions #include "MediaInfo/Setup.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Reader/Reader_File.h" #include "MediaInfo/File__Analyze.h" #include "ZenLib/FileName.h" #ifdef WINDOWS #undef __TEXT #include "Windows.h" #endif WINDOWS using namespace ZenLib; using namespace std; //--------------------------------------------------------------------------- // Debug stuff #ifdef MEDIAINFO_DEBUG int64u Reader_File_Offset=0; int64u Reader_File_BytesRead_Total=0; int64u Reader_File_BytesRead=0; int64u Reader_File_Count=1; #include <iostream> #endif // MEDIAINFO_DEBUG //--------------------------------------------------------------------------- namespace MediaInfoLib { const size_t Buffer_NoJump=128*1024; //--------------------------------------------------------------------------- size_t Reader_File::Format_Test(MediaInfo_Internal* MI, const String &File_Name) { //std::cout<<Ztring(File_Name).To_Local().c_str()<<std::endl; #if MEDIAINFO_EVENTS { struct MediaInfo_Event_General_Start_0 Event; Event.EventCode=MediaInfo_EventCode_Create(MediaInfo_Parser_None, MediaInfo_Event_General_Start, 0); Event.Stream_Size=File::Size_Get(File_Name); MI->Config.Event_Send((const int8u*)&Event, sizeof(MediaInfo_Event_General_Start_0)); } #endif //MEDIAINFO_EVENTS //With Parser MultipleParsing /* MI->Open_Buffer_Init((int64u)-1, File_Name); if (Format_Test_PerParser(MI, File_Name)) return 1; return 0; //There is a problem */ //Get the Extension Ztring Extension=FileName::Extension_Get(File_Name); Extension.MakeLowerCase(); //Search the theorical format from extension InfoMap &FormatList=MediaInfoLib::Config.Format_Get(); InfoMap::iterator Format=FormatList.begin(); while (Format!=FormatList.end()) { const Ztring &Extensions=FormatList.Get(Format->first, InfoFormat_Extensions); if (Extensions.find(Extension)!=Error) { if(Extension.size()==Extensions.size()) break; //Only one extenion in the list if(Extensions.find(Extension+_T(" "))!=Error || Extensions.find(_T(" ")+Extension)!=Error) break; } Format++; } if (Format!=FormatList.end()) { const Ztring &Parser=Format->second(InfoFormat_Parser); if (MI->SelectFromExtension(Parser)) { //Test the theorical format if (Format_Test_PerParser(MI, File_Name)>0) return 1; } } size_t ToReturn=MI->ListFormats(File_Name); return ToReturn; } //--------------------------------------------------------------------------- size_t Reader_File::Format_Test_PerParser(MediaInfo_Internal* MI, const String &File_Name) { //Opening the file F.Open(File_Name); if (!F.Opened_Get()) return 0; //Info Status=0; FileSize_Current=F.Size_Get(); IsGrowing=false; //Partial file handling Ztring Config_Partial_Begin=MI->Config.File_Partial_Begin_Get(); if (!Config_Partial_Begin.empty() && Config_Partial_Begin[0]>=_T('0') && Config_Partial_Begin[0]<=_T('9')) { if (Config_Partial_Begin.find(_T('%'))==Config_Partial_Begin.size()-1) Partial_Begin=float64_int64s(FileSize_Current*Config_Partial_Begin.To_float64()/100); else Partial_Begin=Config_Partial_Begin.To_int64u(); if (Partial_Begin) F.GoTo(Partial_Begin); } else Partial_Begin=0; Ztring Config_Partial_End=MI->Config.File_Partial_End_Get(); if (!Config_Partial_End.empty() && Config_Partial_End[0]>=_T('0') && Config_Partial_End[0]<=_T('9')) { if (Config_Partial_End.find(_T('%'))==Config_Partial_End.size()-1) Partial_End=float64_int64s(FileSize_Current*Config_Partial_End.To_float64()/100); else Partial_End=Config_Partial_End.To_int64u(); } else Partial_End=FileSize_Current; if (Partial_Begin>FileSize_Current) Partial_Begin=0; //Wrong value if (Partial_End>FileSize_Current) Partial_End=FileSize_Current; //Wrong value if (Partial_Begin>Partial_End) { Partial_Begin=0; //Wrong value Partial_End=FileSize_Current; //Wrong value } //Parser MI->Open_Buffer_Init(Partial_End-Partial_Begin, File_Name); //Buffer MI->Option(_T("File_Buffer_Size_Hint_Pointer"), Ztring::ToZtring((size_t)(&MI->Config.File_Buffer_Size_ToRead))); //Test the format with buffer return Format_Test_PerParser_Continue(MI); } //--------------------------------------------------------------------------- size_t Reader_File::Format_Test_PerParser_Continue (MediaInfo_Internal* MI) { bool StopAfterFilled=MI->Config.File_StopAfterFilled_Get(); bool ShouldContinue=true; //Previous data if (MI->Config.File_Buffer_Repeat) { MI->Config.File_Buffer_Repeat=false; #if MEDIAINFO_DEMUX MI->Config.Demux_EventWasSent=false; #endif //MEDIAINFO_DEMUX Status=MI->Open_Buffer_Continue(MI->Config.File_Buffer, MI->Config.File_Buffer_Size); #if MEDIAINFO_DEMUX //Demux if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX //Threading if (MI->IsTerminating()) return 1; //Termination is requested if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled])) ShouldContinue=false; } #if MEDIAINFO_DEMUX //PerPacket if (ShouldContinue && MI->Config.Demux_EventWasSent) { MI->Config.Demux_EventWasSent=false; Status=MI->Open_Buffer_Continue(NULL, 0); //Demux if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately //Threading if (MI->IsTerminating()) return 1; //Termination is requested if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled])) ShouldContinue=false; } #endif //MEDIAINFO_DEMUX if (ShouldContinue) { //Test the format with buffer while (!(Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))) { //Seek (if needed) if (MI->Open_Buffer_Continue_GoTo_Get()!=(int64u)-1) { #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl; Reader_File_Offset=MI->Open_Buffer_Continue_GoTo_Get(); Reader_File_BytesRead=0; Reader_File_Count++; #endif //MEDIAINFO_DEBUG if (MI->Open_Buffer_Continue_GoTo_Get()>=F.Size_Get()) break; //Seek requested, but on a file bigger in theory than what is in the real file, we can't do this if (!(MI->Open_Buffer_Continue_GoTo_Get()>F.Position_Get() && MI->Open_Buffer_Continue_GoTo_Get()<F.Position_Get()+Buffer_NoJump)) //No smal jumps { if (!F.GoTo(Partial_Begin+MI->Open_Buffer_Continue_GoTo_Get())) break; //File is not seekable MI->Open_Buffer_Init((int64u)-1, F.Position_Get()-Partial_Begin); } } //Handling of hints if (MI->Config.File_Buffer_Size_ToRead==0) break; //Problem while config if (MI->Config.File_Buffer_Size_ToRead>MI->Config.File_Buffer_Size_Max) { delete[] MI->Config.File_Buffer; if (MI->Config.File_Buffer_Size_Max==0) MI->Config.File_Buffer_Size_Max=1; while (MI->Config.File_Buffer_Size_ToRead>MI->Config.File_Buffer_Size_Max) MI->Config.File_Buffer_Size_Max*=2; MI->Config.File_Buffer=new int8u[MI->Config.File_Buffer_Size_Max]; } MI->Config.File_Buffer_Size=F.Read(MI->Config.File_Buffer, (F.Position_Get()+MI->Config.File_Buffer_Size_ToRead<Partial_End)?MI->Config.File_Buffer_Size_ToRead:((size_t)(Partial_End-F.Position_Get()))); if (MI->Config.File_Buffer_Size==0) break; //Problem while reading //Testing growing files if (!IsGrowing && F.Position_Get()>=FileSize_Current) { if (MediaInfoLib::Config.ParseSpeed_Get()>=1.0) //Only if full parsing { int64u FileSize_New=F.Size_Get(); if (FileSize_Current!=FileSize_New) IsGrowing=true; } } if (IsGrowing && F.Position_Get()>=FileSize_Current) { for (size_t CountOfSeconds=0; CountOfSeconds<10; CountOfSeconds++) { int64u FileSize_New=F.Size_Get(); if (FileSize_Current!=FileSize_New) { Partial_End=FileSize_Current=FileSize_New; MI->Open_Buffer_Init(FileSize_Current, F.Position_Get()-MI->Config.File_Buffer_Size); break; } #ifdef WINDOWS Sleep(1000); #endif //WINDOWS } } #ifdef MEDIAINFO_DEBUG Reader_File_BytesRead_Total+=MI->Config.File_Buffer_Size; Reader_File_BytesRead+=MI->Config.File_Buffer_Size; #endif //MEDIAINFO_DEBUG //Parser Status=MI->Open_Buffer_Continue(MI->Config.File_Buffer, MI->Config.File_Buffer_Size); #if MEDIAINFO_DEMUX if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX //Threading if (MI->IsTerminating()) break; //Termination is requested } if (F.Size_Get()==0) //If Size==0, Status is never updated Status=MI->Open_Buffer_Continue(NULL, 0); } #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl; std::cout<<"Total: "<<std::dec<<Reader_File_BytesRead_Total<<" bytes in "<<Reader_File_Count<<" blocks"<<std::endl; #endif //MEDIAINFO_DEBUG if (MI==NULL || !MI->Config.File_KeepInfo_Get()) { //File F.Close(); } //Is this file detected? if (!Status[File__Analyze::IsAccepted]) return 0; MI->Open_Buffer_Finalize(); #if MEDIAINFO_DEMUX if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX return 1; } //--------------------------------------------------------------------------- #if MEDIAINFO_SEEK size_t Reader_File::Format_Test_PerParser_Seek (MediaInfo_Internal* MI, size_t Method, int64u Value, int64u ID) { size_t ToReturn=MI->Open_Buffer_Seek(Method, Value, ID); if (ToReturn==0 || ToReturn==1) { //Reset Status=0; } return ToReturn; } #endif //MEDIAINFO_SEEK } //NameSpace <commit_msg><commit_after>// MediaInfo_Internal - All info about media files // Copyright (C) 2002-2011 MediaArea.net SARL, Info@MediaArea.net // // This library is free software: you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library. If not, see <http://www.gnu.org/licenses/>. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // For user: you can disable or enable it //#define MEDIAINFO_DEBUG //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Compilation conditions #include "MediaInfo/Setup.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Reader/Reader_File.h" #include "MediaInfo/File__Analyze.h" #include "ZenLib/FileName.h" #ifdef WINDOWS #undef __TEXT #include "Windows.h" #endif WINDOWS using namespace ZenLib; using namespace std; //--------------------------------------------------------------------------- // Debug stuff #ifdef MEDIAINFO_DEBUG int64u Reader_File_Offset=0; int64u Reader_File_BytesRead_Total=0; int64u Reader_File_BytesRead=0; int64u Reader_File_Count=1; #endif // MEDIAINFO_DEBUG #include <iostream> //--------------------------------------------------------------------------- namespace MediaInfoLib { const size_t Buffer_NoJump=128*1024; //--------------------------------------------------------------------------- size_t Reader_File::Format_Test(MediaInfo_Internal* MI, const String &File_Name) { std::cout<<Ztring(File_Name).To_Local().c_str()<<std::endl; #if MEDIAINFO_EVENTS { struct MediaInfo_Event_General_Start_0 Event; Event.EventCode=MediaInfo_EventCode_Create(MediaInfo_Parser_None, MediaInfo_Event_General_Start, 0); Event.Stream_Size=File::Size_Get(File_Name); MI->Config.Event_Send((const int8u*)&Event, sizeof(MediaInfo_Event_General_Start_0)); } #endif //MEDIAINFO_EVENTS //With Parser MultipleParsing /* MI->Open_Buffer_Init((int64u)-1, File_Name); if (Format_Test_PerParser(MI, File_Name)) return 1; return 0; //There is a problem */ //Get the Extension Ztring Extension=FileName::Extension_Get(File_Name); Extension.MakeLowerCase(); //Search the theorical format from extension InfoMap &FormatList=MediaInfoLib::Config.Format_Get(); InfoMap::iterator Format=FormatList.begin(); while (Format!=FormatList.end()) { const Ztring &Extensions=FormatList.Get(Format->first, InfoFormat_Extensions); if (Extensions.find(Extension)!=Error) { if(Extension.size()==Extensions.size()) break; //Only one extenion in the list if(Extensions.find(Extension+_T(" "))!=Error || Extensions.find(_T(" ")+Extension)!=Error) break; } Format++; } if (Format!=FormatList.end()) { const Ztring &Parser=Format->second(InfoFormat_Parser); if (MI->SelectFromExtension(Parser)) { //Test the theorical format if (Format_Test_PerParser(MI, File_Name)>0) return 1; } } size_t ToReturn=MI->ListFormats(File_Name); return ToReturn; } //--------------------------------------------------------------------------- size_t Reader_File::Format_Test_PerParser(MediaInfo_Internal* MI, const String &File_Name) { //Opening the file F.Open(File_Name); if (!F.Opened_Get()) return 0; //Info Status=0; FileSize_Current=F.Size_Get(); IsGrowing=false; //Partial file handling Ztring Config_Partial_Begin=MI->Config.File_Partial_Begin_Get(); if (!Config_Partial_Begin.empty() && Config_Partial_Begin[0]>=_T('0') && Config_Partial_Begin[0]<=_T('9')) { if (Config_Partial_Begin.find(_T('%'))==Config_Partial_Begin.size()-1) Partial_Begin=float64_int64s(FileSize_Current*Config_Partial_Begin.To_float64()/100); else Partial_Begin=Config_Partial_Begin.To_int64u(); if (Partial_Begin) F.GoTo(Partial_Begin); } else Partial_Begin=0; Ztring Config_Partial_End=MI->Config.File_Partial_End_Get(); if (!Config_Partial_End.empty() && Config_Partial_End[0]>=_T('0') && Config_Partial_End[0]<=_T('9')) { if (Config_Partial_End.find(_T('%'))==Config_Partial_End.size()-1) Partial_End=float64_int64s(FileSize_Current*Config_Partial_End.To_float64()/100); else Partial_End=Config_Partial_End.To_int64u(); } else Partial_End=FileSize_Current; if (Partial_Begin>FileSize_Current) Partial_Begin=0; //Wrong value if (Partial_End>FileSize_Current) Partial_End=FileSize_Current; //Wrong value if (Partial_Begin>Partial_End) { Partial_Begin=0; //Wrong value Partial_End=FileSize_Current; //Wrong value } //Parser MI->Open_Buffer_Init(Partial_End-Partial_Begin, File_Name); //Buffer MI->Option(_T("File_Buffer_Size_Hint_Pointer"), Ztring::ToZtring((size_t)(&MI->Config.File_Buffer_Size_ToRead))); //Test the format with buffer return Format_Test_PerParser_Continue(MI); } //--------------------------------------------------------------------------- size_t Reader_File::Format_Test_PerParser_Continue (MediaInfo_Internal* MI) { bool StopAfterFilled=MI->Config.File_StopAfterFilled_Get(); bool ShouldContinue=true; //Previous data if (MI->Config.File_Buffer_Repeat) { MI->Config.File_Buffer_Repeat=false; #if MEDIAINFO_DEMUX MI->Config.Demux_EventWasSent=false; #endif //MEDIAINFO_DEMUX Status=MI->Open_Buffer_Continue(MI->Config.File_Buffer, MI->Config.File_Buffer_Size); #if MEDIAINFO_DEMUX //Demux if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX //Threading if (MI->IsTerminating()) return 1; //Termination is requested if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled])) ShouldContinue=false; } #if MEDIAINFO_DEMUX //PerPacket if (ShouldContinue && MI->Config.Demux_EventWasSent) { MI->Config.Demux_EventWasSent=false; Status=MI->Open_Buffer_Continue(NULL, 0); //Demux if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately //Threading if (MI->IsTerminating()) return 1; //Termination is requested if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled])) ShouldContinue=false; } #endif //MEDIAINFO_DEMUX if (ShouldContinue) { //Test the format with buffer while (!(Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))) { //Seek (if needed) if (MI->Open_Buffer_Continue_GoTo_Get()!=(int64u)-1) { #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl; Reader_File_Offset=MI->Open_Buffer_Continue_GoTo_Get(); Reader_File_BytesRead=0; Reader_File_Count++; #endif //MEDIAINFO_DEBUG if (MI->Open_Buffer_Continue_GoTo_Get()>=F.Size_Get()) break; //Seek requested, but on a file bigger in theory than what is in the real file, we can't do this if (!(MI->Open_Buffer_Continue_GoTo_Get()>F.Position_Get() && MI->Open_Buffer_Continue_GoTo_Get()<F.Position_Get()+Buffer_NoJump)) //No smal jumps { if (!F.GoTo(Partial_Begin+MI->Open_Buffer_Continue_GoTo_Get())) break; //File is not seekable MI->Open_Buffer_Init((int64u)-1, F.Position_Get()-Partial_Begin); } } //Handling of hints if (MI->Config.File_Buffer_Size_ToRead==0) break; //Problem while config if (MI->Config.File_Buffer_Size_ToRead>MI->Config.File_Buffer_Size_Max) { delete[] MI->Config.File_Buffer; if (MI->Config.File_Buffer_Size_Max==0) MI->Config.File_Buffer_Size_Max=1; while (MI->Config.File_Buffer_Size_ToRead>MI->Config.File_Buffer_Size_Max) MI->Config.File_Buffer_Size_Max*=2; MI->Config.File_Buffer=new int8u[MI->Config.File_Buffer_Size_Max]; } MI->Config.File_Buffer_Size=F.Read(MI->Config.File_Buffer, (F.Position_Get()+MI->Config.File_Buffer_Size_ToRead<Partial_End)?MI->Config.File_Buffer_Size_ToRead:((size_t)(Partial_End-F.Position_Get()))); //Testing growing files if (!IsGrowing && F.Position_Get()>=FileSize_Current) { if (MediaInfoLib::Config.ParseSpeed_Get()>=1.0) //Only if full parsing { int64u FileSize_New=F.Size_Get(); if (FileSize_Current!=FileSize_New) IsGrowing=true; } } if (IsGrowing && F.Position_Get()>=FileSize_Current) { for (size_t CountOfSeconds=0; CountOfSeconds<10; CountOfSeconds++) { int64u FileSize_New=F.Size_Get(); if (FileSize_Current!=FileSize_New) { Partial_End=FileSize_Current=FileSize_New; MI->Open_Buffer_Init(FileSize_Current, F.Position_Get()-MI->Config.File_Buffer_Size); break; } #ifdef WINDOWS Sleep(1000); #endif //WINDOWS } } #ifdef MEDIAINFO_DEBUG Reader_File_BytesRead_Total+=MI->Config.File_Buffer_Size; Reader_File_BytesRead+=MI->Config.File_Buffer_Size; #endif //MEDIAINFO_DEBUG //Parser Status=MI->Open_Buffer_Continue(MI->Config.File_Buffer, MI->Config.File_Buffer_Size); if (MI->Config.File_Buffer_Size==0) break; #if MEDIAINFO_DEMUX if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX //Threading if (MI->IsTerminating()) break; //Termination is requested } } #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl; std::cout<<"Total: "<<std::dec<<Reader_File_BytesRead_Total<<" bytes in "<<Reader_File_Count<<" blocks"<<std::endl; #endif //MEDIAINFO_DEBUG if (MI==NULL || !MI->Config.File_KeepInfo_Get()) { //File F.Close(); } //Is this file detected? if (!Status[File__Analyze::IsAccepted]) return 0; MI->Open_Buffer_Finalize(); #if MEDIAINFO_DEMUX if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX return 1; } //--------------------------------------------------------------------------- #if MEDIAINFO_SEEK size_t Reader_File::Format_Test_PerParser_Seek (MediaInfo_Internal* MI, size_t Method, int64u Value, int64u ID) { size_t ToReturn=MI->Open_Buffer_Seek(Method, Value, ID); if (ToReturn==0 || ToReturn==1) { //Reset Status=0; } return ToReturn; } #endif //MEDIAINFO_SEEK } //NameSpace <|endoftext|>
<commit_before>/****************************************************************************************/ /* */ /* Pegasus */ /* */ /****************************************************************************************/ //! \file RenderContext.cpp //! \author David Worsham //! \date 5th July 2013 //! \brief Class that encapsulates an OGL rendering context. #include "Pegasus/Render/RenderContext.h" #include <windows.h> #define GLEW_STATIC 1 #include "Pegasus/Libs/GLEW/glew.h" #include "Pegasus/Libs/GLEW/wglew.h" namespace Pegasus { namespace Render { // Global pixel format descriptor for RGBA 32-bits static PIXELFORMATDESCRIPTOR sPixelFormat = { sizeof(PIXELFORMATDESCRIPTOR), //! size of structure 1, //! default version PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //! flags PFD_TYPE_RGBA, //! RGBA color mode 32, //! 32 bit color mode 0, 0, 0, 0, 0, 0, //! ignore color bits 0, //! no alpha buffer 0, //! ignore shift bit 0, //! no accumulation buffer 0, 0, 0, 0, //! ignore accumulation bits 24, //! 24 bit z-buffer size 8, //! 8 bit stencil-buffer size 0, //! no aux buffer PFD_MAIN_PLANE, //! main drawing plane 0, //! reserved 0, 0, 0}; //! layer masks ignored //---------------------------------------------------------------------------------------- ContextConfig::ContextConfig() : mDeviceContextHandle(0), mStartupContext(false) { } //---------------------------------------------------------------------------------------- ContextConfig::~ContextConfig() { } //---------------------------------------------------------------------------------------- Context::Context(const ContextConfig& config) : mDeviceContextHandle(config.mDeviceContextHandle) { // Create context if (config.mStartupContext) { // Startup int nPixelFormat = ChoosePixelFormat((HDC) mDeviceContextHandle, &sPixelFormat); // Setup pixel format for backbuffer SetPixelFormat((HDC) mDeviceContextHandle, nPixelFormat, &sPixelFormat); // Make a new opengl context mRenderContextHandle = (RenderContextHandle) wglCreateContext((HDC) mDeviceContextHandle); } else { // Context attributes for OGL 4.3 const int sAttrib[8] = {WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB , 3, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0, 0}; //! \todo Assert on startup context created // Full context int nPixelFormat = ChoosePixelFormat((HDC) mDeviceContextHandle, &sPixelFormat); // Setup pixel format for backbuffer SetPixelFormat((HDC) mDeviceContextHandle, nPixelFormat, &sPixelFormat); // Make a new opengl context mRenderContextHandle = (RenderContextHandle) wglCreateContextAttribsARB((HDC) mDeviceContextHandle, 0, sAttrib); } // Link it to the window Bind(); } //---------------------------------------------------------------------------------------- Context::~Context() { // Unbind and destroy the context Unbind(); wglDeleteContext((HGLRC) mRenderContextHandle); } //---------------------------------------------------------------------------------------- void Context::Bind() const { wglMakeCurrent((HDC) mDeviceContextHandle, (HGLRC) mRenderContextHandle); } //---------------------------------------------------------------------------------------- void Context::Unbind() const { wglMakeCurrent((HDC) mDeviceContextHandle, NULL); } //---------------------------------------------------------------------------------------- void Context::Swap() const { // Present glFlush(); SwapBuffers((HDC) mDeviceContextHandle); } } // namespace Render } // namespace Pegasus <commit_msg>[RENDER] Removed the glFlush() that was not required.<commit_after>/****************************************************************************************/ /* */ /* Pegasus */ /* */ /****************************************************************************************/ //! \file RenderContext.cpp //! \author David Worsham //! \date 5th July 2013 //! \brief Class that encapsulates an OGL rendering context. #include "Pegasus/Render/RenderContext.h" #include <windows.h> #define GLEW_STATIC 1 #include "Pegasus/Libs/GLEW/glew.h" #include "Pegasus/Libs/GLEW/wglew.h" namespace Pegasus { namespace Render { // Global pixel format descriptor for RGBA 32-bits static PIXELFORMATDESCRIPTOR sPixelFormat = { sizeof(PIXELFORMATDESCRIPTOR), //! size of structure 1, //! default version PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //! flags PFD_TYPE_RGBA, //! RGBA color mode 32, //! 32 bit color mode 0, 0, 0, 0, 0, 0, //! ignore color bits 0, //! no alpha buffer 0, //! ignore shift bit 0, //! no accumulation buffer 0, 0, 0, 0, //! ignore accumulation bits 24, //! 24 bit z-buffer size 8, //! 8 bit stencil-buffer size 0, //! no aux buffer PFD_MAIN_PLANE, //! main drawing plane 0, //! reserved 0, 0, 0}; //! layer masks ignored //---------------------------------------------------------------------------------------- ContextConfig::ContextConfig() : mDeviceContextHandle(0), mStartupContext(false) { } //---------------------------------------------------------------------------------------- ContextConfig::~ContextConfig() { } //---------------------------------------------------------------------------------------- Context::Context(const ContextConfig& config) : mDeviceContextHandle(config.mDeviceContextHandle) { // Create context if (config.mStartupContext) { // Startup int nPixelFormat = ChoosePixelFormat((HDC) mDeviceContextHandle, &sPixelFormat); // Setup pixel format for backbuffer SetPixelFormat((HDC) mDeviceContextHandle, nPixelFormat, &sPixelFormat); // Make a new opengl context mRenderContextHandle = (RenderContextHandle) wglCreateContext((HDC) mDeviceContextHandle); } else { // Context attributes for OGL 4.3 const int sAttrib[8] = {WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB , 3, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0, 0}; //! \todo Assert on startup context created // Full context int nPixelFormat = ChoosePixelFormat((HDC) mDeviceContextHandle, &sPixelFormat); // Setup pixel format for backbuffer SetPixelFormat((HDC) mDeviceContextHandle, nPixelFormat, &sPixelFormat); // Make a new opengl context mRenderContextHandle = (RenderContextHandle) wglCreateContextAttribsARB((HDC) mDeviceContextHandle, 0, sAttrib); } // Link it to the window Bind(); } //---------------------------------------------------------------------------------------- Context::~Context() { // Unbind and destroy the context Unbind(); wglDeleteContext((HGLRC) mRenderContextHandle); } //---------------------------------------------------------------------------------------- void Context::Bind() const { wglMakeCurrent((HDC) mDeviceContextHandle, (HGLRC) mRenderContextHandle); } //---------------------------------------------------------------------------------------- void Context::Unbind() const { wglMakeCurrent((HDC) mDeviceContextHandle, NULL); } //---------------------------------------------------------------------------------------- void Context::Swap() const { // Present (no need for glFlush() since SwapBuffers() takes care of it) SwapBuffers((HDC) mDeviceContextHandle); } } // namespace Render } // namespace Pegasus <|endoftext|>
<commit_before>/*========================================================================= medInria Copyright (c) INRIA 2013 - 2014. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "medCompositeParameter.h" #include <QtGui> #include <QPair> class medCompositeParameterPrivate { public: QHash<QString, QVariant> variants; QHash<QString, QPair <QVariant, QVariant> > ranges; QHash<QString, QVariant> steps; QHash<QString, QWidget*> widgets; ~medCompositeParameterPrivate() { variants.clear(); QHashIterator<QString, QWidget*> i(widgets); while (i.hasNext()) { i.next(); delete i.value(); } widgets.clear(); } }; medCompositeParameter::medCompositeParameter(QString name, QObject* parent): medAbstractParameter(name, parent), d(new medCompositeParameterPrivate) { } medCompositeParameter::~medCompositeParameter() { delete d; } QWidget* medCompositeParameter::getWidget() { QWidget *mainWidget = new QWidget; QFormLayout *layout = new QFormLayout(mainWidget); QHash<QString, QWidget*>::const_iterator i = d->widgets.constBegin(); while (i != d->widgets.constEnd()) { layout->addRow(i.key(), i.value()); ++i; } return mainWidget; } void medCompositeParameter::setValues(const QHash<QString, QVariant> value) { QHash<QString, QVariant>::const_iterator valuesIterator = value.constBegin(); while (valuesIterator != value.constEnd()) { QString key = valuesIterator.key(); if (!d->variants.contains(key)) { valuesIterator++; continue; } if(d->variants[key].type() == QVariant::Double) { if(valuesIterator.value().toDouble() < d->ranges.value(key).first.toDouble()) d->variants[key] = d->ranges.value(key).first; else if(valuesIterator.value().toDouble() > d->ranges.value(key).second.toDouble()) d->variants[key] = d->ranges.value(key).second; else d->variants[key] = valuesIterator.value(); } else if(d->variants[key].type() == QVariant::Int) { if(valuesIterator.value().toInt() < d->ranges.value(key).first.toInt()) d->variants[key] = d->ranges.value(key).first; else if(valuesIterator.value().toInt() > d->ranges.value(key).second.toInt()) d->variants[key] = d->ranges.value(key).second; else d->variants[key] = valuesIterator.value(); } else d->variants[key] = valuesIterator.value(); valuesIterator++; } // update intern widget this->blockInternWidgetsSignals(true); this->updateInternWigets(); this->blockInternWidgetsSignals(false); emit valuesChanged(d->variants); } QList<QVariant> medCompositeParameter::values() const { return d->variants.values(); } void medCompositeParameter::updateInternWigets() { QHash<QString, QVariant>::const_iterator i = d->variants.constBegin(); while (i != d->variants.constEnd()) { QString name = i.key(); QVariant var = i.value(); QWidget* widget = d->widgets.value(name); if(QCheckBox *checkbox = qobject_cast<QCheckBox*>(widget)) checkbox->setChecked(var.toBool()); else if(QSpinBox *spinBox = qobject_cast<QSpinBox*>(widget)) spinBox->setValue(var.toInt()); else if(QDoubleSpinBox *doubleSpinBox = qobject_cast<QDoubleSpinBox*>(widget)) doubleSpinBox->setValue(var.toDouble()); ++i; } } void medCompositeParameter::addVariant(QString name, QVariant variant, QVariant min, QVariant max, QVariant step) { d->variants.insert(name, variant); if(variant.type() == QVariant::Bool) { QCheckBox *checkbox = new QCheckBox(name); d->widgets.insert(name, checkbox); this->addToInternWidgets(checkbox); connect(checkbox, SIGNAL(toggled(bool)), this, SLOT(updateValue(bool))); connect(checkbox, SIGNAL(destroyed(QObject*)), this, SLOT(removeInternWidget(QObject*))); } else if(variant.type() == QVariant::Int) { QSpinBox *spinbox = new QSpinBox; if(min != QVariant() && max != QVariant()) { spinbox->setMinimum(min.toInt()); spinbox->setMaximum(max.toInt()); d->ranges.insert(name, QPair<QVariant, QVariant>(min, max)); } if(step != QVariant()) { spinbox->setSingleStep(step.toInt()); d->steps.insert(name, step); } spinbox->setValue(variant.toInt()); d->widgets.insert(name, spinbox); this->addToInternWidgets(spinbox); connect(spinbox, SIGNAL(valueChanged(int)), this, SLOT(updateValue(int))); connect(spinbox, SIGNAL(destroyed(QObject*)), this, SLOT(removeInternWidget(QObject*))); } else if(variant.type() == QVariant::Double ) { QDoubleSpinBox *spinbox = new QDoubleSpinBox; if(min != QVariant() && max != QVariant()) { spinbox->setMinimum(min.toDouble()); spinbox->setMaximum(max.toDouble()); d->ranges.insert(name, QPair<QVariant, QVariant>(min, max)); } if(step != QVariant()) { spinbox->setSingleStep(step.toDouble()); d->steps.insert(name, step); } spinbox->setValue(variant.toDouble()); d->widgets.insert(name, spinbox); this->addToInternWidgets(spinbox); connect(spinbox, SIGNAL(valueChanged(double)), this, SLOT(updateValue(double))); connect(spinbox, SIGNAL(destroyed(QObject*)), this, SLOT(removeInternWidget(QObject*))); } //TODO: to complete with other QVariant types } void medCompositeParameter::updateValue(bool value) { QCheckBox *checkbox = qobject_cast<QCheckBox*>(QObject::sender()); if(checkbox) { QString name = d->widgets.key(checkbox); d->variants[name] = QVariant(value); emit valuesChanged(d->variants); } } void medCompositeParameter::updateValue(double value) { QDoubleSpinBox *spinbox = qobject_cast<QDoubleSpinBox*>(QObject::sender()); if(spinbox) { QString name = d->widgets.key(spinbox); d->variants[name] = QVariant(value); emit valuesChanged(d->variants); } } void medCompositeParameter::updateValue(int value) { QSpinBox *spinbox = qobject_cast<QSpinBox*>(QObject::sender()); if(spinbox) { QString name = d->widgets.key(spinbox); d->variants[name] = QVariant(value); emit valuesChanged(d->variants); } } void medCompositeParameter::removeInternWidget(QObject *widget) { QWidget *w = qobject_cast<QWidget*>(widget); if(!w) return; this->removeFromInternWidgets(w); QHashIterator<QString, QWidget*> i(d->widgets); while (i.hasNext()) { i.next(); if(w == i.value()) d->widgets.remove(i.key()); } } QList<QPair<QVariant, QVariant> > medCompositeParameter::ranges() const { return d->ranges.values(); } QList<QVariant> medCompositeParameter::steps() const { return d->steps.values(); } <commit_msg>bug corrected in medCompositeParameter<commit_after>/*========================================================================= medInria Copyright (c) INRIA 2013 - 2014. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "medCompositeParameter.h" #include <QtGui> #include <QPair> class medCompositeParameterPrivate { public: QHash<QString, QVariant> variants; QHash<QString, QPair <QVariant, QVariant> > ranges; QHash<QString, QVariant> steps; QHash<QString, QWidget*> widgets; ~medCompositeParameterPrivate() { variants.clear(); QHashIterator<QString, QWidget*> i(widgets); while (i.hasNext()) { i.next(); delete i.value(); } widgets.clear(); } }; medCompositeParameter::medCompositeParameter(QString name, QObject* parent): medAbstractParameter(name, parent), d(new medCompositeParameterPrivate) { } medCompositeParameter::~medCompositeParameter() { delete d; } QWidget* medCompositeParameter::getWidget() { QWidget *mainWidget = new QWidget; QFormLayout *layout = new QFormLayout(mainWidget); QHash<QString, QWidget*>::const_iterator i = d->widgets.constBegin(); while (i != d->widgets.constEnd()) { layout->addRow(i.key(), i.value()); ++i; } return mainWidget; } void medCompositeParameter::setValues(const QHash<QString, QVariant> value) { QHash<QString, QVariant>::const_iterator valuesIterator = value.constBegin(); bool valueUpdated = false; while (valuesIterator != value.constEnd()) { QString key = valuesIterator.key(); if (!d->variants.contains(key)) { valuesIterator++; continue; } if(d->variants[key].type() == QVariant::Double) { double previousValue = d->variants[key].toDouble(); if(valuesIterator.value().toDouble() < d->ranges.value(key).first.toDouble()) d->variants[key] = d->ranges.value(key).first; else if(valuesIterator.value().toDouble() > d->ranges.value(key).second.toDouble()) d->variants[key] = d->ranges.value(key).second; else d->variants[key] = valuesIterator.value(); if( previousValue != d->variants[key] ) valueUpdated = true; } else if(d->variants[key].type() == QVariant::Int) { int previousValue = d->variants[key].toInt(); if(valuesIterator.value().toInt() < d->ranges.value(key).first.toInt()) d->variants[key] = d->ranges.value(key).first; else if(valuesIterator.value().toInt() > d->ranges.value(key).second.toInt()) d->variants[key] = d->ranges.value(key).second; else d->variants[key] = valuesIterator.value(); if( previousValue != d->variants[key] ) valueUpdated = true; } else d->variants[key] = valuesIterator.value(); valuesIterator++; } if(!valueUpdated) return; // update intern widget this->blockInternWidgetsSignals(true); this->updateInternWigets(); this->blockInternWidgetsSignals(false); emit valuesChanged(d->variants); } QList<QVariant> medCompositeParameter::values() const { return d->variants.values(); } void medCompositeParameter::updateInternWigets() { QHash<QString, QVariant>::const_iterator i = d->variants.constBegin(); while (i != d->variants.constEnd()) { QString name = i.key(); QVariant var = i.value(); QWidget* widget = d->widgets.value(name); if(QCheckBox *checkbox = qobject_cast<QCheckBox*>(widget)) checkbox->setChecked(var.toBool()); else if(QSpinBox *spinBox = qobject_cast<QSpinBox*>(widget)) spinBox->setValue(var.toInt()); else if(QDoubleSpinBox *doubleSpinBox = qobject_cast<QDoubleSpinBox*>(widget)) doubleSpinBox->setValue(var.toDouble()); ++i; } } void medCompositeParameter::addVariant(QString name, QVariant variant, QVariant min, QVariant max, QVariant step) { d->variants.insert(name, variant); if(variant.type() == QVariant::Bool) { QCheckBox *checkbox = new QCheckBox(name); d->widgets.insert(name, checkbox); this->addToInternWidgets(checkbox); connect(checkbox, SIGNAL(toggled(bool)), this, SLOT(updateValue(bool))); connect(checkbox, SIGNAL(destroyed(QObject*)), this, SLOT(removeInternWidget(QObject*))); } else if(variant.type() == QVariant::Int) { QSpinBox *spinbox = new QSpinBox; if(min != QVariant() && max != QVariant()) { spinbox->setMinimum(min.toInt()); spinbox->setMaximum(max.toInt()); d->ranges.insert(name, QPair<QVariant, QVariant>(min, max)); } if(step != QVariant()) { spinbox->setSingleStep(step.toInt()); d->steps.insert(name, step); } spinbox->setValue(variant.toInt()); d->widgets.insert(name, spinbox); this->addToInternWidgets(spinbox); connect(spinbox, SIGNAL(valueChanged(int)), this, SLOT(updateValue(int))); connect(spinbox, SIGNAL(destroyed(QObject*)), this, SLOT(removeInternWidget(QObject*))); } else if(variant.type() == QVariant::Double ) { QDoubleSpinBox *spinbox = new QDoubleSpinBox; if(min != QVariant() && max != QVariant()) { spinbox->setMinimum(min.toDouble()); spinbox->setMaximum(max.toDouble()); d->ranges.insert(name, QPair<QVariant, QVariant>(min, max)); } if(step != QVariant()) { spinbox->setSingleStep(step.toDouble()); d->steps.insert(name, step); } spinbox->setValue(variant.toDouble()); d->widgets.insert(name, spinbox); this->addToInternWidgets(spinbox); connect(spinbox, SIGNAL(valueChanged(double)), this, SLOT(updateValue(double))); connect(spinbox, SIGNAL(destroyed(QObject*)), this, SLOT(removeInternWidget(QObject*))); } //TODO: to complete with other QVariant types } void medCompositeParameter::updateValue(bool value) { QCheckBox *checkbox = qobject_cast<QCheckBox*>(QObject::sender()); if(checkbox) { QString name = d->widgets.key(checkbox); d->variants[name] = QVariant(value); emit valuesChanged(d->variants); } } void medCompositeParameter::updateValue(double value) { QDoubleSpinBox *spinbox = qobject_cast<QDoubleSpinBox*>(QObject::sender()); if(spinbox) { QString name = d->widgets.key(spinbox); d->variants[name] = QVariant(value); emit valuesChanged(d->variants); } } void medCompositeParameter::updateValue(int value) { QSpinBox *spinbox = qobject_cast<QSpinBox*>(QObject::sender()); if(spinbox) { QString name = d->widgets.key(spinbox); d->variants[name] = QVariant(value); emit valuesChanged(d->variants); } } void medCompositeParameter::removeInternWidget(QObject *widget) { QWidget *w = qobject_cast<QWidget*>(widget); if(!w) return; this->removeFromInternWidgets(w); QHashIterator<QString, QWidget*> i(d->widgets); while (i.hasNext()) { i.next(); if(w == i.value()) d->widgets.remove(i.key()); } } QList<QPair<QVariant, QVariant> > medCompositeParameter::ranges() const { return d->ranges.values(); } QList<QVariant> medCompositeParameter::steps() const { return d->steps.values(); } <|endoftext|>
<commit_before>#include <cfloat> #include "Steering.h" #include "Math.h" #include "Random.h" namespace Common { Steering::Steering(const Vehicle& e) : mUnit(e), mWanderRadius(2.0f), mWanderDistance(3.0f), mWanderJitter(1.0f) { } Vector3 Steering::seek(const Vector3& tgtpos) { Vector3 desiredVelocity = (tgtpos - mUnit.getPosition()).normalized() * mUnit.getMaxSpeed(); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::flee(const Vector3& threatpos) { Vector3 desiredVelocity = (mUnit.getPosition() - threatpos).normalized() * mUnit.getMaxSpeed(); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::arrive(const Vector3& tgtpos) { auto dist = tgtpos - mUnit.getPosition(); float distlen = dist.length(); if(distlen < 0.0001f) return Vector3(); float speed = std::min(distlen / 0.6f, mUnit.getMaxSpeed()); Vector3 desiredVelocity = dist * (speed / distlen); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::pursuit(const Vehicle& tgt) { Vector3 totgt = tgt.getPosition() - mUnit.getPosition(); float relHeading = mUnit.getVelocity().dot(tgt.getVelocity()); if((totgt.dot(mUnit.getPosition()) > 0.0f) && (relHeading < -0.95f)) { return seek(tgt.getPosition()); } float lookAheadTime = totgt.length() * (1.0f / mUnit.getMaxSpeed() + tgt.getSpeed()); return seek(tgt.getPosition() + tgt.getVelocity() * lookAheadTime); } Vector3 Steering::evade(const Vehicle& threat) { Vector3 tothreat = threat.getPosition() - mUnit.getPosition(); float lookAheadTime = tothreat.length() * (1.0f / mUnit.getMaxSpeed() + threat.getSpeed()); return flee(threat.getPosition() + threat.getVelocity() * lookAheadTime); } Vector3 Steering::wander() { mWanderTarget += Vector3(Random::clamped() * mWanderJitter, Random::clamped() * mWanderJitter, 0.0f); mWanderTarget.normalize(); mWanderTarget *= mWanderRadius; Vector3 target = mUnit.getPosition() + mUnit.getVelocity().normalized() * mWanderDistance + mWanderTarget; return target - mUnit.getPosition(); } Vector3 Steering::obstacleAvoidance(const std::vector<Obstacle*> obstacles) { Obstacle* nearest = nullptr; float distToNearest = FLT_MAX; if(mUnit.getVelocity().null()) return Vector3(); for(auto o : obstacles) { float dot = mUnit.getPosition().dot(o->getPosition()); if(dot < 0.0f) { continue; } float rad = mUnit.getRadius() + o->getRadius(); float dist = Math::pointToSegmentDistance(mUnit.getPosition(), mUnit.getPosition() + mUnit.getVelocity() * 0.5f, o->getPosition()) - rad; if(dist < distToNearest) { distToNearest = dist; nearest = o; } } if(!nearest) { return Vector3(); } Vector3 vecFromObj = Entity::vectorFromTo(*nearest, mUnit); if(vecFromObj.length() < mUnit.getRadius() + nearest->getRadius()) { // we're inside the obstacle return vecFromObj.normalized() * 100.0f; } distToNearest = std::max(0.01f, distToNearest); float velmultiplier = 0.1f + mUnit.getVelocity().length() * 0.5f; float multiplier = velmultiplier / distToNearest; Vector3 res = vecFromObj.normalized() * multiplier; return res; } bool Steering::accumulate(Vector3& runningTotal, const Vector3& add) { float magnitude = runningTotal.length(); float remaining = mUnit.getMaxAcceleration() - magnitude; if(remaining <= 0.0f) return false; double toAdd = add.length(); if(toAdd < remaining) { runningTotal += add; return true; } else { runningTotal += add.normalized() * remaining; return false; } } Vector3 Steering::wallAvoidance(const std::vector<Wall*> walls) { Vector3 nearestPointOnWall; float distToNearest = FLT_MAX; if(mUnit.getVelocity().null()) return Vector3(); for(auto w : walls) { bool found = false; Math::segmentSegmentIntersection2D(mUnit.getPosition(), mUnit.getPosition() + mUnit.getVelocity() * 0.5f, w->getStart(), w->getEnd(), &found); if(found) { Vector3 nearest; float dist = Math::pointToSegmentDistance(w->getStart(), w->getEnd(), mUnit.getPosition(), &nearest); if(dist < distToNearest) { distToNearest = dist; nearestPointOnWall = nearest; } } } if(distToNearest == FLT_MAX) { return Vector3(); } Vector3 vecFromPoint = mUnit.getPosition() - nearestPointOnWall; float velmultiplier = 5.0f + mUnit.getVelocity().length() * 1.0f; float multiplier = velmultiplier / distToNearest; Vector3 res = vecFromPoint.normalized() * multiplier; return res; } } <commit_msg>tweak wall avoidance steering<commit_after>#include <cfloat> #include "Steering.h" #include "Math.h" #include "Random.h" namespace Common { Steering::Steering(const Vehicle& e) : mUnit(e), mWanderRadius(2.0f), mWanderDistance(3.0f), mWanderJitter(1.0f) { } Vector3 Steering::seek(const Vector3& tgtpos) { Vector3 desiredVelocity = (tgtpos - mUnit.getPosition()).normalized() * mUnit.getMaxSpeed(); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::flee(const Vector3& threatpos) { Vector3 desiredVelocity = (mUnit.getPosition() - threatpos).normalized() * mUnit.getMaxSpeed(); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::arrive(const Vector3& tgtpos) { auto dist = tgtpos - mUnit.getPosition(); float distlen = dist.length(); if(distlen < 0.0001f) return Vector3(); float speed = std::min(distlen / 0.6f, mUnit.getMaxSpeed()); Vector3 desiredVelocity = dist * (speed / distlen); return desiredVelocity - mUnit.getVelocity(); } Vector3 Steering::pursuit(const Vehicle& tgt) { Vector3 totgt = tgt.getPosition() - mUnit.getPosition(); float relHeading = mUnit.getVelocity().dot(tgt.getVelocity()); if((totgt.dot(mUnit.getPosition()) > 0.0f) && (relHeading < -0.95f)) { return seek(tgt.getPosition()); } float lookAheadTime = totgt.length() * (1.0f / mUnit.getMaxSpeed() + tgt.getSpeed()); return seek(tgt.getPosition() + tgt.getVelocity() * lookAheadTime); } Vector3 Steering::evade(const Vehicle& threat) { Vector3 tothreat = threat.getPosition() - mUnit.getPosition(); float lookAheadTime = tothreat.length() * (1.0f / mUnit.getMaxSpeed() + threat.getSpeed()); return flee(threat.getPosition() + threat.getVelocity() * lookAheadTime); } Vector3 Steering::wander() { mWanderTarget += Vector3(Random::clamped() * mWanderJitter, Random::clamped() * mWanderJitter, 0.0f); mWanderTarget.normalize(); mWanderTarget *= mWanderRadius; Vector3 target = mUnit.getPosition() + mUnit.getVelocity().normalized() * mWanderDistance + mWanderTarget; return target - mUnit.getPosition(); } Vector3 Steering::obstacleAvoidance(const std::vector<Obstacle*> obstacles) { Obstacle* nearest = nullptr; float distToNearest = FLT_MAX; if(mUnit.getVelocity().null()) return Vector3(); for(auto o : obstacles) { float dot = mUnit.getPosition().dot(o->getPosition()); if(dot < 0.0f) { continue; } float rad = mUnit.getRadius() + o->getRadius(); float dist = Math::pointToSegmentDistance(mUnit.getPosition(), mUnit.getPosition() + mUnit.getVelocity() * 0.5f, o->getPosition()) - rad; if(dist < distToNearest) { distToNearest = dist; nearest = o; } } if(!nearest) { return Vector3(); } Vector3 vecFromObj = Entity::vectorFromTo(*nearest, mUnit); if(vecFromObj.length() < mUnit.getRadius() + nearest->getRadius()) { // we're inside the obstacle return vecFromObj.normalized() * 100.0f; } distToNearest = std::max(0.01f, distToNearest); float velmultiplier = 0.1f + mUnit.getVelocity().length() * 0.5f; float multiplier = velmultiplier / distToNearest; Vector3 res = vecFromObj.normalized() * multiplier; return res; } bool Steering::accumulate(Vector3& runningTotal, const Vector3& add) { float magnitude = runningTotal.length(); float remaining = mUnit.getMaxAcceleration() - magnitude; if(remaining <= 0.0f) return false; double toAdd = add.length(); if(toAdd < remaining) { runningTotal += add; return true; } else { runningTotal += add.normalized() * remaining; return false; } } Vector3 Steering::wallAvoidance(const std::vector<Wall*> walls) { Vector3 nearestPointOnWall; float distToNearest = FLT_MAX; if(mUnit.getVelocity().null()) return Vector3(); for(auto w : walls) { bool found = false; Math::segmentSegmentIntersection2D(mUnit.getPosition(), mUnit.getPosition() + mUnit.getVelocity() * 0.5f, w->getStart(), w->getEnd(), &found); if(found) { Vector3 nearest; float dist = Math::pointToSegmentDistance(w->getStart(), w->getEnd(), mUnit.getPosition(), &nearest); if(dist < distToNearest) { distToNearest = dist; nearestPointOnWall = nearest; } } } if(distToNearest == FLT_MAX) { return Vector3(); } Vector3 vecFromPoint = mUnit.getPosition() - nearestPointOnWall; float velmultiplier = 500.0f + mUnit.getVelocity().length() * 1.0f; float multiplier = velmultiplier / distToNearest; Vector3 res = vecFromPoint.normalized() * multiplier; return res; } } <|endoftext|>
<commit_before>#ifndef ARABICA_XSLT_TEMPLATE_HANDLER_HPP #define ARABICA_XSLT_TEMPLATE_HANDLER_HPP #include "../xslt_template.hpp" #include "xslt_item_container_handler.hpp" namespace Arabica { namespace XSLT { class TemplateHandler : public ItemContainerHandler<Template> { public: TemplateHandler(CompilationContext& context) : ItemContainerHandler<Template>(context), done_params_(false) { } // TemplateHandler protected: virtual Template* createContainer(const std::string& namespaceURI, const std::string& localName, const std::string& qName, const SAX::Attributes<std::string>& atts) { const std::string& match = atts.getValue("match"); if((match == "") && (atts.getValue("name") == "")) throw SAX::SAXException("xsl:template must have a match and/or a name attribute"); int index = atts.getIndex("mode"); if(index != -1) { const std::string& mode = atts.getValue(index); if(mode == "") throw SAX::SAXException("xsl:template mode cannot be empty"); if(match == "") throw SAX::SAXException("xsl:template may not have a mode without a match"); } // ... std::pair<std::string, std::string> name; if(atts.getValue("name") != "") name = context().processQName(atts.getValue("name")); std::pair<std::string, std::string> mode; if(atts.getValue("mode") != "") mode = context().processQName(atts.getValue("mode")); if(match == "") return new Template(name, mode, atts.getValue("priority")); return new Template(context().xpath_match(match), name, mode, atts.getValue("priority")); } // createContainer virtual bool createChild(const std::string& namespaceURI, const std::string& localName, const std::string& qName, const SAX::Attributes<std::string>& atts) { if((namespaceURI == StylesheetConstant::NamespaceURI()) && (localName == "param")) { if(!done_params_) { context().push(container(), new VariableHandler<Param>(context()), namespaceURI, qName, localName, atts); return true; } else throw SAX::SAXException("xsl:param must immediately follow xsl:template"); } done_params_ = true; return ItemContainerHandler<Template>::createChild(namespaceURI, localName, qName, atts); } // createChild public: virtual void endElement(const std::string& namespaceURI, const std::string& localName, const std::string& qName) { context().stylesheet().add_template(container()); context().pop(); } // endElement private: bool done_params_; }; // class TemplateHandler } // namespace XSLT } // namespace Arabica #endif // ARABICA_XSLT_TEMPLATE_HANDLER_HPP <commit_msg>disallow pcdata ahead of xsl:param<commit_after>#ifndef ARABICA_XSLT_TEMPLATE_HANDLER_HPP #define ARABICA_XSLT_TEMPLATE_HANDLER_HPP #include "../xslt_template.hpp" #include "xslt_item_container_handler.hpp" namespace Arabica { namespace XSLT { class TemplateHandler : public ItemContainerHandler<Template> { public: TemplateHandler(CompilationContext& context) : ItemContainerHandler<Template>(context), done_params_(false) { } // TemplateHandler virtual void characters(const std::string& ch) { if(!done_params_) { for(std::string::const_iterator i = ch.begin(), e = ch.end(); i != e; ++i) if(!Arabica::XML::is_space(*i)) { done_params_ = true; break; } // if ... } // if(!done_params_) ItemContainerHandler<Template>::characters(ch); } // characters protected: virtual Template* createContainer(const std::string& namespaceURI, const std::string& localName, const std::string& qName, const SAX::Attributes<std::string>& atts) { const std::string& match = atts.getValue("match"); if((match == "") && (atts.getValue("name") == "")) throw SAX::SAXException("xsl:template must have a match and/or a name attribute"); int index = atts.getIndex("mode"); if(index != -1) { const std::string& mode = atts.getValue(index); if(mode == "") throw SAX::SAXException("xsl:template mode cannot be empty"); if(match == "") throw SAX::SAXException("xsl:template may not have a mode without a match"); } // ... std::pair<std::string, std::string> name; if(atts.getValue("name") != "") name = context().processQName(atts.getValue("name")); std::pair<std::string, std::string> mode; if(atts.getValue("mode") != "") mode = context().processQName(atts.getValue("mode")); if(match == "") return new Template(name, mode, atts.getValue("priority")); return new Template(context().xpath_match(match), name, mode, atts.getValue("priority")); } // createContainer virtual bool createChild(const std::string& namespaceURI, const std::string& localName, const std::string& qName, const SAX::Attributes<std::string>& atts) { if((namespaceURI == StylesheetConstant::NamespaceURI()) && (localName == "param")) { if(!done_params_) { context().push(container(), new VariableHandler<Param>(context()), namespaceURI, qName, localName, atts); return true; } else throw SAX::SAXException("xsl:param must immediately follow xsl:template"); } done_params_ = true; return ItemContainerHandler<Template>::createChild(namespaceURI, localName, qName, atts); } // createChild public: virtual void endElement(const std::string& namespaceURI, const std::string& localName, const std::string& qName) { context().stylesheet().add_template(container()); context().pop(); } // endElement private: bool done_params_; }; // class TemplateHandler } // namespace XSLT } // namespace Arabica #endif // ARABICA_XSLT_TEMPLATE_HANDLER_HPP <|endoftext|>
<commit_before>/******************************************************************************* * include/util/common.hpp * * Copyright (C) 2018 Jonas Ellert <jonas.ellert@tu-dortmund.de> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #include <vector> #include "arrays/stxxl_helper.hpp" #include "construction/wavelet_structure.hpp" class wavelet_structure_external_writer; class wavelet_structure_external_factory; class wavelet_structure_external { public: friend class wavelet_structure_external_writer; friend class wavelet_structure_external_factory; using bv_type = stxxlvector<uint64_t>; private: uint64_t text_size_; uint64_t levels_; bool is_tree_; bool save_zeros_; bool save_histograms_; bool is_huffman_shaped_; bv_type metadata_; bv_type bvs_; uint64_t data_size_; std::vector<uint64_t> level_sizes_; std::vector<uint64_t> level_offsets_; std::vector<uint64_t> zeros_; std::vector<std::vector<uint64_t>> histograms_; wavelet_structure_external(uint64_t text_size, uint64_t levels, bool is_tree, bool save_zeros, bool save_histograms, bool is_huffman_shaped, std::string em_name, unsigned em_dir) : text_size_(text_size), levels_(levels), is_tree_(is_tree), save_zeros_(save_zeros), save_histograms_(save_histograms), is_huffman_shaped_(is_huffman_shaped), metadata_(stxxl_files::getVectorPermanent<bv_type>( em_dir, em_name + ".meta")), bvs_(stxxl_files::getVectorPermanent<bv_type>( em_dir, em_name + ".bvs")) { if (is_huffman_shaped_) std::abort(); //TODO: implement // make sure disk files are clean bvs_.clear(); metadata_.clear(); data_size_ = 0; level_sizes_.resize(levels_, text_size_); level_offsets_.reserve(levels_ + 1); for (uint64_t level = 0; level < levels_; ++level) { level_offsets_.push_back(data_size_); data_size_ += (level_sizes_[level] + 63) / 64; } level_offsets_.push_back(data_size_); bvs_.resize(data_size_); if (save_zeros_) { zeros_.resize(levels, 0); } else { assert(is_tree_); } if (save_histograms_){ uint64_t histogram_length = 1; histograms_.resize(levels + 1); for (uint64_t i = 0; i < levels + 1; i++) { histograms_[i].resize(histogram_length, 0); histogram_length *= 2; } } } bit_vectors getInternalBitvectors() { if(is_huffman_shaped_) std::abort(); bit_vectors result(levels_, text_size_); for(uint64_t level = 0; level < levels_; level++) { auto intLevel = result[level]; auto extLevel = (*this)[level]; for(uint64_t datapos = 0; datapos < intLevel.size(); datapos++) { intLevel[datapos] = extLevel[datapos]; } } return result; } std::vector<uint64_t> getInternalZeros() { if(is_huffman_shaped_) std::abort(); std::vector<uint64_t> result(levels_); for(uint64_t level = 0; level < levels_; level++) { result[level] = zeros()[level]; } return result; } public: // Prevent accidental copies wavelet_structure_external(wavelet_structure_external const&) = delete; wavelet_structure_external& operator=(wavelet_structure_external const&) = delete; // Allow moving wavelet_structure_external(wavelet_structure_external&& other) = default; wavelet_structure_external& operator=(wavelet_structure_external&& other) = default; inline bool is_tree() const { return is_tree_; } inline bool has_zeros() const { return save_zeros_; } inline bool has_histograms() const { return save_histograms_; } inline uint64_t levels() const { return levels_; } inline uint64_t text_size() const { return text_size_; } inline std::vector<uint64_t> const& level_sizes() const { return level_sizes_; } inline std::vector<uint64_t> const& level_offsets() const { return level_offsets_; } inline std::vector<uint64_t> const& zeros() const { static std::vector<uint64_t> empty; if(!save_zeros_) return empty; return zeros_; } inline std::vector<std::vector<uint64_t>> const& histograms() const { static std::vector<std::vector<uint64_t>> empty; if(!save_histograms_) return empty; return histograms_; } inline const stxxlvector_offset<uint64_t> operator[](const uint64_t level) const { return stxxlvector_offset<uint64_t>(bvs_, level_offsets_[level]); } inline stxxlvector_offset<uint64_t> operator[](const uint64_t level) { return stxxlvector_offset<uint64_t>(bvs_, level_offsets_[level]); } void saveMetaData() { // TODO: implement } wavelet_structure getInternalStructure() { if(is_huffman_shaped_) std::abort(); if(is_tree_) { return wavelet_structure_tree(getInternalBitvectors()); } else { return wavelet_structure_matrix(getInternalBitvectors(), getInternalZeros()); } } }; class wavelet_structure_external_writer { public: inline static auto& zeros(wavelet_structure_external& w) { return w.zeros_; } inline static auto& histograms(wavelet_structure_external& w) { return w.histograms_; } inline static auto& bvs(wavelet_structure_external& w) { return w.bvs_; } }; class wavelet_structure_external_factory { private: bool is_tree; bool save_zeros; bool save_hists; bool is_huff; public: using self_type = wavelet_structure_external_factory; wavelet_structure_external_factory(bool tree) : is_tree(tree), save_zeros(!tree), save_hists(false), is_huff(false) {} wavelet_structure_external construct(uint64_t text_size, uint64_t levels, std::string em_name, unsigned em_dir) { return wavelet_structure_external(text_size, levels, is_tree, save_zeros, save_hists, is_huff, em_name, em_dir); } self_type zeros(bool value = true) { save_zeros = value || !is_tree; return *this; } self_type noZeros(bool value = true) { return zeros(!value); } self_type histograms(bool value = true) { save_hists = value; return *this; } self_type noHistograms(bool value = true) { return histograms(!value); } self_type huffman(bool value = true) { is_huff = value; if(is_huff) std::abort(); //TODO: implement return *this; } self_type noHuffman(bool value = true) { return huffman(!value); } }; /******************************************************************************/ <commit_msg>Add typedefs in wavelet_structure_external<commit_after>/******************************************************************************* * include/util/common.hpp * * Copyright (C) 2018 Jonas Ellert <jonas.ellert@tu-dortmund.de> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #include <vector> #include "arrays/stxxl_helper.hpp" #include "construction/wavelet_structure.hpp" class wavelet_structure_external_writer; class wavelet_structure_external_factory; class wavelet_structure_external { public: friend class wavelet_structure_external_writer; friend class wavelet_structure_external_factory; using bv_type = stxxlvector<uint64_t>; using zeros_type = std::vector<uint64_t>; using hists_type = std::vector<std::vector<uint64_t>>; private: uint64_t text_size_; uint64_t levels_; bool is_tree_; bool save_zeros_; bool save_histograms_; bool is_huffman_shaped_; bv_type metadata_; bv_type bvs_; uint64_t data_size_; std::vector<uint64_t> level_sizes_; std::vector<uint64_t> level_offsets_; zeros_type zeros_; hists_type histograms_; wavelet_structure_external(uint64_t text_size, uint64_t levels, bool is_tree, bool save_zeros, bool save_histograms, bool is_huffman_shaped, std::string em_name, unsigned em_dir) : text_size_(text_size), levels_(levels), is_tree_(is_tree), save_zeros_(save_zeros), save_histograms_(save_histograms), is_huffman_shaped_(is_huffman_shaped), metadata_(stxxl_files::getVectorPermanent<bv_type>( em_dir, em_name + ".meta")), bvs_(stxxl_files::getVectorPermanent<bv_type>( em_dir, em_name + ".bvs")) { if (is_huffman_shaped_) std::abort(); //TODO: implement // make sure disk files are clean bvs_.clear(); metadata_.clear(); data_size_ = 0; level_sizes_.resize(levels_, text_size_); level_offsets_.reserve(levels_ + 1); for (uint64_t level = 0; level < levels_; ++level) { level_offsets_.push_back(data_size_); data_size_ += (level_sizes_[level] + 63) / 64; } level_offsets_.push_back(data_size_); bvs_.resize(data_size_); if (save_zeros_) { zeros_.resize(levels, 0); } else { assert(is_tree_); } if (save_histograms_){ uint64_t histogram_length = 1; histograms_.resize(levels + 1); for (uint64_t i = 0; i < levels + 1; i++) { histograms_[i].resize(histogram_length, 0); histogram_length *= 2; } } } bit_vectors getInternalBitvectors() { if(is_huffman_shaped_) std::abort(); bit_vectors result(levels_, text_size_); for(uint64_t level = 0; level < levels_; level++) { auto intLevel = result[level]; auto extLevel = (*this)[level]; for(uint64_t datapos = 0; datapos < intLevel.size(); datapos++) { intLevel[datapos] = extLevel[datapos]; } } return result; } std::vector<uint64_t> getInternalZeros() { if(is_huffman_shaped_) std::abort(); std::vector<uint64_t> result(levels_); for(uint64_t level = 0; level < levels_; level++) { result[level] = zeros()[level]; } return result; } public: // Prevent accidental copies wavelet_structure_external(wavelet_structure_external const&) = delete; wavelet_structure_external& operator=(wavelet_structure_external const&) = delete; // Allow moving wavelet_structure_external(wavelet_structure_external&& other) = default; wavelet_structure_external& operator=(wavelet_structure_external&& other) = default; inline bool is_tree() const { return is_tree_; } inline bool has_zeros() const { return save_zeros_; } inline bool has_histograms() const { return save_histograms_; } inline uint64_t levels() const { return levels_; } inline uint64_t text_size() const { return text_size_; } inline std::vector<uint64_t> const& level_sizes() const { return level_sizes_; } inline std::vector<uint64_t> const& level_offsets() const { return level_offsets_; } inline std::vector<uint64_t> const& zeros() const { static std::vector<uint64_t> empty; if(!save_zeros_) return empty; return zeros_; } inline std::vector<std::vector<uint64_t>> const& histograms() const { static std::vector<std::vector<uint64_t>> empty; if(!save_histograms_) return empty; return histograms_; } inline const stxxlvector_offset<uint64_t> operator[](const uint64_t level) const { return stxxlvector_offset<uint64_t>(bvs_, level_offsets_[level]); } inline stxxlvector_offset<uint64_t> operator[](const uint64_t level) { return stxxlvector_offset<uint64_t>(bvs_, level_offsets_[level]); } void saveMetaData() { // TODO: implement } wavelet_structure getInternalStructure() { if(is_huffman_shaped_) std::abort(); if(is_tree_) { return wavelet_structure_tree(getInternalBitvectors()); } else { return wavelet_structure_matrix(getInternalBitvectors(), getInternalZeros()); } } }; class wavelet_structure_external_writer { public: inline static auto& zeros(wavelet_structure_external& w) { return w.zeros_; } inline static auto& histograms(wavelet_structure_external& w) { return w.histograms_; } inline static auto& bvs(wavelet_structure_external& w) { return w.bvs_; } }; class wavelet_structure_external_factory { private: bool is_tree; bool save_zeros; bool save_hists; bool is_huff; public: using self_type = wavelet_structure_external_factory; wavelet_structure_external_factory(bool tree) : is_tree(tree), save_zeros(!tree), save_hists(false), is_huff(false) {} wavelet_structure_external construct(uint64_t text_size, uint64_t levels, std::string em_name, unsigned em_dir) { return wavelet_structure_external(text_size, levels, is_tree, save_zeros, save_hists, is_huff, em_name, em_dir); } self_type zeros(bool value = true) { save_zeros = value || !is_tree; return *this; } self_type noZeros(bool value = true) { return zeros(!value); } self_type histograms(bool value = true) { save_hists = value; return *this; } self_type noHistograms(bool value = true) { return histograms(!value); } self_type huffman(bool value = true) { is_huff = value; if(is_huff) std::abort(); //TODO: implement return *this; } self_type noHuffman(bool value = true) { return huffman(!value); } }; /******************************************************************************/ <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <iostream> namespace temporaries { struct A { int f; }; std::unique_ptr<A> some_f(); void FN_call_some_f_deref_bad() { const A& a_ref = *some_f(); // temporary unique_ptr returned by `some_f` is // destroyed at the end of the statement std::cout << a_ref.f; } void call_some_f_ok() { auto local = some_f(); // ok, as ownership of a temporary unique_ptr is passed // to `local` const A& a_ref = *local; std::cout << a_ref.f; } void call_some_f_copy_object_ok() { auto a = *some_f().get(); // ok, as value is copied before temporary // unique_prt is destroyed std::cout << a.f; } } // namespace temporaries <commit_msg>[pulse] another test for temporaries<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ namespace temporaries { template <typename X> struct UniquePtr { X* x_; ~UniquePtr() { if (x_) { delete x_; } } UniquePtr(X* y) { x_ = y; } UniquePtr(UniquePtr<X>& p) = delete; // no copy constructor UniquePtr(UniquePtr<X>&& p) { x_ = p.get(); p.x_ = nullptr; } X* get() const { return x_; } X& operator*() const { return *get(); } X* operator->() const { return get(); } }; struct A { int s_; ~A() {} A() { A(42); } A(int s) { s_ = s; } A(A& a) { s_ = a.s_; } }; UniquePtr<A> mk_UniquePtr_A() { return UniquePtr<A>(new A); } int FN_call_mk_UniquePtr_A_deref_bad() { A* a = mk_UniquePtr_A().get(); // temporary unique_ptr returned by // `mk_UniquePtr_A` is destroyed at the end // of the statement return a->s_; } int call_mk_UniquePtr_A_ok() { const UniquePtr<A>& local = mk_UniquePtr_A(); // ok, as ownership of a temporary unique_ptr is passed // to `local` return local->s_; } int call_mk_UniquePtr_A_copy_object_ok() { A a = *mk_UniquePtr_A().get(); // ok, as value is copied before temporary // unique_prt is destroyed return a.s_; } } // namespace temporaries <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <cstdlib> #include <vector> #include <algorithm> #include <cmath> #include <climits> #include <complex> #include <iostream> #include <iomanip> #include <string> #include <sstream> #include <utility> #include <queue> #include <stack> #include <list> #include <map> #include <set> #define EPS 1e-9 #define PI 3.141592654 #define INF 1000000000 #define mp make_pair #define pb push_back #define sc1(a) scanf("%d", &a) #define sc2(a, b) scanf("%d %d", &a, &b) #define sc3(a, b, c) scanf("%d %d %d", &a, &b, &c) #define sc4(a, b, c, d) scanf("%d %d %d %d", &a, &b, &c, &d) #define size(a) ((int)((a).size())) #define var(a,b) __typeof(b) a=(b) #define zero(x) memset(x, 0, sizeof(x)) #define clear(x, a) memset(x, a, sizeof(x)) #define for(i, n) for(int i = 0; i < (n); ++i) #define isLetter(c) (((c) >= 'A' && (c) <= 'Z') || ((c) >= 'a' && (c) <= 'z')) typedef long long ll; typedef list<int> li; typedef stack<int> si; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; using namespace std; int main(int argc, char const *argv[]) { return 0; }<commit_msg>TEMPLATE updated<commit_after>#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <math.h> #include <limits.h> using namespace std; // Datatypes typedef vector<int> vi; typedef vector<string> vs; typedef vector<vi> vvi; typedef pair<int,int> ii; typedef long long ll; typedef long double ld; // Define Macros #define fi first #define se second #define mp make_pair #define pb push_back #define sz(a) int((a).size()) #define all(c) (c).begin(),(c).end() #define clear(x, a) memset(x, a, sizeof(x)) #define present(c,x) ((c).find(x) != (c).end()) #define cpresent(c,x) (find(all(c),x) != (c).end()) #define for(i,n) for(int (i) = 0; (i) < (n); (i)++) #define sc1(a) scanf("%d", &a) #define sc2(a,b) scanf("%d %d", &a, &b) #define sc3(a,b,c) scanf("%d %d %d", &a, &b, &c) #define sc4(a,b,c,d) scanf("%d %d %d %d", &a, &b, &c, &d) #define isLetter(c) (((c) >= 'A' && (c) <= 'Z') || ((c) >= 'a' && (c) <= 'z')) // Constants const double eps = 1e-8; const double PI = 3.1415926535897932384626433832795; int main(void) { return 0; }<|endoftext|>
<commit_before>/* COPYRIGHT (c) 2014 Umut Acar, Arthur Chargueraud, and Michael * Rainey * All rights reserved. * * \file bench.cpp * \brief Benchmarking driver * */ #include "benchmark.hpp" #include "hash.hpp" #include "dup.hpp" #include "string.hpp" #include "sort.hpp" #include "graph.hpp" #include "fib.hpp" #include "mcss.hpp" #include "numeric.hpp" /***********************************************************************/ /*---------------------------------------------------------------------*/ /* Random-array generation */ loop_controller_type random_array_contr("random_array"); // returns a random array of size n using seed s array random_array(long s, long n) { array tmp = array(n); par::parallel_for(random_array_contr, 0l, n, [&] (long i) { tmp[i] = hash_signed(i+s); }); return tmp; } loop_controller_type almost_sorted_array_contr("almost_sorted_array"); // returns an array that is sorted up to a given number of swaps array almost_sorted_array(long s, long n, long nb_swaps) { array tmp = array(n); par::parallel_for(almost_sorted_array_contr, 0l, n, [&] (long i) { tmp[i] = i; }); for (long i = 0; i < nb_swaps; i++) std::swap(tmp[random_index(2*i, n)], tmp[random_index(2*i+1, n)]); return tmp; } loop_controller_type exp_dist_array_contr("exp_dist_array"); // returns an array with exponential distribution of size n using seed s array exp_dist_array(long s, long n) { array tmp = array(n); int lg = log2_up(n)+1; par::parallel_for(exp_dist_array_contr, 0l, n, [&] (long i) { long range = (1 << (random_index(2*(i+s), lg))); tmp[i] = hash64shift((long)(range+random_index(2*(i+s), range))); }); return tmp; } /*---------------------------------------------------------------------*/ /* Benchmark framework */ using thunk_type = std::function<void ()>; using benchmark_type = std::pair<std::pair<thunk_type,thunk_type>, std::pair<thunk_type, thunk_type>>; benchmark_type make_benchmark(thunk_type init, thunk_type bench, thunk_type output, thunk_type destroy) { return std::make_pair(std::make_pair(init, bench), std::make_pair(output, destroy)); } void bench_init(const benchmark_type& b) { b.first.first(); } void bench_run(const benchmark_type& b) { b.first.second(); } void bench_output(const benchmark_type& b) { b.second.first(); } void bench_destroy(const benchmark_type& b) { b.second.second(); } /*---------------------------------------------------------------------*/ /* Benchmark definitions */ benchmark_type fib_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); value_type* result = new value_type; auto init = [=] { }; auto bench = [=] { *result = fib(n); }; auto output = [=] { std::cout << "result\t" << *result << std::endl; }; auto destroy = [=] { delete result; }; return make_benchmark(init, bench, output, destroy); } benchmark_type duplicate_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); array_ptr outp = new array(0); auto init = [=] { *inp = fill(n, 1); }; auto bench = [=] { *outp = duplicate(*inp); }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type ktimes_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); long k = pasl::util::cmdline::parse_or_default_long("k", 4); array_ptr inp = new array(0); array_ptr outp = new array(0); auto init = [=] { *inp = fill(n, 1); }; auto bench = [=] { *outp = ktimes(*inp, k); }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type reduce_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); value_type* result = new value_type; auto init = [=] { *inp = fill(n, 1); }; auto bench = [=] { *result = sum(*inp); }; auto output = [=] { std::cout << "result\t" << *result << std::endl; }; auto destroy = [=] { delete inp; delete result; }; return make_benchmark(init, bench, output, destroy); } benchmark_type scan_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); array_ptr outp = new array(0); auto init = [=] { *inp = fill(n, 1); }; auto bench = [=] { *outp = partial_sums(*inp).prefix; }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type mcss_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); value_type* outp = new value_type; auto init = [=] { *inp = gen_random_array(n); }; auto bench = [=] { *outp = mcss(*inp); }; auto output = [=] { std::cout << "result\t" << *outp << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type dmdvmult_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); long nxn = n*n; array_ptr mtxp = new array(0); array_ptr vecp = new array(0); array_ptr outp = new array(0); auto init = [=] { *mtxp = gen_random_array(nxn); *vecp = gen_random_array(n); }; auto bench = [=] { *outp = dmdvmult(*mtxp, *vecp); }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete mtxp; delete vecp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type sort_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); array_ptr outp = new array(0); std::string s = pasl::util::cmdline::parse_string("algo"); if (s != "quicksort" && s != "mergesort") pasl::util::atomic::fatal([&] { std::cerr << "bogus algo:" << s << std::endl; }); auto sort_fct = (s == "quicksort") ? [] (array_ref xs) { return quicksort(xs); } : [] (array_ref xs) { return mergesort(xs); }; auto init = [=] { pasl::util::cmdline::argmap_dispatch c; c.add("random", [&] { *inp = random_array(12345, n); }); c.add("almost_sorted", [&] { long nb_swaps = pasl::util::cmdline::parse_or_default_long("nb_swaps", 1000); *inp = almost_sorted_array(1232, n, nb_swaps); }); c.add("exponential_dist", [&] { *inp = exp_dist_array(12323, n); }); c.find_by_arg_or_default_key("generator", "random")(); }; auto bench = [=] { *outp = sort_fct(*inp); }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type graph_bench() { adjlist* graphp = new adjlist; array* distsp = new array; std::string fname = pasl::util::cmdline::parse_or_default_string("fname", ""); vtxid_type source = pasl::util::cmdline::parse_or_default_long("source", 0l); if (fname == "") pasl::util::atomic::fatal([] { std::cerr << "missing filename for graph: -fname filename"; }); auto init = [=] { graphp->load_from_file(fname); }; auto bench = [=] { *distsp = bfs(*graphp, source); }; auto output = [=] { long nb_visited = sum(map([] (value_type v) { return (v != dist_unknown); }, *distsp)); long max_dist = max(*distsp); std::cout << "nb_visited\t" << nb_visited << std::endl; std::cout << "max_dist\t" << max_dist << std::endl; }; auto destroy = [=] { delete graphp; delete distsp; }; return make_benchmark(init, bench, output, destroy); } /*---------------------------------------------------------------------*/ /* PASL Driver */ int main(int argc, char** argv) { benchmark_type bench; auto init = [&] { pasl::util::cmdline::argmap<std::function<benchmark_type()>> m; m.add("fib", [&] { return fib_bench(); }); m.add("duplicate", [&] { return duplicate_bench(); }); m.add("ktimes", [&] { return ktimes_bench(); }); m.add("reduce", [&] { return reduce_bench(); }); m.add("scan", [&] { return scan_bench(); }); m.add("mcss", [&] { return mcss_bench(); }); m.add("dmdvmult", [&] { return dmdvmult_bench(); }); m.add("sort", [&] { return sort_bench(); }); m.add("graph", [&] { return graph_bench(); }); bench = m.find_by_arg("bench")(); bench_init(bench); }; auto run = [&] (bool) { bench_run(bench); }; auto output = [&] { bench_output(bench); }; auto destroy = [&] { bench_destroy(bench); }; pasl::sched::launch(argc, argv, init, run, output, destroy); } /***********************************************************************/ <commit_msg>change default<commit_after>/* COPYRIGHT (c) 2014 Umut Acar, Arthur Chargueraud, and Michael * Rainey * All rights reserved. * * \file bench.cpp * \brief Benchmarking driver * */ #include "benchmark.hpp" #include "hash.hpp" #include "dup.hpp" #include "string.hpp" #include "sort.hpp" #include "graph.hpp" #include "fib.hpp" #include "mcss.hpp" #include "numeric.hpp" /***********************************************************************/ /*---------------------------------------------------------------------*/ /* Random-array generation */ loop_controller_type random_array_contr("random_array"); // returns a random array of size n using seed s array random_array(long s, long n) { array tmp = array(n); par::parallel_for(random_array_contr, 0l, n, [&] (long i) { tmp[i] = hash_signed(i+s); }); return tmp; } loop_controller_type almost_sorted_array_contr("almost_sorted_array"); // returns an array that is sorted up to a given number of swaps array almost_sorted_array(long s, long n, long nb_swaps) { array tmp = array(n); par::parallel_for(almost_sorted_array_contr, 0l, n, [&] (long i) { tmp[i] = i; }); for (long i = 0; i < nb_swaps; i++) std::swap(tmp[random_index(2*i, n)], tmp[random_index(2*i+1, n)]); return tmp; } loop_controller_type exp_dist_array_contr("exp_dist_array"); // returns an array with exponential distribution of size n using seed s array exp_dist_array(long s, long n) { array tmp = array(n); int lg = log2_up(n)+1; par::parallel_for(exp_dist_array_contr, 0l, n, [&] (long i) { long range = (1 << (random_index(2*(i+s), lg))); tmp[i] = hash64shift((long)(range+random_index(2*(i+s), range))); }); return tmp; } /*---------------------------------------------------------------------*/ /* Benchmark framework */ using thunk_type = std::function<void ()>; using benchmark_type = std::pair<std::pair<thunk_type,thunk_type>, std::pair<thunk_type, thunk_type>>; benchmark_type make_benchmark(thunk_type init, thunk_type bench, thunk_type output, thunk_type destroy) { return std::make_pair(std::make_pair(init, bench), std::make_pair(output, destroy)); } void bench_init(const benchmark_type& b) { b.first.first(); } void bench_run(const benchmark_type& b) { b.first.second(); } void bench_output(const benchmark_type& b) { b.second.first(); } void bench_destroy(const benchmark_type& b) { b.second.second(); } /*---------------------------------------------------------------------*/ /* Benchmark definitions */ benchmark_type fib_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); value_type* result = new value_type; auto init = [=] { }; auto bench = [=] { *result = fib(n); }; auto output = [=] { std::cout << "result\t" << *result << std::endl; }; auto destroy = [=] { delete result; }; return make_benchmark(init, bench, output, destroy); } benchmark_type duplicate_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); array_ptr outp = new array(0); auto init = [=] { *inp = fill(n, 1); }; auto bench = [=] { *outp = duplicate(*inp); }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type ktimes_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); long k = pasl::util::cmdline::parse_or_default_long("k", 4); array_ptr inp = new array(0); array_ptr outp = new array(0); auto init = [=] { *inp = fill(n, 1); }; auto bench = [=] { *outp = ktimes(*inp, k); }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type reduce_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); value_type* result = new value_type; auto init = [=] { *inp = fill(n, 1); }; auto bench = [=] { *result = sum(*inp); }; auto output = [=] { std::cout << "result\t" << *result << std::endl; }; auto destroy = [=] { delete inp; delete result; }; return make_benchmark(init, bench, output, destroy); } benchmark_type scan_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); array_ptr outp = new array(0); auto init = [=] { *inp = fill(n, 1); }; auto bench = [=] { *outp = partial_sums(*inp).prefix; }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type mcss_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); value_type* outp = new value_type; auto init = [=] { *inp = gen_random_array(n); }; auto bench = [=] { *outp = mcss(*inp); }; auto output = [=] { std::cout << "result\t" << *outp << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type dmdvmult_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 4000); long nxn = n*n; array_ptr mtxp = new array(0); array_ptr vecp = new array(0); array_ptr outp = new array(0); auto init = [=] { *mtxp = gen_random_array(nxn); *vecp = gen_random_array(n); }; auto bench = [=] { *outp = dmdvmult(*mtxp, *vecp); }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete mtxp; delete vecp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type sort_bench() { long n = pasl::util::cmdline::parse_or_default_long("n", 1l<<20); array_ptr inp = new array(0); array_ptr outp = new array(0); std::string s = pasl::util::cmdline::parse_string("algo"); if (s != "quicksort" && s != "mergesort") pasl::util::atomic::fatal([&] { std::cerr << "bogus algo:" << s << std::endl; }); auto sort_fct = (s == "quicksort") ? [] (array_ref xs) { return quicksort(xs); } : [] (array_ref xs) { return mergesort(xs); }; auto init = [=] { pasl::util::cmdline::argmap_dispatch c; c.add("random", [&] { *inp = random_array(12345, n); }); c.add("almost_sorted", [&] { long nb_swaps = pasl::util::cmdline::parse_or_default_long("nb_swaps", 1000); *inp = almost_sorted_array(1232, n, nb_swaps); }); c.add("exponential_dist", [&] { *inp = exp_dist_array(12323, n); }); c.find_by_arg_or_default_key("generator", "random")(); }; auto bench = [=] { *outp = sort_fct(*inp); }; auto output = [=] { std::cout << "result\t" << (*outp)[outp->size()-1] << std::endl; }; auto destroy = [=] { delete inp; delete outp; }; return make_benchmark(init, bench, output, destroy); } benchmark_type graph_bench() { adjlist* graphp = new adjlist; array* distsp = new array; std::string fname = pasl::util::cmdline::parse_or_default_string("fname", ""); vtxid_type source = pasl::util::cmdline::parse_or_default_long("source", 0l); if (fname == "") pasl::util::atomic::fatal([] { std::cerr << "missing filename for graph: -fname filename"; }); auto init = [=] { graphp->load_from_file(fname); }; auto bench = [=] { *distsp = bfs(*graphp, source); }; auto output = [=] { long nb_visited = sum(map([] (value_type v) { return (v != dist_unknown); }, *distsp)); long max_dist = max(*distsp); std::cout << "nb_visited\t" << nb_visited << std::endl; std::cout << "max_dist\t" << max_dist << std::endl; }; auto destroy = [=] { delete graphp; delete distsp; }; return make_benchmark(init, bench, output, destroy); } /*---------------------------------------------------------------------*/ /* PASL Driver */ int main(int argc, char** argv) { benchmark_type bench; auto init = [&] { pasl::util::cmdline::argmap<std::function<benchmark_type()>> m; m.add("fib", [&] { return fib_bench(); }); m.add("duplicate", [&] { return duplicate_bench(); }); m.add("ktimes", [&] { return ktimes_bench(); }); m.add("reduce", [&] { return reduce_bench(); }); m.add("scan", [&] { return scan_bench(); }); m.add("mcss", [&] { return mcss_bench(); }); m.add("dmdvmult", [&] { return dmdvmult_bench(); }); m.add("sort", [&] { return sort_bench(); }); m.add("graph", [&] { return graph_bench(); }); bench = m.find_by_arg("bench")(); bench_init(bench); }; auto run = [&] (bool) { bench_run(bench); }; auto output = [&] { bench_output(bench); }; auto destroy = [&] { bench_destroy(bench); }; pasl::sched::launch(argc, argv, init, run, output, destroy); } /***********************************************************************/ <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/synchronization/SmallLocks.h> #include <cassert> #include <condition_variable> #include <cstdio> #include <mutex> #include <string> #include <thread> #include <vector> #include <glog/logging.h> #include <folly/Random.h> #include <folly/portability/Asm.h> #include <folly/portability/GFlags.h> #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <folly/portability/PThread.h> #include <folly/portability/Unistd.h> #include <folly/test/TestUtils.h> using folly::MicroLock; using folly::MicroSpinLock; using folly::MSLGuard; #ifdef FOLLY_PICO_SPIN_LOCK_H_ using folly::PicoSpinLock; #endif DEFINE_int64( stress_test_seconds, 2, "Number of seconds for which to run stress tests"); namespace { struct LockedVal { int ar[1024]; MicroSpinLock lock; LockedVal() { lock.init(); memset(ar, 0, sizeof ar); } }; // Compile time test for packed struct support (requires that both of // these classes are POD). FOLLY_PACK_PUSH struct ignore1 { MicroSpinLock msl; int16_t foo; } FOLLY_PACK_ATTR; static_assert(sizeof(ignore1) == 3, "Size check failed"); static_assert(sizeof(MicroSpinLock) == 1, "Size check failed"); #ifdef FOLLY_PICO_SPIN_LOCK_H_ struct ignore2 { PicoSpinLock<uint32_t> psl; int16_t foo; } FOLLY_PACK_ATTR; static_assert(sizeof(ignore2) == 6, "Size check failed"); #endif FOLLY_PACK_POP LockedVal v; void splock_test() { const int max = 1000; auto rng = folly::ThreadLocalPRNG(); for (int i = 0; i < max; i++) { folly::asm_volatile_pause(); MSLGuard g(v.lock); EXPECT_THAT(v.ar, testing::Each(testing::Eq(v.ar[0]))); int byte = folly::Random::rand32(rng); memset(v.ar, char(byte), sizeof v.ar); } } #ifdef FOLLY_PICO_SPIN_LOCK_H_ template <class T> struct PslTest { PicoSpinLock<T> lock; PslTest() { lock.init(); } void doTest() { using UT = typename std::make_unsigned<T>::type; T ourVal = rand() % T(UT(1) << (sizeof(UT) * 8 - 1)); for (int i = 0; i < 100; ++i) { std::lock_guard<PicoSpinLock<T>> guard(lock); lock.setData(ourVal); for (int n = 0; n < 10; ++n) { folly::asm_volatile_pause(); EXPECT_EQ(lock.getData(), ourVal); } } } }; template <class T> void doPslTest() { PslTest<T> testObj; const int nthrs = 17; std::vector<std::thread> threads; for (int i = 0; i < nthrs; ++i) { threads.push_back(std::thread(&PslTest<T>::doTest, &testObj)); } for (auto& t : threads) { t.join(); } } #endif struct TestClobber { TestClobber() { lock_.init(); } void go() { std::lock_guard<MicroSpinLock> g(lock_); // This bug depends on gcc register allocation and is very sensitive. We // have to use DCHECK instead of EXPECT_*. DCHECK(!lock_.try_lock()); } private: MicroSpinLock lock_; }; } // namespace TEST(SmallLocks, SpinLockCorrectness) { EXPECT_EQ(sizeof(MicroSpinLock), 1); int nthrs = sysconf(_SC_NPROCESSORS_ONLN) * 2; std::vector<std::thread> threads; for (int i = 0; i < nthrs; ++i) { threads.push_back(std::thread(splock_test)); } for (auto& t : threads) { t.join(); } } #ifdef FOLLY_PICO_SPIN_LOCK_H_ TEST(SmallLocks, PicoSpinCorrectness) { doPslTest<int16_t>(); doPslTest<uint16_t>(); doPslTest<int32_t>(); doPslTest<uint32_t>(); doPslTest<int64_t>(); doPslTest<uint64_t>(); } TEST(SmallLocks, PicoSpinSigned) { typedef PicoSpinLock<int16_t, 0> Lock; Lock val; val.init(-4); EXPECT_EQ(val.getData(), -4); { std::lock_guard<Lock> guard(val); EXPECT_EQ(val.getData(), -4); val.setData(-8); EXPECT_EQ(val.getData(), -8); } EXPECT_EQ(val.getData(), -8); } TEST(SmallLocks, PicoSpinLockThreadSanitizer) { SKIP_IF(!folly::kIsSanitizeThread) << "Enabled in TSAN mode only"; typedef PicoSpinLock<int16_t, 0> Lock; { Lock a; Lock b; a.init(-8); b.init(-8); { std::lock_guard<Lock> ga(a); std::lock_guard<Lock> gb(b); } { std::lock_guard<Lock> gb(b); EXPECT_DEATH( [&]() { std::lock_guard<Lock> ga(a); }(), "Cycle in lock order graph"); } } } #endif TEST(SmallLocks, RegClobber) { TestClobber().go(); } static_assert(sizeof(MicroLock) == 1, "Size check failed"); namespace { struct SimpleBarrier { SimpleBarrier() : lock_(), cv_(), ready_(false) {} void wait() { std::unique_lock<std::mutex> lockHeld(lock_); while (!ready_) { cv_.wait(lockHeld); } } void run() { { std::unique_lock<std::mutex> lockHeld(lock_); ready_ = true; } cv_.notify_all(); } private: std::mutex lock_; std::condition_variable cv_; bool ready_; }; } // namespace TEST(SmallLocks, MicroLock) { volatile uint64_t counters[4] = {0, 0, 0, 0}; std::vector<std::thread> threads; static const unsigned nrThreads = 20; static const unsigned iterPerThread = 10000; SimpleBarrier startBarrier; assert(iterPerThread % 4 == 0); // Embed the lock in a larger structure to ensure that we do not // affect bits outside the ones MicroLock is defined to affect. struct { uint8_t a; std::atomic<uint8_t> b; MicroLock alock; std::atomic<uint8_t> d; } x; uint8_t origB = 'b'; uint8_t origD = 'd'; x.a = 'a'; x.b = origB; x.alock.init(); x.d = origD; // This thread touches other parts of the host word to show that // MicroLock does not interfere with memory outside of the byte // it owns. std::thread adjacentMemoryToucher = std::thread([&] { startBarrier.wait(); for (unsigned iter = 0; iter < iterPerThread; ++iter) { if (iter % 2) { x.b++; } else { x.d++; } } }); for (unsigned i = 0; i < nrThreads; ++i) { threads.emplace_back([&] { startBarrier.wait(); for (unsigned iter = 0; iter < iterPerThread; ++iter) { unsigned slotNo = iter % 4; x.alock.lock(slotNo); counters[slotNo] += 1; // The occasional sleep makes it more likely that we'll // exercise the futex-wait path inside MicroLock. if (iter % 1000 == 0) { struct timespec ts = {0, 10000}; (void)nanosleep(&ts, nullptr); } x.alock.unlock(slotNo); } }); } startBarrier.run(); for (auto it = threads.begin(); it != threads.end(); ++it) { it->join(); } adjacentMemoryToucher.join(); EXPECT_EQ(x.a, 'a'); EXPECT_EQ(x.b, (uint8_t)(origB + iterPerThread / 2)); EXPECT_EQ(x.d, (uint8_t)(origD + iterPerThread / 2)); for (unsigned i = 0; i < 4; ++i) { EXPECT_EQ(counters[i], ((uint64_t)nrThreads * iterPerThread) / 4); } } TEST(SmallLocks, MicroLockTryLock) { MicroLock lock; lock.init(); EXPECT_TRUE(lock.try_lock()); EXPECT_FALSE(lock.try_lock()); lock.unlock(); } namespace { template <typename Mutex, typename Duration> void simpleStressTest(Duration duration, int numThreads) { auto&& mutex = Mutex{}; auto&& data = std::atomic<std::uint64_t>{0}; auto&& threads = std::vector<std::thread>{}; auto&& stop = std::atomic<bool>{true}; for (auto i = 0; i < numThreads; ++i) { threads.emplace_back([&mutex, &data, &stop] { while (!stop.load(std::memory_order_relaxed)) { auto lck = std::unique_lock<Mutex>{mutex}; EXPECT_EQ(data.fetch_add(1, std::memory_order_relaxed), 0); EXPECT_EQ(data.fetch_sub(1, std::memory_order_relaxed), 1); } }); } std::this_thread::sleep_for(duration); stop.store(true); for (auto& thread : threads) { thread.join(); } } } // namespace TEST(SmallLocks, MicroSpinLockStressTestLockTwoThreads) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; simpleStressTest<MicroSpinLock>(duration, 2); } TEST(SmallLocks, MicroSpinLockStressTestLockHardwareConcurrency) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; auto threads = std::thread::hardware_concurrency(); simpleStressTest<MicroSpinLock>(duration, threads); } TEST(SmallLocks, PicoSpinLockStressTestLockTwoThreads) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; simpleStressTest<PicoSpinLock<std::uint16_t>>(duration, 2); } TEST(SmallLocks, PicoSpinLockStressTestLockHardwareConcurrency) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; auto threads = std::thread::hardware_concurrency(); simpleStressTest<PicoSpinLock<std::uint16_t>>(duration, threads); } namespace { template <typename Mutex> class MutexWrapper { public: void lock() { while (!mutex_.try_lock()) { } } void unlock() { mutex_.unlock(); } Mutex mutex_; }; template <typename Mutex, typename Duration> void simpleStressTestTryLock(Duration duration, int numThreads) { simpleStressTest<MutexWrapper<Mutex>>(duration, numThreads); } } // namespace TEST(SmallLocks, MicroSpinLockStressTestTryLockTwoThreads) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; simpleStressTestTryLock<MicroSpinLock>(duration, 2); } TEST(SmallLocks, MicroSpinLockStressTestTryLockHardwareConcurrency) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; auto threads = std::thread::hardware_concurrency(); simpleStressTestTryLock<MicroSpinLock>(duration, threads); } TEST(SmallLocksk, MicroSpinLockThreadSanitizer) { SKIP_IF(!folly::kIsSanitizeThread) << "Enabled in TSAN mode only"; uint8_t val = 0; static_assert(sizeof(uint8_t) == sizeof(MicroSpinLock), "sanity check"); // make sure TSAN handles this case too: // same lock but initialized via setting a value for (int i = 0; i < 10; i++) { val = 0; std::lock_guard<MicroSpinLock> g(*reinterpret_cast<MicroSpinLock*>(&val)); } { MicroSpinLock a; MicroSpinLock b; a.init(); b.init(); { std::lock_guard<MicroSpinLock> ga(a); std::lock_guard<MicroSpinLock> gb(b); } { std::lock_guard<MicroSpinLock> gb(b); EXPECT_DEATH( [&]() { std::lock_guard<MicroSpinLock> ga(a); }(), "Cycle in lock order graph"); } } { uint8_t a = 0; uint8_t b = 0; { std::lock_guard<MicroSpinLock> ga(*reinterpret_cast<MicroSpinLock*>(&a)); std::lock_guard<MicroSpinLock> gb(*reinterpret_cast<MicroSpinLock*>(&b)); } a = 0; b = 0; { std::lock_guard<MicroSpinLock> gb(*reinterpret_cast<MicroSpinLock*>(&b)); EXPECT_DEATH( [&]() { std::lock_guard<MicroSpinLock> ga( *reinterpret_cast<MicroSpinLock*>(&a)); }(), "Cycle in lock order graph"); } } } TEST(SmallLocks, PicoSpinLockStressTestTryLockTwoThreads) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; simpleStressTestTryLock<PicoSpinLock<std::uint16_t>>(duration, 2); } TEST(SmallLocks, PicoSpinLockStressTestTryLockHardwareConcurrency) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; auto threads = std::thread::hardware_concurrency(); simpleStressTestTryLock<PicoSpinLock<std::uint16_t>>(duration, threads); } <commit_msg>Make SmallLocksTest pass under TSAN if halt_on_error=0.<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/synchronization/SmallLocks.h> #include <cassert> #include <condition_variable> #include <cstdio> #include <mutex> #include <string> #include <thread> #include <vector> #include <glog/logging.h> #include <folly/Random.h> #include <folly/portability/Asm.h> #include <folly/portability/GFlags.h> #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <folly/portability/PThread.h> #include <folly/portability/Unistd.h> #include <folly/test/TestUtils.h> using folly::MicroLock; using folly::MicroSpinLock; using folly::MSLGuard; #ifdef FOLLY_PICO_SPIN_LOCK_H_ using folly::PicoSpinLock; #endif DEFINE_int64( stress_test_seconds, 2, "Number of seconds for which to run stress tests"); namespace { struct LockedVal { int ar[1024]; MicroSpinLock lock; LockedVal() { lock.init(); memset(ar, 0, sizeof ar); } }; // Compile time test for packed struct support (requires that both of // these classes are POD). FOLLY_PACK_PUSH struct ignore1 { MicroSpinLock msl; int16_t foo; } FOLLY_PACK_ATTR; static_assert(sizeof(ignore1) == 3, "Size check failed"); static_assert(sizeof(MicroSpinLock) == 1, "Size check failed"); #ifdef FOLLY_PICO_SPIN_LOCK_H_ struct ignore2 { PicoSpinLock<uint32_t> psl; int16_t foo; } FOLLY_PACK_ATTR; static_assert(sizeof(ignore2) == 6, "Size check failed"); #endif FOLLY_PACK_POP LockedVal v; void splock_test() { const int max = 1000; auto rng = folly::ThreadLocalPRNG(); for (int i = 0; i < max; i++) { folly::asm_volatile_pause(); MSLGuard g(v.lock); EXPECT_THAT(v.ar, testing::Each(testing::Eq(v.ar[0]))); int byte = folly::Random::rand32(rng); memset(v.ar, char(byte), sizeof v.ar); } } #ifdef FOLLY_PICO_SPIN_LOCK_H_ template <class T> struct PslTest { PicoSpinLock<T> lock; PslTest() { lock.init(); } void doTest() { using UT = typename std::make_unsigned<T>::type; T ourVal = rand() % T(UT(1) << (sizeof(UT) * 8 - 1)); for (int i = 0; i < 100; ++i) { std::lock_guard<PicoSpinLock<T>> guard(lock); lock.setData(ourVal); for (int n = 0; n < 10; ++n) { folly::asm_volatile_pause(); EXPECT_EQ(lock.getData(), ourVal); } } } }; template <class T> void doPslTest() { PslTest<T> testObj; const int nthrs = 17; std::vector<std::thread> threads; for (int i = 0; i < nthrs; ++i) { threads.push_back(std::thread(&PslTest<T>::doTest, &testObj)); } for (auto& t : threads) { t.join(); } } #endif struct TestClobber { TestClobber() { lock_.init(); } void go() { std::lock_guard<MicroSpinLock> g(lock_); // This bug depends on gcc register allocation and is very sensitive. We // have to use DCHECK instead of EXPECT_*. DCHECK(!lock_.try_lock()); } private: MicroSpinLock lock_; }; } // namespace TEST(SmallLocks, SpinLockCorrectness) { EXPECT_EQ(sizeof(MicroSpinLock), 1); int nthrs = sysconf(_SC_NPROCESSORS_ONLN) * 2; std::vector<std::thread> threads; for (int i = 0; i < nthrs; ++i) { threads.push_back(std::thread(splock_test)); } for (auto& t : threads) { t.join(); } } #ifdef FOLLY_PICO_SPIN_LOCK_H_ TEST(SmallLocks, PicoSpinCorrectness) { doPslTest<int16_t>(); doPslTest<uint16_t>(); doPslTest<int32_t>(); doPslTest<uint32_t>(); doPslTest<int64_t>(); doPslTest<uint64_t>(); } TEST(SmallLocks, PicoSpinSigned) { typedef PicoSpinLock<int16_t, 0> Lock; Lock val; val.init(-4); EXPECT_EQ(val.getData(), -4); { std::lock_guard<Lock> guard(val); EXPECT_EQ(val.getData(), -4); val.setData(-8); EXPECT_EQ(val.getData(), -8); } EXPECT_EQ(val.getData(), -8); } TEST(SmallLocks, PicoSpinLockThreadSanitizer) { SKIP_IF(!folly::kIsSanitizeThread) << "Enabled in TSAN mode only"; typedef PicoSpinLock<int16_t, 0> Lock; { Lock a; Lock b; a.init(-8); b.init(-8); { std::lock_guard<Lock> ga(a); std::lock_guard<Lock> gb(b); } { std::lock_guard<Lock> gb(b); EXPECT_DEATH( [&]() { std::lock_guard<Lock> ga(a); // If halt_on_error is turned off for TSAN, then death would // happen on exit, so give that a chance as well. std::quick_exit(1); }(), "Cycle in lock order graph"); } } } #endif TEST(SmallLocks, RegClobber) { TestClobber().go(); } static_assert(sizeof(MicroLock) == 1, "Size check failed"); namespace { struct SimpleBarrier { SimpleBarrier() : lock_(), cv_(), ready_(false) {} void wait() { std::unique_lock<std::mutex> lockHeld(lock_); while (!ready_) { cv_.wait(lockHeld); } } void run() { { std::unique_lock<std::mutex> lockHeld(lock_); ready_ = true; } cv_.notify_all(); } private: std::mutex lock_; std::condition_variable cv_; bool ready_; }; } // namespace TEST(SmallLocks, MicroLock) { volatile uint64_t counters[4] = {0, 0, 0, 0}; std::vector<std::thread> threads; static const unsigned nrThreads = 20; static const unsigned iterPerThread = 10000; SimpleBarrier startBarrier; assert(iterPerThread % 4 == 0); // Embed the lock in a larger structure to ensure that we do not // affect bits outside the ones MicroLock is defined to affect. struct { uint8_t a; std::atomic<uint8_t> b; MicroLock alock; std::atomic<uint8_t> d; } x; uint8_t origB = 'b'; uint8_t origD = 'd'; x.a = 'a'; x.b = origB; x.alock.init(); x.d = origD; // This thread touches other parts of the host word to show that // MicroLock does not interfere with memory outside of the byte // it owns. std::thread adjacentMemoryToucher = std::thread([&] { startBarrier.wait(); for (unsigned iter = 0; iter < iterPerThread; ++iter) { if (iter % 2) { x.b++; } else { x.d++; } } }); for (unsigned i = 0; i < nrThreads; ++i) { threads.emplace_back([&] { startBarrier.wait(); for (unsigned iter = 0; iter < iterPerThread; ++iter) { unsigned slotNo = iter % 4; x.alock.lock(slotNo); counters[slotNo] += 1; // The occasional sleep makes it more likely that we'll // exercise the futex-wait path inside MicroLock. if (iter % 1000 == 0) { struct timespec ts = {0, 10000}; (void)nanosleep(&ts, nullptr); } x.alock.unlock(slotNo); } }); } startBarrier.run(); for (auto it = threads.begin(); it != threads.end(); ++it) { it->join(); } adjacentMemoryToucher.join(); EXPECT_EQ(x.a, 'a'); EXPECT_EQ(x.b, (uint8_t)(origB + iterPerThread / 2)); EXPECT_EQ(x.d, (uint8_t)(origD + iterPerThread / 2)); for (unsigned i = 0; i < 4; ++i) { EXPECT_EQ(counters[i], ((uint64_t)nrThreads * iterPerThread) / 4); } } TEST(SmallLocks, MicroLockTryLock) { MicroLock lock; lock.init(); EXPECT_TRUE(lock.try_lock()); EXPECT_FALSE(lock.try_lock()); lock.unlock(); } namespace { template <typename Mutex, typename Duration> void simpleStressTest(Duration duration, int numThreads) { auto&& mutex = Mutex{}; auto&& data = std::atomic<std::uint64_t>{0}; auto&& threads = std::vector<std::thread>{}; auto&& stop = std::atomic<bool>{true}; for (auto i = 0; i < numThreads; ++i) { threads.emplace_back([&mutex, &data, &stop] { while (!stop.load(std::memory_order_relaxed)) { auto lck = std::unique_lock<Mutex>{mutex}; EXPECT_EQ(data.fetch_add(1, std::memory_order_relaxed), 0); EXPECT_EQ(data.fetch_sub(1, std::memory_order_relaxed), 1); } }); } std::this_thread::sleep_for(duration); stop.store(true); for (auto& thread : threads) { thread.join(); } } } // namespace TEST(SmallLocks, MicroSpinLockStressTestLockTwoThreads) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; simpleStressTest<MicroSpinLock>(duration, 2); } TEST(SmallLocks, MicroSpinLockStressTestLockHardwareConcurrency) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; auto threads = std::thread::hardware_concurrency(); simpleStressTest<MicroSpinLock>(duration, threads); } TEST(SmallLocks, PicoSpinLockStressTestLockTwoThreads) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; simpleStressTest<PicoSpinLock<std::uint16_t>>(duration, 2); } TEST(SmallLocks, PicoSpinLockStressTestLockHardwareConcurrency) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; auto threads = std::thread::hardware_concurrency(); simpleStressTest<PicoSpinLock<std::uint16_t>>(duration, threads); } namespace { template <typename Mutex> class MutexWrapper { public: void lock() { while (!mutex_.try_lock()) { } } void unlock() { mutex_.unlock(); } Mutex mutex_; }; template <typename Mutex, typename Duration> void simpleStressTestTryLock(Duration duration, int numThreads) { simpleStressTest<MutexWrapper<Mutex>>(duration, numThreads); } } // namespace TEST(SmallLocks, MicroSpinLockStressTestTryLockTwoThreads) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; simpleStressTestTryLock<MicroSpinLock>(duration, 2); } TEST(SmallLocks, MicroSpinLockStressTestTryLockHardwareConcurrency) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; auto threads = std::thread::hardware_concurrency(); simpleStressTestTryLock<MicroSpinLock>(duration, threads); } TEST(SmallLocksk, MicroSpinLockThreadSanitizer) { SKIP_IF(!folly::kIsSanitizeThread) << "Enabled in TSAN mode only"; uint8_t val = 0; static_assert(sizeof(uint8_t) == sizeof(MicroSpinLock), "sanity check"); // make sure TSAN handles this case too: // same lock but initialized via setting a value for (int i = 0; i < 10; i++) { val = 0; std::lock_guard<MicroSpinLock> g(*reinterpret_cast<MicroSpinLock*>(&val)); } { MicroSpinLock a; MicroSpinLock b; a.init(); b.init(); { std::lock_guard<MicroSpinLock> ga(a); std::lock_guard<MicroSpinLock> gb(b); } { std::lock_guard<MicroSpinLock> gb(b); EXPECT_DEATH( [&]() { std::lock_guard<MicroSpinLock> ga(a); // If halt_on_error is turned off for TSAN, then death would // happen on exit, so give that a chance as well. std::quick_exit(1); }(), "Cycle in lock order graph"); } } { uint8_t a = 0; uint8_t b = 0; { std::lock_guard<MicroSpinLock> ga(*reinterpret_cast<MicroSpinLock*>(&a)); std::lock_guard<MicroSpinLock> gb(*reinterpret_cast<MicroSpinLock*>(&b)); } a = 0; b = 0; { std::lock_guard<MicroSpinLock> gb(*reinterpret_cast<MicroSpinLock*>(&b)); EXPECT_DEATH( [&]() { std::lock_guard<MicroSpinLock> ga( *reinterpret_cast<MicroSpinLock*>(&a)); // If halt_on_error is turned off for TSAN, then death would // happen on exit, so give that a chance as well. std::quick_exit(1); }(), "Cycle in lock order graph"); } } } TEST(SmallLocks, PicoSpinLockStressTestTryLockTwoThreads) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; simpleStressTestTryLock<PicoSpinLock<std::uint16_t>>(duration, 2); } TEST(SmallLocks, PicoSpinLockStressTestTryLockHardwareConcurrency) { auto duration = std::chrono::seconds{FLAGS_stress_test_seconds}; auto threads = std::thread::hardware_concurrency(); simpleStressTestTryLock<PicoSpinLock<std::uint16_t>>(duration, threads); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: matril3d.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:30:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _B3D_MATRIL3D_HXX #include "matril3d.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif /************************************************************************* |* |* Konstruktor B3dMaterial |* \************************************************************************/ B3dMaterial::B3dMaterial() : aAmbient(COL_BLACK), // kein lokales Umgebungslicht aDiffuse(0x00, 0xb8, 0xff), // Blau7 aSpecular(COL_WHITE), // Weisser Glanzpunkt aEmission(COL_BLACK), // Keine Selbstleuchtfarbe nExponent(15) // Glanzpunktbuendelung { } /************************************************************************* |* |* Materialeigenschaft setzen |* \************************************************************************/ void B3dMaterial::SetMaterial(Color rNew, Base3DMaterialValue eVal) { switch(eVal) { case Base3DMaterialAmbient: aAmbient = rNew; break; case Base3DMaterialDiffuse: aDiffuse = rNew; break; case Base3DMaterialSpecular: aSpecular = rNew; break; case Base3DMaterialEmission: aEmission = rNew; break; } } /************************************************************************* |* |* Materialeigenschaft abfragen |* \************************************************************************/ Color B3dMaterial::GetMaterial(Base3DMaterialValue eVal) const { if(eVal == Base3DMaterialAmbient) return aAmbient; if(eVal == Base3DMaterialDiffuse) return aDiffuse; if(eVal == Base3DMaterialEmission) return aEmission; return aSpecular; } /************************************************************************* |* |* Materialeigenschaften setzen, exponent der specular-Eigenschaft |* \************************************************************************/ void B3dMaterial::SetShininess(UINT16 nNew) { nExponent = nNew; } /************************************************************************* |* |* Materialeigenschaften abfragen, exponent der specular-Eigenschaft |* \************************************************************************/ UINT16 B3dMaterial::GetShininess() const { return nExponent; } void B3dMaterial::WriteData(SvStream& rOut) const { rOut << aAmbient; rOut << aDiffuse; rOut << aSpecular; rOut << aEmission; rOut << nExponent; } void B3dMaterial::ReadData(SvStream& rIn) { rIn >> aAmbient; rIn >> aDiffuse; rIn >> aSpecular; rIn >> aEmission; rIn >> nExponent; } /************************************************************************* |* |* Vergleichsoperator |* \************************************************************************/ BOOL B3dMaterial::operator==(const B3dMaterial& rMat) { if(aAmbient == rMat.aAmbient && aDiffuse == rMat.aDiffuse && aSpecular == rMat.aSpecular && aEmission == rMat.aEmission && nExponent == rMat.nExponent) return TRUE; return FALSE; } /************************************************************************* |* |* Bucket fuer geometrische Daten |* \************************************************************************/ BASE3D_IMPL_BUCKET(B3dMaterial, Bucket) <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.326); FILE MERGED 2005/09/05 15:11:54 rt 1.1.1.1.326.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: matril3d.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:29:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _B3D_MATRIL3D_HXX #include "matril3d.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif /************************************************************************* |* |* Konstruktor B3dMaterial |* \************************************************************************/ B3dMaterial::B3dMaterial() : aAmbient(COL_BLACK), // kein lokales Umgebungslicht aDiffuse(0x00, 0xb8, 0xff), // Blau7 aSpecular(COL_WHITE), // Weisser Glanzpunkt aEmission(COL_BLACK), // Keine Selbstleuchtfarbe nExponent(15) // Glanzpunktbuendelung { } /************************************************************************* |* |* Materialeigenschaft setzen |* \************************************************************************/ void B3dMaterial::SetMaterial(Color rNew, Base3DMaterialValue eVal) { switch(eVal) { case Base3DMaterialAmbient: aAmbient = rNew; break; case Base3DMaterialDiffuse: aDiffuse = rNew; break; case Base3DMaterialSpecular: aSpecular = rNew; break; case Base3DMaterialEmission: aEmission = rNew; break; } } /************************************************************************* |* |* Materialeigenschaft abfragen |* \************************************************************************/ Color B3dMaterial::GetMaterial(Base3DMaterialValue eVal) const { if(eVal == Base3DMaterialAmbient) return aAmbient; if(eVal == Base3DMaterialDiffuse) return aDiffuse; if(eVal == Base3DMaterialEmission) return aEmission; return aSpecular; } /************************************************************************* |* |* Materialeigenschaften setzen, exponent der specular-Eigenschaft |* \************************************************************************/ void B3dMaterial::SetShininess(UINT16 nNew) { nExponent = nNew; } /************************************************************************* |* |* Materialeigenschaften abfragen, exponent der specular-Eigenschaft |* \************************************************************************/ UINT16 B3dMaterial::GetShininess() const { return nExponent; } void B3dMaterial::WriteData(SvStream& rOut) const { rOut << aAmbient; rOut << aDiffuse; rOut << aSpecular; rOut << aEmission; rOut << nExponent; } void B3dMaterial::ReadData(SvStream& rIn) { rIn >> aAmbient; rIn >> aDiffuse; rIn >> aSpecular; rIn >> aEmission; rIn >> nExponent; } /************************************************************************* |* |* Vergleichsoperator |* \************************************************************************/ BOOL B3dMaterial::operator==(const B3dMaterial& rMat) { if(aAmbient == rMat.aAmbient && aDiffuse == rMat.aDiffuse && aSpecular == rMat.aSpecular && aEmission == rMat.aEmission && nExponent == rMat.nExponent) return TRUE; return FALSE; } /************************************************************************* |* |* Bucket fuer geometrische Daten |* \************************************************************************/ BASE3D_IMPL_BUCKET(B3dMaterial, Bucket) <|endoftext|>
<commit_before>/* openssl_threading.cc Wolfgang Sourdeau, 15 July 2015 Copyright (c) 2015 Datacratic. All rights reserved. This module registers OpenSSL-specific callbacks required to ensure proper functioning of the library when used in multi-threaded programs. See manpage "CRYPTO_set_dynlock_create_callback" for further details. */ #include <pthread.h> #include <openssl/crypto.h> #include <mutex> #include <vector> #include "jml/arch/threads.h" #include "openssl_threading.h" using namespace std; extern "C" { struct CRYPTO_dynlock_value { std::mutex lock; }; } namespace { std::mutex initLock; bool threadingInit(false); /* basic lock callbacks */ std::vector<pthread_mutex_t> cryptoLocks; /* vector<std::mutex> is not * available */ void lockingFunc(int mode, int n, const char *, int line) { pthread_mutex_t * lock = &cryptoLocks[n]; if (mode & CRYPTO_LOCK) { ::pthread_mutex_lock(lock); } else { ::pthread_mutex_unlock(lock); } } void threadIdFunc(CRYPTO_THREADID * threadIdPtr) { pid_t tid = getpid(); CRYPTO_THREADID_set_numeric(threadIdPtr, tid); } /* dyn lock callbacks */ struct CRYPTO_dynlock_value * dynLockCreateFunc(const char * file, int line) { return new CRYPTO_dynlock_value(); } void dynLockLockFunc(int mode, CRYPTO_dynlock_value * l, const char *, int) { auto & lock = l->lock; if (mode & CRYPTO_LOCK) { lock.lock(); } else { lock.unlock(); } } void dynLockDestroyFunc(CRYPTO_dynlock_value * l, const char *, int) { delete l; } void setupCallbacks() { CRYPTO_set_locking_callback(lockingFunc); CRYPTO_THREADID_set_callback(threadIdFunc); CRYPTO_set_dynlock_create_callback(dynLockCreateFunc); CRYPTO_set_dynlock_lock_callback(dynLockLockFunc); CRYPTO_set_dynlock_destroy_callback(dynLockDestroyFunc); } } void Datacratic:: initOpenSSLThreading() { std::unique_lock<std::mutex> guard(initLock); if (threadingInit) { return; } cryptoLocks.resize(CRYPTO_num_locks()); for (size_t i = 0; i < CRYPTO_num_locks(); i++) { ::pthread_mutex_init(&cryptoLocks[i], NULL); } setupCallbacks(); threadingInit = true; } <commit_msg>PLAT-1002: fixed global dtor mess by making openssl threading use of a non-vector array of C mutexes<commit_after>/* openssl_threading.cc Wolfgang Sourdeau, 15 July 2015 Copyright (c) 2015 Datacratic. All rights reserved. This module registers OpenSSL-specific callbacks required to ensure proper functioning of the library when used in multi-threaded programs. See manpage "CRYPTO_set_dynlock_create_callback" for further details. */ #include <pthread.h> #include <openssl/crypto.h> #include <mutex> #include <vector> #include "jml/arch/threads.h" #include "openssl_threading.h" using namespace std; extern "C" { struct CRYPTO_dynlock_value { std::mutex lock; }; } namespace { std::mutex initLock; bool threadingInit(false); /* basic lock callbacks */ pthread_mutex_t * cryptoLocks; /* vector<std::mutex> is not available */ void lockingFunc(int mode, int n, const char *, int line) { pthread_mutex_t * lock = cryptoLocks + n; if (mode & CRYPTO_LOCK) { ::pthread_mutex_lock(lock); } else { ::pthread_mutex_unlock(lock); } } void threadIdFunc(CRYPTO_THREADID * threadIdPtr) { pid_t tid = getpid(); CRYPTO_THREADID_set_numeric(threadIdPtr, tid); } /* dyn lock callbacks */ struct CRYPTO_dynlock_value * dynLockCreateFunc(const char * file, int line) { return new CRYPTO_dynlock_value(); } void dynLockLockFunc(int mode, CRYPTO_dynlock_value * l, const char *, int) { auto & lock = l->lock; if (mode & CRYPTO_LOCK) { lock.lock(); } else { lock.unlock(); } } void dynLockDestroyFunc(CRYPTO_dynlock_value * l, const char *, int) { delete l; } void setupCallbacks() { CRYPTO_set_locking_callback(lockingFunc); CRYPTO_THREADID_set_callback(threadIdFunc); CRYPTO_set_dynlock_create_callback(dynLockCreateFunc); CRYPTO_set_dynlock_lock_callback(dynLockLockFunc); CRYPTO_set_dynlock_destroy_callback(dynLockDestroyFunc); } } void Datacratic:: initOpenSSLThreading() { std::unique_lock<std::mutex> guard(initLock); if (threadingInit) { return; } size_t maxLocks = CRYPTO_num_locks(); cryptoLocks = new pthread_mutex_t[maxLocks]; for (size_t i = 0; i < CRYPTO_num_locks(); i++) { ::pthread_mutex_init(&cryptoLocks[i], NULL); } setupCallbacks(); threadingInit = true; } <|endoftext|>
<commit_before>/* * LoginServConn.cpp * * Created on: 2013-7-8 * Author: ziteng@mogujie.com */ #include "LoginServConn.h" #include "MsgConn.h" #include "ImUser.h" #include "IM.Other.pb.h" #include "IM.Server.pb.h" #include "ImPduBase.h" #include "public_define.h" using namespace IM::BaseDefine; static ConnMap_t g_login_server_conn_map; static serv_info_t* g_login_server_list; static uint32_t g_login_server_count; static string g_msg_server_ip_addr1; static string g_msg_server_ip_addr2; static uint16_t g_msg_server_port; static uint32_t g_max_conn_cnt; void login_server_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam) { ConnMap_t::iterator it_old; CLoginServConn* pConn = NULL; uint64_t cur_time = get_tick_count(); for (ConnMap_t::iterator it = g_login_server_conn_map.begin(); it != g_login_server_conn_map.end(); ) { it_old = it; it++; pConn = (CLoginServConn*)it_old->second; pConn->OnTimer(cur_time); } // reconnect LoginServer serv_check_reconnect<CLoginServConn>(g_login_server_list, g_login_server_count); } void init_login_serv_conn(serv_info_t* server_list, uint32_t server_count, const char* msg_server_ip_addr1, const char* msg_server_ip_addr2, uint16_t msg_server_port, uint32_t max_conn_cnt) { g_login_server_list = server_list; g_login_server_count = server_count; serv_init<CLoginServConn>(g_login_server_list, g_login_server_count); g_msg_server_ip_addr1 = msg_server_ip_addr1; g_msg_server_ip_addr2 = msg_server_ip_addr2; g_msg_server_port = msg_server_port; g_max_conn_cnt = max_conn_cnt; netlib_register_timer(login_server_conn_timer_callback, NULL, 1000); } // if there is one LoginServer available, return true bool is_login_server_available() { CLoginServConn* pConn = NULL; for (uint32_t i = 0; i < g_login_server_count; i++) { pConn = (CLoginServConn*)g_login_server_list[i].serv_conn; if (pConn && pConn->IsOpen()) { return true; } } return false; } void send_to_all_login_server(CImPdu* pPdu) { CLoginServConn* pConn = NULL; for (uint32_t i = 0; i < g_login_server_count; i++) { pConn = (CLoginServConn*)g_login_server_list[i].serv_conn; if (pConn && pConn->IsOpen()) { pConn->SendPdu(pPdu); } } } CLoginServConn::CLoginServConn() { m_bOpen = false; } CLoginServConn::~CLoginServConn() { } void CLoginServConn::Connect(const char* server_ip, uint16_t server_port, uint32_t serv_idx) { log("Connecting to LoginServer %s:%d ", server_ip, server_port); m_serv_idx = serv_idx; m_handle = netlib_connect(server_ip, server_port, imconn_callback, (void*)&g_login_server_conn_map); if (m_handle != NETLIB_INVALID_HANDLE) { g_login_server_conn_map.insert(make_pair(m_handle, this)); } } void CLoginServConn::Close() { serv_reset<CLoginServConn>(g_login_server_list, g_login_server_count, m_serv_idx); if (m_handle != NETLIB_INVALID_HANDLE) { netlib_close(m_handle); g_login_server_conn_map.erase(m_handle); } ReleaseRef(); } void CLoginServConn::OnConfirm() { log("connect to login server success "); m_bOpen = true; g_login_server_list[m_serv_idx].reconnect_cnt = MIN_RECONNECT_CNT / 2; uint32_t cur_conn_cnt = 0; uint32_t shop_user_cnt = 0; list<user_conn_t> user_conn_list; CImUserManager::GetInstance()->GetUserConnCnt(&user_conn_list, cur_conn_cnt); char hostname[256] = {0}; gethostname(hostname, 256); IM::Server::IMMsgServInfo msg; msg.set_ip1(g_msg_server_ip_addr1); msg.set_ip2(g_msg_server_ip_addr2); msg.set_port(g_msg_server_port); msg.set_max_conn_cnt(g_max_conn_cnt); msg.set_cur_conn_cnt(cur_conn_cnt); msg.set_host_name(hostname); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_OTHER); pdu.SetCommandId(CID_OTHER_MSG_SERV_INFO); SendPdu(&pdu); } void CLoginServConn::OnClose() { log("login server conn onclose, from handle=%d ", m_handle); Close(); } void CLoginServConn::OnTimer(uint64_t curr_tick) { if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) { IM::Other::IMHeartBeat msg; CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_OTHER); pdu.SetCommandId(CID_OTHER_HEARTBEAT); SendPdu(&pdu); } if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) { log("conn to login server timeout "); Close(); } } void CLoginServConn::HandlePdu(CImPdu* pPdu) { //printf("recv pdu_type=%d ", pPdu->GetPduType()); } <commit_msg>Update LoginServConn.cpp<commit_after>/* * LoginServConn.cpp * * Created on: 2013-7-8 * Author: ziteng@mogujie.com */ #include "LoginServConn.h" #include "MsgConn.h" #include "ImUser.h" #include "IM.Other.pb.h" #include "IM.Server.pb.h" #include "ImPduBase.h" #include "public_define.h" using namespace IM::BaseDefine; static ConnMap_t g_login_server_conn_map; static serv_info_t* g_login_server_list; static uint32_t g_login_server_count; static string g_msg_server_ip_addr1; static string g_msg_server_ip_addr2; static uint16_t g_msg_server_port; static uint32_t g_max_conn_cnt; void login_server_conn_timer_callback(void* callback_data, uint8_t msg, uint32_t handle, void* pParam) { ConnMap_t::iterator it_old; CLoginServConn* pConn = NULL; uint64_t cur_time = get_tick_count(); for (ConnMap_t::iterator it = g_login_server_conn_map.begin(); it != g_login_server_conn_map.end(); ) { it_old = it; it++; pConn = (CLoginServConn*)it_old->second; pConn->OnTimer(cur_time); } // reconnect LoginServer serv_check_reconnect<CLoginServConn>(g_login_server_list, g_login_server_count); } void init_login_serv_conn(serv_info_t* server_list, uint32_t server_count, const char* msg_server_ip_addr1, const char* msg_server_ip_addr2, uint16_t msg_server_port, uint32_t max_conn_cnt) { g_login_server_list = server_list; g_login_server_count = server_count; serv_init<CLoginServConn>(g_login_server_list, g_login_server_count); g_msg_server_ip_addr1 = msg_server_ip_addr1; g_msg_server_ip_addr2 = msg_server_ip_addr2; g_msg_server_port = msg_server_port; g_max_conn_cnt = max_conn_cnt; netlib_register_timer(login_server_conn_timer_callback, NULL, 1000); } //--> return true if there is a LoginServer available in g_login_server_list bool is_login_server_available() { CLoginServConn* pConn = NULL; for (uint32_t i = 0; i < g_login_server_count; i++) { pConn = (CLoginServConn*)g_login_server_list[i].serv_conn; if (pConn && pConn->IsOpen()) { return true; } } return false; } void send_to_all_login_server(CImPdu* pPdu) { CLoginServConn* pConn = NULL; for (uint32_t i = 0; i < g_login_server_count; i++) { pConn = (CLoginServConn*)g_login_server_list[i].serv_conn; if (pConn && pConn->IsOpen()) { pConn->SendPdu(pPdu); } } } CLoginServConn::CLoginServConn() { m_bOpen = false; } CLoginServConn::~CLoginServConn() { } //--> connect to loginserver and update g_login_server_conn_map void CLoginServConn::Connect(const char* server_ip, uint16_t server_port, uint32_t serv_idx) { log("Connecting to LoginServer %s:%d ", server_ip, server_port); m_serv_idx = serv_idx; m_handle = netlib_connect(server_ip, server_port, imconn_callback, (void*)&g_login_server_conn_map); if (m_handle != NETLIB_INVALID_HANDLE) { g_login_server_conn_map.insert(make_pair(m_handle, this)); } } void CLoginServConn::Close() { serv_reset<CLoginServConn>(g_login_server_list, g_login_server_count, m_serv_idx); if (m_handle != NETLIB_INVALID_HANDLE) { netlib_close(m_handle); g_login_server_conn_map.erase(m_handle); } ReleaseRef(); } void CLoginServConn::OnConfirm() { log("connect to login server success "); m_bOpen = true; g_login_server_list[m_serv_idx].reconnect_cnt = MIN_RECONNECT_CNT / 2; uint32_t cur_conn_cnt = 0; uint32_t shop_user_cnt = 0; list<user_conn_t> user_conn_list; CImUserManager::GetInstance()->GetUserConnCnt(&user_conn_list, cur_conn_cnt); char hostname[256] = {0}; gethostname(hostname, 256); IM::Server::IMMsgServInfo msg; msg.set_ip1(g_msg_server_ip_addr1); msg.set_ip2(g_msg_server_ip_addr2); msg.set_port(g_msg_server_port); msg.set_max_conn_cnt(g_max_conn_cnt); msg.set_cur_conn_cnt(cur_conn_cnt); msg.set_host_name(hostname); CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_OTHER); pdu.SetCommandId(CID_OTHER_MSG_SERV_INFO); SendPdu(&pdu); } void CLoginServConn::OnClose() { log("login server conn onclose, from handle=%d ", m_handle); Close(); } void CLoginServConn::OnTimer(uint64_t curr_tick) { if (curr_tick > m_last_send_tick + SERVER_HEARTBEAT_INTERVAL) { IM::Other::IMHeartBeat msg; CImPdu pdu; pdu.SetPBMsg(&msg); pdu.SetServiceId(SID_OTHER); pdu.SetCommandId(CID_OTHER_HEARTBEAT); SendPdu(&pdu); } if (curr_tick > m_last_recv_tick + SERVER_TIMEOUT) { log("conn to login server timeout "); Close(); } } void CLoginServConn::HandlePdu(CImPdu* pPdu) { //printf("recv pdu_type=%d ", pPdu->GetPduType()); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkLookupTable.h> #include <mitkTestFixture.h> #include "mitkTestingMacros.h" #include <mitkVector.h> #include <iostream> #include <vtkColorTransferFunction.h> #include <vtkPiecewiseFunction.h> class mitkLookupTableTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkLookupTableTestSuite); MITK_TEST(TestCreateLookupTable); MITK_TEST(TestSetVtkLookupTable); MITK_TEST(TestSetOpacity); MITK_TEST(TestCreateColorTransferFunction); MITK_TEST(TestCreateOpacityTransferFunction); MITK_TEST(TestCreateGradientTransferFunction); CPPUNIT_TEST_SUITE_END(); private: mitk::LookupTable::Pointer m_LookupTable; public: void TestCreateLookupTable() { // let's create an object of our class mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // first test: did this work? // it makes no sense to continue without an object. CPPUNIT_ASSERT_MESSAGE("Testing instantiation", myLookupTable.IsNotNull()); } void TestSetVtkLookupTable () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetTableValue(0, 0.5, 0.5, 0.5, 1.0); lut->SetTableValue(1, 0.5, 0.5, 0.5, 0.5); lut->Build(); myLookupTable->SetVtkLookupTable(lut); // check if the same lookuptable is returned vtkLookupTable *lut2 = myLookupTable->GetVtkLookupTable(); CPPUNIT_ASSERT_MESSAGE("Input and output table are not equal",lut == lut2); lut->Delete(); } void TestSetOpacity() { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetRange(0, 200); lut->SetAlphaRange(0.0, 1.0); lut->Build(); myLookupTable->SetVtkLookupTable(lut); myLookupTable->ChangeOpacityForAll(0.7f); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { CPPUNIT_ASSERT_MESSAGE("Opacity not set for all", mitk::Equal(0.7, lut->GetOpacity(i), 0.01, true)); } vtkIdType tableIndex = 10; myLookupTable->ChangeOpacity(tableIndex, 1.0); double rgba[4]; lut->GetTableValue(tableIndex, rgba); CPPUNIT_ASSERT_MESSAGE("Opacity not set for value", mitk::Equal(1.0, rgba[3], 0.01, true)); } void TestCreateColorTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetRange(0, 255); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction = myLookupTable->CreateColorTransferFunction(); CPPUNIT_ASSERT(colorTransferFunction != 0); vtkIdType numberOfTableEntries = lut->GetNumberOfTableValues(); double rgbaTable[4]; double rgbaFunction[4]; for (int i = 0; i < numberOfTableEntries; ++i) { lut->GetIndexedColor(i, rgbaTable); colorTransferFunction->GetIndexedColor(i, rgbaFunction); CPPUNIT_ASSERT_MESSAGE("Wrong color of transfer function", mitk::Equal(rgbaTable[0], rgbaFunction[0], 0.000001, true) && mitk::Equal(rgbaTable[1], rgbaFunction[1], 0.000001, true) && mitk::Equal(rgbaTable[2], rgbaFunction[2], 0.000001, true) ); } } void TestCreateOpacityTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetAlphaRange(0, 1.0); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer<vtkPiecewiseFunction> opacityTransferFunction = myLookupTable->CreateOpacityTransferFunction(); CPPUNIT_ASSERT(opacityTransferFunction != 0); int funcSize = opacityTransferFunction->GetSize(); double table[funcSize]; double rgba[4]; opacityTransferFunction->GetTable(0, 1, funcSize, table); for (int i = 0; i < funcSize; ++i) { lut->GetIndexedColor(i, rgba); CPPUNIT_ASSERT_MESSAGE("Wrong opacity of transfer function", mitk::Equal(table[i], rgba[3], 0.000001, true) ); } } void TestCreateGradientTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetAlphaRange(0, 0.73); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer<vtkPiecewiseFunction> gradientTransferFunction = myLookupTable->CreateGradientTransferFunction(); CPPUNIT_ASSERT(gradientTransferFunction != 0); int funcSize = gradientTransferFunction->GetSize(); double table[funcSize]; double rgba[4]; gradientTransferFunction->GetTable(0, 1, funcSize, table); for (int i = 0; i < funcSize; ++i) { lut->GetIndexedColor(i, rgba); CPPUNIT_ASSERT_MESSAGE("Wrong opacity of transfer function", mitk::Equal(table[i], rgba[3], 0.000001, true) ); } } }; MITK_TEST_SUITE_REGISTRATION(mitkLookupTable) <commit_msg>COMP fixed dynamic array allocation<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkLookupTable.h> #include <mitkTestFixture.h> #include "mitkTestingMacros.h" #include <mitkVector.h> #include <iostream> #include <vtkColorTransferFunction.h> #include <vtkPiecewiseFunction.h> class mitkLookupTableTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkLookupTableTestSuite); MITK_TEST(TestCreateLookupTable); MITK_TEST(TestSetVtkLookupTable); MITK_TEST(TestSetOpacity); MITK_TEST(TestCreateColorTransferFunction); MITK_TEST(TestCreateOpacityTransferFunction); MITK_TEST(TestCreateGradientTransferFunction); CPPUNIT_TEST_SUITE_END(); private: mitk::LookupTable::Pointer m_LookupTable; public: void TestCreateLookupTable() { // let's create an object of our class mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // first test: did this work? // it makes no sense to continue without an object. CPPUNIT_ASSERT_MESSAGE("Testing instantiation", myLookupTable.IsNotNull()); } void TestSetVtkLookupTable () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetTableValue(0, 0.5, 0.5, 0.5, 1.0); lut->SetTableValue(1, 0.5, 0.5, 0.5, 0.5); lut->Build(); myLookupTable->SetVtkLookupTable(lut); // check if the same lookuptable is returned vtkLookupTable *lut2 = myLookupTable->GetVtkLookupTable(); CPPUNIT_ASSERT_MESSAGE("Input and output table are not equal",lut == lut2); lut->Delete(); } void TestSetOpacity() { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetRange(0, 200); lut->SetAlphaRange(0.0, 1.0); lut->Build(); myLookupTable->SetVtkLookupTable(lut); myLookupTable->ChangeOpacityForAll(0.7f); for (int i = 0; i < lut->GetNumberOfTableValues(); ++i) { CPPUNIT_ASSERT_MESSAGE("Opacity not set for all", mitk::Equal(0.7, lut->GetOpacity(i), 0.01, true)); } vtkIdType tableIndex = 10; myLookupTable->ChangeOpacity(tableIndex, 1.0); double rgba[4]; lut->GetTableValue(tableIndex, rgba); CPPUNIT_ASSERT_MESSAGE("Opacity not set for value", mitk::Equal(1.0, rgba[3], 0.01, true)); } void TestCreateColorTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetRange(0, 255); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction = myLookupTable->CreateColorTransferFunction(); CPPUNIT_ASSERT(colorTransferFunction != 0); vtkIdType numberOfTableEntries = lut->GetNumberOfTableValues(); double rgbaTable[4]; double rgbaFunction[4]; for (int i = 0; i < numberOfTableEntries; ++i) { lut->GetIndexedColor(i, rgbaTable); colorTransferFunction->GetIndexedColor(i, rgbaFunction); CPPUNIT_ASSERT_MESSAGE("Wrong color of transfer function", mitk::Equal(rgbaTable[0], rgbaFunction[0], 0.000001, true) && mitk::Equal(rgbaTable[1], rgbaFunction[1], 0.000001, true) && mitk::Equal(rgbaTable[2], rgbaFunction[2], 0.000001, true) ); } } void TestCreateOpacityTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetAlphaRange(0, 1.0); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer<vtkPiecewiseFunction> opacityTransferFunction = myLookupTable->CreateOpacityTransferFunction(); CPPUNIT_ASSERT(opacityTransferFunction != 0); int funcSize = opacityTransferFunction->GetSize(); double *table = new double[funcSize]; double rgba[4]; opacityTransferFunction->GetTable(0, 1, funcSize, table); for (int i = 0; i < funcSize; ++i) { lut->GetIndexedColor(i, rgba); CPPUNIT_ASSERT_MESSAGE("Wrong opacity of transfer function", mitk::Equal(table[i], rgba[3], 0.000001, true) ); } delete [] table; } void TestCreateGradientTransferFunction () { mitk::LookupTable::Pointer myLookupTable = mitk::LookupTable::New(); // create a vtkLookupTable and add two values vtkLookupTable *lut = vtkLookupTable::New(); lut->SetAlphaRange(0, 0.73); lut->Build(); myLookupTable->SetVtkLookupTable(lut); vtkSmartPointer<vtkPiecewiseFunction> gradientTransferFunction = myLookupTable->CreateGradientTransferFunction(); CPPUNIT_ASSERT(gradientTransferFunction != 0); int funcSize = gradientTransferFunction->GetSize(); double *table = new double[funcSize]; double rgba[4]; gradientTransferFunction->GetTable(0, 1, funcSize, table); for (int i = 0; i < funcSize; ++i) { lut->GetIndexedColor(i, rgba); CPPUNIT_ASSERT_MESSAGE("Wrong opacity of transfer function", mitk::Equal(table[i], rgba[3], 0.000001, true) ); } delete [] table; } }; MITK_TEST_SUITE_REGISTRATION(mitkLookupTable) <|endoftext|>
<commit_before>#include "PlaneGeometry.h" #include <vtkTransform.h> //##ModelId=3E395F22035A mitk::PlaneGeometry::PlaneGeometry() : Geometry2D(10.0, 10.0), m_ScaleFactorMMPerUnitX(1.0), m_ScaleFactorMMPerUnitY(1.0) { } //##ModelId=3E395F220382 mitk::PlaneGeometry::~PlaneGeometry() { } //##ModelId=3E395E3E0077 const mitk::PlaneView& mitk::PlaneGeometry::GetPlaneView() const { return m_PlaneView; } //##ModelId=3E396ABE0385 void mitk::PlaneGeometry::SetPlaneView(const mitk::PlaneView& aPlaneView) { m_PlaneView=aPlaneView; m_WidthInUnits = m_PlaneView.getOrientation1().length(); m_HeightInUnits = m_PlaneView.getOrientation2().length(); m_ScaleFactorMMPerUnitX=m_PlaneView.getOrientation1().length()/m_WidthInUnits; m_ScaleFactorMMPerUnitY=m_PlaneView.getOrientation2().length()/m_HeightInUnits; Modified(); } //##ModelId=3E3AEB7C001C itk::Transform<float,3,2>::Pointer mitk::PlaneGeometry::GetTransfrom() const { itkExceptionMacro("Transform not yet supported."); return NULL; } //##ModelId=3E3B9C6E02B5 void mitk::PlaneGeometry::Map(const mitk::Point3D &pt3d_mm, mitk::Point2D &pt2d_mm) const { m_PlaneView.map(pt3d_mm, pt2d_mm); } //##ModelId=3E3B9C7101BF void mitk::PlaneGeometry::Map(const mitk::Point2D &pt2d_mm, mitk::Point3D &pt3d_mm) const { m_PlaneView.map(pt2d_mm, pt3d_mm); } //##ModelId=3E3B9C730262 void mitk::PlaneGeometry::UnitsToMM(const mitk::Point2D &pt_units, mitk::Point2D &pt_mm) const { pt_mm.x=m_ScaleFactorMMPerUnitX*pt_units.x; pt_mm.y=m_ScaleFactorMMPerUnitY*pt_units.y; } //##ModelId=3E3B9C760112 void mitk::PlaneGeometry::MMToUnits(const mitk::Point2D &pt_mm, mitk::Point2D &pt_units) const { pt_units.x=pt_mm.x*(1.0/m_ScaleFactorMMPerUnitX); pt_units.y=pt_mm.y*(1.0/m_ScaleFactorMMPerUnitY); } //##ModelId=3E3B9C8C0145 void mitk::PlaneGeometry::UnitsToMM(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_mm) const { vec_mm.x=m_ScaleFactorMMPerUnitX*vec_units.x; vec_mm.y=m_ScaleFactorMMPerUnitY*vec_units.y; } //##ModelId=3E3B9C8E0152 void mitk::PlaneGeometry::MMToUnits(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_units) const { vec_units.x=vec_mm.x*(1.0/m_ScaleFactorMMPerUnitX); vec_units.y=vec_mm.y*(1.0/m_ScaleFactorMMPerUnitY); } //##ModelId=3ED91D060363 void mitk::PlaneGeometry::TransformGeometry(const vtkTransform * transform) { float p[3], n[3]; // the const_casts in the following are safe, since the used TransformNormalAtPoint/TransformPoint methods // do not change anything vec2vtk(m_PlaneView.normal, n); const_cast<vtkTransform *>(transform)->TransformNormalAtPoint(p, n, n); vtk2vec(n, m_PlaneView.normal); vec2vtk(m_PlaneView.point, p); const_cast<vtkTransform *>(transform)->TransformPoint(p, p); vtk2vec(p, m_PlaneView.point); }<commit_msg>completed initializer list<commit_after>#include "PlaneGeometry.h" #include <vtkTransform.h> //##ModelId=3E395F22035A mitk::PlaneGeometry::PlaneGeometry() : Geometry2D(10.0, 10.0), m_ScaleFactorMMPerUnitX(1.0), m_ScaleFactorMMPerUnitY(1.0) { } //##ModelId=3E395F220382 mitk::PlaneGeometry::~PlaneGeometry() { } //##ModelId=3E395E3E0077 const mitk::PlaneView& mitk::PlaneGeometry::GetPlaneView() const { return m_PlaneView; } //##ModelId=3E396ABE0385 void mitk::PlaneGeometry::SetPlaneView(const mitk::PlaneView& aPlaneView) { m_PlaneView=aPlaneView; m_WidthInUnits = m_PlaneView.getOrientation1().length(); m_HeightInUnits = m_PlaneView.getOrientation2().length(); m_ScaleFactorMMPerUnitX=m_PlaneView.getOrientation1().length()/m_WidthInUnits; m_ScaleFactorMMPerUnitY=m_PlaneView.getOrientation2().length()/m_HeightInUnits; Modified(); } //##ModelId=3E3AEB7C001C itk::Transform<float,3,2>::Pointer mitk::PlaneGeometry::GetTransfrom() const { itkExceptionMacro("Transform not yet supported."); return NULL; } //##ModelId=3E3B9C6E02B5 void mitk::PlaneGeometry::Map(const mitk::Point3D &pt3d_mm, mitk::Point2D &pt2d_mm) const { m_PlaneView.map(pt3d_mm, pt2d_mm); } //##ModelId=3E3B9C7101BF void mitk::PlaneGeometry::Map(const mitk::Point2D &pt2d_mm, mitk::Point3D &pt3d_mm) const { m_PlaneView.map(pt2d_mm, pt3d_mm); } //##ModelId=3E3B9C730262 void mitk::PlaneGeometry::UnitsToMM(const mitk::Point2D &pt_units, mitk::Point2D &pt_mm) const { pt_mm.x=m_ScaleFactorMMPerUnitX*pt_units.x; pt_mm.y=m_ScaleFactorMMPerUnitY*pt_units.y; } //##ModelId=3E3B9C760112 void mitk::PlaneGeometry::MMToUnits(const mitk::Point2D &pt_mm, mitk::Point2D &pt_units) const { pt_units.x=pt_mm.x*(1.0/m_ScaleFactorMMPerUnitX); pt_units.y=pt_mm.y*(1.0/m_ScaleFactorMMPerUnitY); } //##ModelId=3E3B9C8C0145 void mitk::PlaneGeometry::UnitsToMM(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_mm) const { vec_mm.x=m_ScaleFactorMMPerUnitX*vec_units.x; vec_mm.y=m_ScaleFactorMMPerUnitY*vec_units.y; } //##ModelId=3E3B9C8E0152 void mitk::PlaneGeometry::MMToUnits(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_units) const { vec_units.x=vec_mm.x*(1.0/m_ScaleFactorMMPerUnitX); vec_units.y=vec_mm.y*(1.0/m_ScaleFactorMMPerUnitY); } //##ModelId=3ED91D060363 void mitk::PlaneGeometry::TransformGeometry(const vtkTransform * transform) { float p[3], n[3]; // the const_casts in the following are safe, since the used TransformNormalAtPoint/TransformPoint methods // do not change anything vec2vtk(m_PlaneView.normal, n); const_cast<vtkTransform *>(transform)->TransformNormalAtPoint(p, n, n); vtk2vec(n, m_PlaneView.normal); vec2vtk(m_PlaneView.point, p); const_cast<vtkTransform *>(transform)->TransformPoint(p, p); vtk2vec(p, m_PlaneView.point); }<|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2020 Alberto Gonzalez <boqwxp@airmail.cc> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct PrintAttrsPass : public Pass { PrintAttrsPass() : Pass("printattrs", "print attributes of selected objects") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" printattrs [selection]\n"); log("\n"); log("Print all attributes of the selected objects.\n"); log("\n"); log("\n"); } static void log_const(const RTLIL::IdString &s, const RTLIL::Const &x, const unsigned int indent) { if (x.flags == RTLIL::CONST_FLAG_STRING) log("%s(* %s=\"%s\" *)\n", stringf(stringf("%%%ds", indent).c_str(), " ").c_str(), log_id(s), x.decode_string().c_str()); else if (x.flags == RTLIL::CONST_FLAG_NONE) log("%s(* %s=%s *)\n", stringf(stringf("%%%ds", indent).c_str(), " ").c_str(), log_id(s), x.as_string().c_str()); else log_assert(x.flags == RTLIL::CONST_FLAG_STRING || x.flags == RTLIL::CONST_FLAG_NONE); //intended to fail } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { size_t argidx = 1; extra_args(args, argidx, design); unsigned int indent = 0; for (auto mod : design->selected_modules()) { if (design->selected_whole_module(mod)) { log("%s%s\n", stringf(stringf("%%%ds", indent).c_str(), " ").c_str(), log_id(mod->name)); indent += 2; for (auto &it : mod->attributes) log_const(it.first, it.second, indent); } for (auto cell : mod->selected_cells()) { log("%s%s\n", stringf(stringf("%%%ds", indent).c_str(), " ").c_str(), log_id(cell->name)); indent += 2; for (auto &it : cell->attributes) log_const(it.first, it.second, indent); indent -= 2; } for (auto wire : mod->selected_wires()) { log("%s%s\n", stringf(stringf("%%%ds", indent).c_str(), " ").c_str(), log_id(wire->name)); indent += 2; for (auto &it : wire->attributes) log_const(it.first, it.second, indent); indent -= 2; } if (design->selected_whole_module(mod)) indent -= 2; } log("\n"); } } PrintAttrsPass; PRIVATE_NAMESPACE_END <commit_msg>printattrs: Refactor indentation string building for clarity.<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2020 Alberto Gonzalez <boqwxp@airmail.cc> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct PrintAttrsPass : public Pass { PrintAttrsPass() : Pass("printattrs", "print attributes of selected objects") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" printattrs [selection]\n"); log("\n"); log("Print all attributes of the selected objects.\n"); log("\n"); log("\n"); } static std::string get_indent_str(const unsigned int indent) { //Build the format string (e.g. "%4s") std::string format_str = stringf("%%%ds", indent); return stringf(format_str.c_str(), " "); //Use the format string with " " as %s } static void log_const(const RTLIL::IdString &s, const RTLIL::Const &x, const unsigned int indent) { if (x.flags == RTLIL::CONST_FLAG_STRING) log("%s(* %s=\"%s\" *)\n", get_indent_str(indent).c_str(), log_id(s), x.decode_string().c_str()); else if (x.flags == RTLIL::CONST_FLAG_NONE) log("%s(* %s=%s *)\n", get_indent_str(indent).c_str(), log_id(s), x.as_string().c_str()); else log_assert(x.flags == RTLIL::CONST_FLAG_STRING || x.flags == RTLIL::CONST_FLAG_NONE); //intended to fail } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { size_t argidx = 1; extra_args(args, argidx, design); unsigned int indent = 0; for (auto mod : design->selected_modules()) { if (design->selected_whole_module(mod)) { log("%s%s\n", get_indent_str(indent).c_str(), log_id(mod->name)); indent += 2; for (auto &it : mod->attributes) log_const(it.first, it.second, indent); } for (auto cell : mod->selected_cells()) { log("%s%s\n", get_indent_str(indent).c_str(), log_id(cell->name)); indent += 2; for (auto &it : cell->attributes) log_const(it.first, it.second, indent); indent -= 2; } for (auto wire : mod->selected_wires()) { log("%s%s\n", get_indent_str(indent).c_str(), log_id(wire->name)); indent += 2; for (auto &it : wire->attributes) log_const(it.first, it.second, indent); indent -= 2; } if (design->selected_whole_module(mod)) indent -= 2; } log("\n"); } } PrintAttrsPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <iostream> #include <list> #include <process/process.hpp> #include "common/foreach.hpp" #include "common/resources.hpp" #include "common/seconds.hpp" #include "common/try.hpp" #include "monitoring/linux/proc_resource_collector.hpp" #include "monitoring/linux/proc_utils.hpp" using process::Clock; using std::ios_base; using std::list; namespace mesos { namespace internal { namespace monitoring { inline Try<seconds> initialTryValue() { return Try<seconds>::error("initial value"); } ProcResourceCollector::ProcResourceCollector(pid_t _rootPid) : rootPid(_rootPid), isInitialized(false), currentMemUsage(Try<double>::error("initial value")), currentCpuUsage(initialTryValue()), currentTimestamp(initialTryValue()), prevCpuUsage(initialTryValue()), prevTimestamp(initialTryValue()) {} ProcResourceCollector::~ProcResourceCollector() {} Try<double> ProcResourceCollector::getMemoryUsage() { return currentMemUsage; } Try<Rate> ProcResourceCollector::getCpuUsage() { if (currentCpuUsage.isSome() && currentTimestamp.isSome() && prevCpuUsage.isSome() && prevTimestamp.isSome()) { return Rate(currentTimestamp.get().value - prevTimestamp.get().value, currentCpuUsage.get().value - prevCpuUsage.get().value); } else if (prevTimestamp.isError()) { // This only happens when process start time lookup fails. Might as // well report this first. return Try<Rate>::error(prevTimestamp.error()); } else { return Try<Rate>::error(currentCpuUsage.error()); } } void ProcResourceCollector::collectUsage() { updatePreviousUsage(); // Read the process stats. Try<list<ProcessStats> > tryProcessTree = getProcessTreeStats(); if (tryProcessTree.isError()) { currentMemUsage = Try<double>::error(tryProcessTree.error()); currentCpuUsage = Try<seconds>::error(tryProcessTree.error()); currentTimestamp = Try<seconds>::error(tryProcessTree.error()); return; } list<ProcessStats> processTree = tryProcessTree.get(); // Success, so roll over previous usage. prevTimestamp = currentTimestamp; prevCpuUsage = currentCpuUsage; // Sum up the current resource usage stats. double cpuUsageTicks, memUsage; aggregateResourceUsage(processTree, memUsage, cpuUsageTicks); // TODO(adegtiar): do this via cast? currentMemUsage = Try<double>::some(memUsage); currentCpuUsage = Try<seconds>::some(seconds(cpuUsageTicks)); currentTimestamp = Try<seconds>::some(seconds(Clock::now())); } void ProcResourceCollector::updatePreviousUsage() { if (!isInitialized) { prevCpuUsage = Try<seconds>::some(seconds(0)); prevTimestamp = getStartTime(rootPid); isInitialized = true; } else if (currentMemUsage.isSome() && currentCpuUsage.isSome()) { // Roll over prev usage from current usage. prevCpuUsage = currentCpuUsage; prevTimestamp = currentTimestamp; } // else keep previous usage. } // TODO(adegtiar): consider doing a full tree walk. Try<list<ProcessStats> > ProcResourceCollector::getProcessTreeStats() { list<ProcessStats> processTree; Try<ProcessStats> tryRootStats = getProcessStats(rootPid); if (tryRootStats.isError()) { return Try<list<ProcessStats> >::error(tryRootStats.error()); } ProcessStats rootProcess = tryRootStats.get(); Try<list<pid_t> > allPidsTry = getAllPids(); if (allPidsTry.isError()) { return Try<list<ProcessStats> >::error(allPidsTry.error()); } list<pid_t> allPids = allPidsTry.get(); // Attempt to add all process in the same tree by checking for: // 1) Direct child via match on ppid. // 2) Same process group as root. // 3) Same session as root. foreach (pid_t pid, allPids) { Try<ProcessStats> tryNextProcess = getProcessStats(pid); if (tryNextProcess.isSome()) { ProcessStats nextProcess = tryNextProcess.get(); if (nextProcess.ppid == rootProcess.ppid || nextProcess.pgrp == rootProcess.pgrp || nextProcess.sid == rootProcess.sid) { processTree.push_back(nextProcess); } } // else process must have died in between calls. } return processTree; } void ProcResourceCollector::aggregateResourceUsage( const list<ProcessStats>& processes, double& memTotal, double& cpuTotal) { memTotal = 0; cpuTotal = 0; foreach (const ProcessStats& pinfo, processes) { memTotal += pinfo.memUsage; cpuTotal += pinfo.cpuTime.value; } } } // namespace monitoring { } // namespace internal { } // namespace mesos { <commit_msg>Switching to implicit Try constructor<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <iostream> #include <list> #include <process/process.hpp> #include "common/foreach.hpp" #include "common/resources.hpp" #include "common/seconds.hpp" #include "common/try.hpp" #include "monitoring/linux/proc_resource_collector.hpp" #include "monitoring/linux/proc_utils.hpp" using process::Clock; using std::ios_base; using std::list; namespace mesos { namespace internal { namespace monitoring { inline Try<seconds> initialTryValue() { return Try<seconds>::error("initial value"); } ProcResourceCollector::ProcResourceCollector(pid_t _rootPid) : rootPid(_rootPid), isInitialized(false), currentMemUsage(Try<double>::error("initial value")), currentCpuUsage(initialTryValue()), currentTimestamp(initialTryValue()), prevCpuUsage(initialTryValue()), prevTimestamp(initialTryValue()) {} ProcResourceCollector::~ProcResourceCollector() {} Try<double> ProcResourceCollector::getMemoryUsage() { return currentMemUsage; } Try<Rate> ProcResourceCollector::getCpuUsage() { if (currentCpuUsage.isSome() && currentTimestamp.isSome() && prevCpuUsage.isSome() && prevTimestamp.isSome()) { return Rate(currentTimestamp.get().value - prevTimestamp.get().value, currentCpuUsage.get().value - prevCpuUsage.get().value); } else if (prevTimestamp.isError()) { // This only happens when process start time lookup fails. Might as // well report this first. return Try<Rate>::error(prevTimestamp.error()); } else { return Try<Rate>::error(currentCpuUsage.error()); } } void ProcResourceCollector::collectUsage() { updatePreviousUsage(); // Read the process stats. Try<list<ProcessStats> > tryProcessTree = getProcessTreeStats(); if (tryProcessTree.isError()) { currentMemUsage = Try<double>::error(tryProcessTree.error()); currentCpuUsage = Try<seconds>::error(tryProcessTree.error()); currentTimestamp = Try<seconds>::error(tryProcessTree.error()); return; } list<ProcessStats> processTree = tryProcessTree.get(); // Success, so roll over previous usage. prevTimestamp = currentTimestamp; prevCpuUsage = currentCpuUsage; // Sum up the current resource usage stats. double cpuUsageTicks, memUsage; aggregateResourceUsage(processTree, memUsage, cpuUsageTicks); // TODO(adegtiar): do this via cast? currentMemUsage = memUsage; currentCpuUsage = seconds(cpuUsageTicks); currentTimestamp = seconds(Clock::now()); } void ProcResourceCollector::updatePreviousUsage() { if (!isInitialized) { prevCpuUsage = seconds(0); prevTimestamp = getStartTime(rootPid); isInitialized = true; } else if (currentMemUsage.isSome() && currentCpuUsage.isSome()) { // Roll over prev usage from current usage. prevCpuUsage = currentCpuUsage; prevTimestamp = currentTimestamp; } // else keep previous usage. } // TODO(adegtiar): consider doing a full tree walk. Try<list<ProcessStats> > ProcResourceCollector::getProcessTreeStats() { list<ProcessStats> processTree; Try<ProcessStats> tryRootStats = getProcessStats(rootPid); if (tryRootStats.isError()) { return Try<list<ProcessStats> >::error(tryRootStats.error()); } ProcessStats rootProcess = tryRootStats.get(); Try<list<pid_t> > allPidsTry = getAllPids(); if (allPidsTry.isError()) { return Try<list<ProcessStats> >::error(allPidsTry.error()); } list<pid_t> allPids = allPidsTry.get(); // Attempt to add all process in the same tree by checking for: // 1) Direct child via match on ppid. // 2) Same process group as root. // 3) Same session as root. foreach (pid_t pid, allPids) { Try<ProcessStats> tryNextProcess = getProcessStats(pid); if (tryNextProcess.isSome()) { ProcessStats nextProcess = tryNextProcess.get(); if (nextProcess.ppid == rootProcess.ppid || nextProcess.pgrp == rootProcess.pgrp || nextProcess.sid == rootProcess.sid) { processTree.push_back(nextProcess); } } // else process must have died in between calls. } return processTree; } void ProcResourceCollector::aggregateResourceUsage( const list<ProcessStats>& processes, double& memTotal, double& cpuTotal) { memTotal = 0; cpuTotal = 0; foreach (const ProcessStats& pinfo, processes) { memTotal += pinfo.memUsage; cpuTotal += pinfo.cpuTime.value; } } } // namespace monitoring { } // namespace internal { } // namespace mesos { <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct Clk2fflogicPass : public Pass { Clk2fflogicPass() : Pass("clk2fflogic", "convert clocked FFs to generic $ff cells") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" clk2fflogic [options] [selection]\n"); log("\n"); log("This command replaces clocked flip-flops with generic $ff cells that use the\n"); log("implicit global clock. This is useful for formal verification of designs with\n"); log("multiple clocks.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { // bool flag_noinit = false; log_header(design, "Executing CLK2FFLOGIC pass (convert clocked FFs to generic $ff cells).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-noinit") { // flag_noinit = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) { SigMap sigmap(module); dict<SigBit, State> initbits; pool<SigBit> del_initbits; for (auto wire : module->wires()) if (wire->attributes.count("\\init") > 0) { Const initval = wire->attributes.at("\\init"); SigSpec initsig = sigmap(wire); for (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++) if (initval[i] == State::S0 || initval[i] == State::S1) initbits[initsig[i]] = initval[i]; } for (auto cell : vector<Cell*>(module->selected_cells())) { if (cell->type.in("$mem")) { log_error("Currently there is no support for memories in clk2fflogic. Run memory_map first to convert memories to logic.\n"); } if (cell->type.in("$dlatch")) { bool enpol = cell->parameters["\\EN_POLARITY"].as_bool(); SigSpec sig_en = cell->getPort("\\EN"); SigSpec sig_d = cell->getPort("\\D"); SigSpec sig_q = cell->getPort("\\Q"); log("Replacing %s.%s (%s): EN=%s, D=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(sig_en), log_signal(sig_d), log_signal(sig_q)); Wire *past_q = module->addWire(NEW_ID, GetSize(sig_q)); module->addFf(NEW_ID, sig_q, past_q); if (enpol) module->addMux(NEW_ID, past_q, sig_d, sig_en, sig_q); else module->addMux(NEW_ID, sig_d, past_q, sig_en, sig_q); Const initval; bool assign_initval = false; for (int i = 0; i < GetSize(sig_d); i++) { SigBit qbit = sigmap(sig_q[i]); if (initbits.count(qbit)) { initval.bits.push_back(initbits.at(qbit)); del_initbits.insert(qbit); } else initval.bits.push_back(State::Sx); if (initval.bits.back() != State::Sx) assign_initval = true; } if (assign_initval) past_q->attributes["\\init"] = initval; module->remove(cell); continue; } if (cell->type.in("$dff", "$adff", "$dffsr")) { bool clkpol = cell->parameters["\\CLK_POLARITY"].as_bool(); SigSpec clk = cell->getPort("\\CLK"); Wire *past_clk = module->addWire(NEW_ID); past_clk->attributes["\\init"] = clkpol ? State::S1 : State::S0; module->addFf(NEW_ID, clk, past_clk); SigSpec sig_d = cell->getPort("\\D"); SigSpec sig_q = cell->getPort("\\Q"); log("Replacing %s.%s (%s): CLK=%s, D=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(clk), log_signal(sig_d), log_signal(sig_q)); SigSpec clock_edge_pattern; if (clkpol) { clock_edge_pattern.append_bit(State::S0); clock_edge_pattern.append_bit(State::S1); } else { clock_edge_pattern.append_bit(State::S1); clock_edge_pattern.append_bit(State::S0); } SigSpec clock_edge = module->Eqx(NEW_ID, {clk, SigSpec(past_clk)}, clock_edge_pattern); Wire *past_d = module->addWire(NEW_ID, GetSize(sig_d)); Wire *past_q = module->addWire(NEW_ID, GetSize(sig_q)); module->addFf(NEW_ID, sig_d, past_d); module->addFf(NEW_ID, sig_q, past_q); if (cell->type == "$adff") { SigSpec arst = cell->getPort("\\ARST"); SigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge); Const rstval = cell->parameters["\\ARST_VALUE"]; if (cell->parameters["\\ARST_POLARITY"].as_bool()) module->addMux(NEW_ID, qval, rstval, arst, sig_q); else module->addMux(NEW_ID, rstval, qval, arst, sig_q); } else if (cell->type == "$dffsr") { SigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge); SigSpec setval = cell->getPort("\\SET"); SigSpec clrval = cell->getPort("\\CLR"); if (!cell->parameters["\\SET_POLARITY"].as_bool()) setval = module->Not(NEW_ID, setval); if (cell->parameters["\\CLR_POLARITY"].as_bool()) clrval = module->Not(NEW_ID, clrval); qval = module->Or(NEW_ID, qval, setval); module->addAnd(NEW_ID, qval, clrval, sig_q); } else { module->addMux(NEW_ID, past_q, past_d, clock_edge, sig_q); } Const initval; bool assign_initval = false; for (int i = 0; i < GetSize(sig_d); i++) { SigBit qbit = sigmap(sig_q[i]); if (initbits.count(qbit)) { initval.bits.push_back(initbits.at(qbit)); del_initbits.insert(qbit); } else initval.bits.push_back(State::Sx); if (initval.bits.back() != State::Sx) assign_initval = true; } if (assign_initval) { past_d->attributes["\\init"] = initval; past_q->attributes["\\init"] = initval; } module->remove(cell); continue; } } for (auto wire : module->wires()) if (wire->attributes.count("\\init") > 0) { bool delete_initattr = true; Const initval = wire->attributes.at("\\init"); SigSpec initsig = sigmap(wire); for (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++) if (del_initbits.count(initsig[i]) > 0) initval[i] = State::Sx; else if (initval[i] != State::Sx) delete_initattr = false; if (delete_initattr) wire->attributes.erase("\\init"); else wire->attributes.at("\\init") = initval; } } } } Clk2fflogicPass; PRIVATE_NAMESPACE_END <commit_msg>Add clk2fflogic memory support<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct Clk2fflogicPass : public Pass { Clk2fflogicPass() : Pass("clk2fflogic", "convert clocked FFs to generic $ff cells") { } virtual void help() { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" clk2fflogic [options] [selection]\n"); log("\n"); log("This command replaces clocked flip-flops with generic $ff cells that use the\n"); log("implicit global clock. This is useful for formal verification of designs with\n"); log("multiple clocks.\n"); log("\n"); } virtual void execute(std::vector<std::string> args, RTLIL::Design *design) { // bool flag_noinit = false; log_header(design, "Executing CLK2FFLOGIC pass (convert clocked FFs to generic $ff cells).\n"); size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { // if (args[argidx] == "-noinit") { // flag_noinit = true; // continue; // } break; } extra_args(args, argidx, design); for (auto module : design->selected_modules()) { SigMap sigmap(module); dict<SigBit, State> initbits; pool<SigBit> del_initbits; for (auto wire : module->wires()) if (wire->attributes.count("\\init") > 0) { Const initval = wire->attributes.at("\\init"); SigSpec initsig = sigmap(wire); for (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++) if (initval[i] == State::S0 || initval[i] == State::S1) initbits[initsig[i]] = initval[i]; } for (auto cell : vector<Cell*>(module->selected_cells())) { if (cell->type.in("$mem")) { int abits = cell->getParam("\\ABITS").as_int(); int width = cell->getParam("\\WIDTH").as_int(); int rd_ports = cell->getParam("\\RD_PORTS").as_int(); int wr_ports = cell->getParam("\\WR_PORTS").as_int(); for (int i = 0; i < rd_ports; i++) { if (cell->getParam("\\RD_CLK_ENABLE").extract(i).as_bool()) log_error("Read port %d of memory %s.%s is clocked. This is not supported by \"clk2fflogic\"! " "Call \"memory\" with -nordff to avoid this error.\n", i, log_id(cell), log_id(module)); } Const wr_clk_en_param = cell->getParam("\\WR_CLK_ENABLE"); Const wr_clk_pol_param = cell->getParam("\\WR_CLK_POLARITY"); SigSpec wr_clk_port = cell->getPort("\\WR_CLK"); SigSpec wr_en_port = cell->getPort("\\WR_EN"); SigSpec wr_addr_port = cell->getPort("\\WR_ADDR"); SigSpec wr_data_port = cell->getPort("\\WR_DATA"); for (int wport = 0; wport < wr_ports; wport++) { bool clken = wr_clk_en_param[wport] == State::S1; bool clkpol = wr_clk_pol_param[wport] == State::S1; if (!clken) continue; SigBit clk = wr_clk_port[wport]; SigSpec en = wr_en_port.extract(wport*width, width); SigSpec addr = wr_addr_port.extract(wport*abits, abits); SigSpec data = wr_data_port.extract(wport*width, width); log("Modifying write port %d on memory %s.%s: CLK=%s, A=%s, D=%s\n", wport, log_id(module), log_id(cell), log_signal(clk), log_signal(addr), log_signal(data)); Wire *past_clk = module->addWire(NEW_ID); past_clk->attributes["\\init"] = clkpol ? State::S1 : State::S0; module->addFf(NEW_ID, clk, past_clk); SigSpec clock_edge_pattern; if (clkpol) { clock_edge_pattern.append_bit(State::S0); clock_edge_pattern.append_bit(State::S1); } else { clock_edge_pattern.append_bit(State::S1); clock_edge_pattern.append_bit(State::S0); } SigSpec clock_edge = module->Eqx(NEW_ID, {clk, SigSpec(past_clk)}, clock_edge_pattern); SigSpec en_q = module->addWire(NEW_ID, GetSize(addr)); module->addFf(NEW_ID, en, en_q); SigSpec addr_q = module->addWire(NEW_ID, GetSize(addr)); module->addFf(NEW_ID, addr, addr_q); SigSpec data_q = module->addWire(NEW_ID, GetSize(data)); module->addFf(NEW_ID, data, data_q); wr_clk_port[wport] = State::S0; wr_en_port.replace(wport*width, module->Mux(NEW_ID, Const(0, GetSize(en_q)), en_q, clock_edge)); wr_addr_port.replace(wport*abits, addr_q); wr_data_port.replace(wport*width, data_q); wr_clk_en_param[wport] = State::S0; wr_clk_pol_param[wport] = State::S0; } cell->setParam("\\WR_CLK_ENABLE", wr_clk_en_param); cell->setParam("\\WR_CLK_POLARITY", wr_clk_pol_param); cell->setPort("\\WR_CLK", wr_clk_port); cell->setPort("\\WR_EN", wr_en_port); cell->setPort("\\WR_ADDR", wr_addr_port); cell->setPort("\\WR_DATA", wr_data_port); } if (cell->type.in("$dlatch")) { bool enpol = cell->parameters["\\EN_POLARITY"].as_bool(); SigSpec sig_en = cell->getPort("\\EN"); SigSpec sig_d = cell->getPort("\\D"); SigSpec sig_q = cell->getPort("\\Q"); log("Replacing %s.%s (%s): EN=%s, D=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(sig_en), log_signal(sig_d), log_signal(sig_q)); Wire *past_q = module->addWire(NEW_ID, GetSize(sig_q)); module->addFf(NEW_ID, sig_q, past_q); if (enpol) module->addMux(NEW_ID, past_q, sig_d, sig_en, sig_q); else module->addMux(NEW_ID, sig_d, past_q, sig_en, sig_q); Const initval; bool assign_initval = false; for (int i = 0; i < GetSize(sig_d); i++) { SigBit qbit = sigmap(sig_q[i]); if (initbits.count(qbit)) { initval.bits.push_back(initbits.at(qbit)); del_initbits.insert(qbit); } else initval.bits.push_back(State::Sx); if (initval.bits.back() != State::Sx) assign_initval = true; } if (assign_initval) past_q->attributes["\\init"] = initval; module->remove(cell); continue; } if (cell->type.in("$dff", "$adff", "$dffsr")) { bool clkpol = cell->parameters["\\CLK_POLARITY"].as_bool(); SigSpec clk = cell->getPort("\\CLK"); Wire *past_clk = module->addWire(NEW_ID); past_clk->attributes["\\init"] = clkpol ? State::S1 : State::S0; module->addFf(NEW_ID, clk, past_clk); SigSpec sig_d = cell->getPort("\\D"); SigSpec sig_q = cell->getPort("\\Q"); log("Replacing %s.%s (%s): CLK=%s, D=%s, Q=%s\n", log_id(module), log_id(cell), log_id(cell->type), log_signal(clk), log_signal(sig_d), log_signal(sig_q)); SigSpec clock_edge_pattern; if (clkpol) { clock_edge_pattern.append_bit(State::S0); clock_edge_pattern.append_bit(State::S1); } else { clock_edge_pattern.append_bit(State::S1); clock_edge_pattern.append_bit(State::S0); } SigSpec clock_edge = module->Eqx(NEW_ID, {clk, SigSpec(past_clk)}, clock_edge_pattern); Wire *past_d = module->addWire(NEW_ID, GetSize(sig_d)); Wire *past_q = module->addWire(NEW_ID, GetSize(sig_q)); module->addFf(NEW_ID, sig_d, past_d); module->addFf(NEW_ID, sig_q, past_q); if (cell->type == "$adff") { SigSpec arst = cell->getPort("\\ARST"); SigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge); Const rstval = cell->parameters["\\ARST_VALUE"]; if (cell->parameters["\\ARST_POLARITY"].as_bool()) module->addMux(NEW_ID, qval, rstval, arst, sig_q); else module->addMux(NEW_ID, rstval, qval, arst, sig_q); } else if (cell->type == "$dffsr") { SigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge); SigSpec setval = cell->getPort("\\SET"); SigSpec clrval = cell->getPort("\\CLR"); if (!cell->parameters["\\SET_POLARITY"].as_bool()) setval = module->Not(NEW_ID, setval); if (cell->parameters["\\CLR_POLARITY"].as_bool()) clrval = module->Not(NEW_ID, clrval); qval = module->Or(NEW_ID, qval, setval); module->addAnd(NEW_ID, qval, clrval, sig_q); } else { module->addMux(NEW_ID, past_q, past_d, clock_edge, sig_q); } Const initval; bool assign_initval = false; for (int i = 0; i < GetSize(sig_d); i++) { SigBit qbit = sigmap(sig_q[i]); if (initbits.count(qbit)) { initval.bits.push_back(initbits.at(qbit)); del_initbits.insert(qbit); } else initval.bits.push_back(State::Sx); if (initval.bits.back() != State::Sx) assign_initval = true; } if (assign_initval) { past_d->attributes["\\init"] = initval; past_q->attributes["\\init"] = initval; } module->remove(cell); continue; } } for (auto wire : module->wires()) if (wire->attributes.count("\\init") > 0) { bool delete_initattr = true; Const initval = wire->attributes.at("\\init"); SigSpec initsig = sigmap(wire); for (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++) if (del_initbits.count(initsig[i]) > 0) initval[i] = State::Sx; else if (initval[i] != State::Sx) delete_initattr = false; if (delete_initattr) wire->attributes.erase("\\init"); else wire->attributes.at("\\init") = initval; } } } } Clk2fflogicPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_util.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_stop_util.C /// @brief implements some utilty functions for STOP API. /// // *HWP HW Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Prem Shanker Jha <premjha2@in.ibm.com> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : HB:HYP #include "p9_stop_api.H" #include "p9_stop_util.H" #include "p9_stop_data_struct.H" #ifdef __cplusplus namespace stopImageSection { #endif /** * @brief Returns proc chip's fuse mode status. * @param i_pImage points to start of chip's HOMER image. * @param o_fusedMode points to fuse mode information. * @return STOP_SAVE_SUCCESS if functions succeeds, error code otherwise. */ static StopReturnCode_t isFusedMode( void* const i_pImage, bool* o_fusedMode ) { StopReturnCode_t l_rc = STOP_SAVE_SUCCESS; *o_fusedMode = false; do { HomerSection_t* pHomerDesc = ( HomerSection_t* ) i_pImage; HomerImgDesc_t* pHomer = (HomerImgDesc_t*)( pHomerDesc->interrruptHandler ); if( !i_pImage ) { MY_ERR( "invalid pointer to HOMER image"); l_rc = STOP_SAVE_ARG_INVALID_IMG; break; } uint64_t cpmrCheckWord = SWIZZLE_8_BYTE(pHomer->cpmrMagicWord); cpmrCheckWord = cpmrCheckWord >> 32; if( CPMR_REGION_CHECK_WORD != cpmrCheckWord ) { MY_ERR("corrupt or invalid HOMER image location 0x%016llx", SWIZZLE_8_BYTE(pHomer->cpmrMagicWord) ); l_rc = STOP_SAVE_ARG_INVALID_IMG; break; } if( (uint8_t) FUSED_CORE_MODE == pHomer->fusedModeStatus ) { *o_fusedMode = true; break; } if( (uint8_t) NONFUSED_CORE_MODE == pHomer->fusedModeStatus ) { break; } MY_ERR("Unexpected value 0x%08x for fused mode. Bad or corrupt " "HOMER location", pHomer->fuseModeStatus ); l_rc = STOP_SAVE_INVALID_FUSED_CORE_STATUS ; } while(0); return l_rc; } //---------------------------------------------------------------------- StopReturnCode_t getCoreAndThread( void* const i_pImage, const uint64_t i_pir, uint32_t* o_pCoreId, uint32_t* o_pThreadId ) { StopReturnCode_t l_rc = STOP_SAVE_SUCCESS; do { // for SPR restore using 'Virtual Thread' and 'Physical Core' number // In Fused Mode: // bit b28 and b31 of PIR give physical core and b29 and b30 gives // virtual thread id. // In Non Fused Mode // bit 28 and b29 of PIR give both logical and physical core number // whereas b30 and b31 gives logical and virtual thread id. bool fusedMode = false; uint8_t coreThreadInfo = (uint8_t)i_pir; *o_pCoreId = 0; *o_pThreadId = 0; l_rc = isFusedMode( i_pImage, &fusedMode ); if( l_rc ) { MY_ERR(" Checking Fused mode. Read failed 0x%08x", l_rc ); break; } if( fusedMode ) { if( coreThreadInfo & FUSED_CORE_BIT1 ) { *o_pThreadId = 2; } if( coreThreadInfo & FUSED_CORE_BIT2 ) { *o_pThreadId += 1; } if( coreThreadInfo & FUSED_CORE_BIT0 ) { *o_pCoreId = 2; } if( coreThreadInfo & FUSED_CORE_BIT3 ) { *o_pCoreId += 1; } } else { if( coreThreadInfo & FUSED_CORE_BIT0 ) { *o_pCoreId = 2; } if ( coreThreadInfo & FUSED_CORE_BIT1 ) { *o_pCoreId += 1; } if( coreThreadInfo & FUSED_CORE_BIT2 ) { *o_pThreadId = 2; } if( coreThreadInfo & FUSED_CORE_BIT3 ) { *o_pThreadId += 1; } } MY_INF("Core Type %s", fusedMode ? "Fused" : "Un-Fused" ); //quad field is not affected by fuse mode *o_pCoreId += 4 * (( coreThreadInfo & 0x70 ) >> 4 ); } while(0); return l_rc; } #ifdef __cplusplus }//namespace stopImageSection ends #endif <commit_msg>STOP API: API conditionally supports 255 SCOM restore entries for each quad.<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_util.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_stop_util.C /// @brief implements some utilty functions for STOP API. /// // *HWP HW Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Prem Shanker Jha <premjha2@in.ibm.com> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : HB:HYP #ifdef PPC_HYP #include <HvPlicModule.H> #endif #include "p9_stop_api.H" #include "p9_stop_util.H" #include "p9_stop_data_struct.H" #ifdef __cplusplus namespace stopImageSection { #endif //----------------------------------------------------------------------- /** * @brief Returns proc chip's fuse mode status. * @param i_pImage points to start of chip's HOMER image. * @param o_fusedMode points to fuse mode information. * @return STOP_SAVE_SUCCESS if functions succeeds, error code otherwise. */ STATIC StopReturnCode_t isFusedMode( void* const i_pImage, bool* o_fusedMode ) { StopReturnCode_t l_rc = STOP_SAVE_SUCCESS; uint64_t cpmrCheckWord = 0; *o_fusedMode = false; do { HomerSection_t* pHomerDesc = ( HomerSection_t* ) i_pImage; HomerImgDesc_t* pHomer = (HomerImgDesc_t*)( pHomerDesc->interrruptHandler ); if( !i_pImage ) { MY_ERR( "invalid pointer to HOMER image"); l_rc = STOP_SAVE_ARG_INVALID_IMG; break; } cpmrCheckWord = SWIZZLE_8_BYTE(pHomer->cpmrMagicWord); cpmrCheckWord = cpmrCheckWord >> 32; if( CPMR_REGION_CHECK_WORD != cpmrCheckWord ) { MY_ERR("corrupt or invalid HOMER image location 0x%016llx", SWIZZLE_8_BYTE(pHomer->cpmrMagicWord) ); l_rc = STOP_SAVE_ARG_INVALID_IMG; break; } if( (uint8_t) FUSED_CORE_MODE == pHomer->fusedModeStatus ) { *o_fusedMode = true; break; } if( (uint8_t) NONFUSED_CORE_MODE == pHomer->fusedModeStatus ) { break; } MY_ERR("Unexpected value 0x%08x for fused mode. Bad or corrupt " "HOMER location", pHomer->fusedModeStatus ); l_rc = STOP_SAVE_INVALID_FUSED_CORE_STATUS ; } while(0); return l_rc; } //---------------------------------------------------------------------- StopReturnCode_t getCoreAndThread( void* const i_pImage, const uint64_t i_pir, uint32_t* o_pCoreId, uint32_t* o_pThreadId ) { StopReturnCode_t l_rc = STOP_SAVE_SUCCESS; do { // for SPR restore using 'Virtual Thread' and 'Physical Core' number // In Fused Mode: // bit b28 and b31 of PIR give physical core and b29 and b30 gives // virtual thread id. // In Non Fused Mode // bit 28 and b29 of PIR give both logical and physical core number // whereas b30 and b31 gives logical and virtual thread id. bool fusedMode = false; uint8_t coreThreadInfo = (uint8_t)i_pir; *o_pCoreId = 0; *o_pThreadId = 0; l_rc = isFusedMode( i_pImage, &fusedMode ); if( l_rc ) { MY_ERR(" Checking Fused mode. Read failed 0x%08x", l_rc ); break; } if( fusedMode ) { if( coreThreadInfo & FUSED_CORE_BIT1 ) { *o_pThreadId = 2; } if( coreThreadInfo & FUSED_CORE_BIT2 ) { *o_pThreadId += 1; } if( coreThreadInfo & FUSED_CORE_BIT0 ) { *o_pCoreId = 2; } if( coreThreadInfo & FUSED_CORE_BIT3 ) { *o_pCoreId += 1; } } else { if( coreThreadInfo & FUSED_CORE_BIT0 ) { *o_pCoreId = 2; } if ( coreThreadInfo & FUSED_CORE_BIT1 ) { *o_pCoreId += 1; } if( coreThreadInfo & FUSED_CORE_BIT2 ) { *o_pThreadId = 2; } if( coreThreadInfo & FUSED_CORE_BIT3 ) { *o_pThreadId += 1; } } MY_INF("Core Type %s", fusedMode ? "Fused" : "Un-Fused" ); //quad field is not affected by fuse mode *o_pCoreId += 4 * (( coreThreadInfo & 0x70 ) >> 4 ); } while(0); return l_rc; } #ifdef __cplusplus }//namespace stopImageSection ends #endif <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: removeModel.C,v 1.2 2003/08/26 18:35:37 amoll Exp $ #include <BALL/VIEW/MODELS/removeModel.h> #include <BALL/KERNEL/forEach.h> #include <BALL/KERNEL/bond.h> using namespace std; namespace BALL { namespace VIEW { RemoveModel::RemoveModel() throw() : AtomBondModelBaseProcessor(), UnaryProcessor<Composite*>() { } RemoveModel::RemoveModel(const RemoveModel &model, bool deep) throw() : AtomBondModelBaseProcessor(model, deep), UnaryProcessor<Composite*>(model) { } RemoveModel::~RemoveModel() throw() { #ifdef BALL_VIEW_DEBUG cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<RemoveModel>() << endl; #endif destroy(); } void RemoveModel::clear() throw() { AtomBondModelBaseProcessor::clear(); } void RemoveModel::destroy() throw() { } bool RemoveModel::start() { getSearcher_().clear(); return AtomBondModelBaseProcessor::start(); } bool RemoveModel::finish() { // generate StickPrimitives Atom* first_atom = 0; Atom* second_atom = 0; Bond* pBond = 0; AtomBondIterator bond_Iterator; List<Atom*>::Iterator list_iterator; // for all used atoms for (list_iterator = getAtomList_().begin(); list_iterator != getAtomList_().end(); ++list_iterator) { first_atom = *list_iterator; // for all bonds connected from first- to second atom BALL_FOREACH_ATOM_BOND(*first_atom, bond_Iterator) { pBond = &(*bond_Iterator); second_atom = const_cast<Atom*>(pBond->getSecondAtom()); // use only atoms with greater handles than first atom if (*first_atom < *second_atom) { // remove models removeGeometricObjects_(*pBond); } } // remove atom models removeGeometricObjects_(*first_atom); } return true; } Processor::Result RemoveModel::operator() (Composite& composite) { // composite is an atom ? if (!RTTI::isKindOf<Atom>(composite)) { return Processor::CONTINUE; } Atom *atom = RTTI::castTo<Atom>(composite); // check if there are already models appended atom->applyChild(getSearcher_()); // geometric object is not existent => do nothing if (getSearcher_().geometricObjectsFound() == false) { return Processor::CONTINUE; } // collect atom with geometric object for deletion insertAtom_(atom); return Processor::CONTINUE; } void RemoveModel::dump(ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); AtomBondModelBaseProcessor::dump(s, depth + 1); BALL_DUMP_STREAM_SUFFIX(s); } } // namespace VIEW } // namespace BALL <commit_msg>*** empty log message ***<commit_after><|endoftext|>
<commit_before>#pragma once #include "lw/event/Promise.hpp" #include "lw/event/Promise.void.hpp" namespace lw { namespace event { template< typename T > inline Future< T > Promise< T >::future( void ){ return Future< T >( m_state ); } // -------------------------------------------------------------------------- // inline Future< void > Promise< void >::future( void ){ return Future< void >( m_state ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Result, typename Resolve, typename Reject, typename > Future< Result > Future< T >::_then( Resolve&& resolve, Reject&& reject ){ auto next = std::make_shared< Promise< Result > >(); auto prev = m_state; m_state->resolve = [ resolve, prev, next ]( T&& value ) mutable { resolve( std::move( value ), std::move( *next ) ); prev->reject = nullptr; prev.reset(); }; typedef std::function< void( const error::Exception& ) > RejectHandler; RejectHandler rejectHandler; if( std::is_same< nullptr_t, Reject >::value ){ rejectHandler = [ next ]( const error::Exception& err ){ next->reject( err ); }; } else { rejectHandler = std::forward< Reject >( reject ); } m_state->reject = [ rejectHandler, prev, next ]( const error::Exception& err ) mutable { rejectHandler( err ); prev->resolve = nullptr; prev.reset(); }; return next->future(); } // -------------------------------------------------------------------------- // template< typename T > template< typename Resolve, typename Reject, typename > inline Future<> Future< T >::_then( Resolve&& resolve, Reject&& reject ){ return then< void >( std::forward< Resolve >( resolve ), std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< IsFuture< ResolveResult >::value >::type* > Future< typename ResolveResult::result_type > Future< T >::_then( Resolve&& resolve, Reject&& reject ){ typedef typename ResolveResult::result_type Result; return then< Result >( [ resolve ]( T&& value, Promise< Result >&& promise ) mutable { resolve( std::move( value ) ).then( std::move( promise ) ); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< !IsFuture< ResolveResult >::value && !std::is_void< ResolveResult >::value >::type* > Future< ResolveResult > Future< T >::_then( Resolve&& resolve, Reject&& reject ){ return then< ResolveResult >( [ resolve ]( T&& value, Promise< ResolveResult >&& promise ) mutable { promise.resolve( resolve( std::move( value ) ) ); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< std::is_void< ResolveResult >::value >::type* > Future<> Future< T >::_then( Resolve&& resolve, Reject&& reject ){ return then( [ resolve ]( T&& value, Promise<>&& promise ){ resolve( std::move( value ) ); promise.resolve(); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename T > void Future< T >::then( promise_type&& promise ){ auto next = std::make_shared< promise_type >( std::move( promise ) ); auto prev = m_state; m_state->resolve = [ prev, next ]( T&& value ) mutable { next->resolve( std::move( value ) ); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]( const error::Exception& err ) mutable { next->reject( err ); prev->resolve = nullptr; prev.reset(); }; } // -------------------------------------------------------------------------- // template< typename Result, typename Resolve, typename Reject, typename > Future< Result > Future< void >::_then( Resolve&& resolve, Reject&& reject ){ auto next = std::make_shared< Promise< Result > >(); auto prev = m_state; m_state->resolve = [ resolve, prev, next ]() mutable { resolve( std::move( *next ) ); prev->reject = nullptr; prev.reset(); }; typedef std::function< void( const error::Exception& ) > RejectHandler; RejectHandler rejectHandler; if( std::is_same< nullptr_t, Reject >::value ){ rejectHandler = [ next ]( const error::Exception& err ){ next->reject( err ); }; } else { rejectHandler = std::forward< Reject >( reject ); } m_state->reject = [ rejectHandler, prev, next ]( const error::Exception& err ) mutable { rejectHandler( err ); prev->resolve = nullptr; prev.reset(); }; return next->future(); } // -------------------------------------------------------------------------- // template< typename Resolve, typename Reject, typename > Future<> Future< void >::_then( Resolve&& resolve, Reject&& reject ){ return then< void >( std::forward< Resolve >( resolve ), std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< IsFuture< ResolveResult >::value >::type* > Future< typename ResolveResult::result_type > Future< void >::_then( Resolve&& resolve, Reject&& reject ){ typedef typename ResolveResult::result_type Result; return then< Result >( [ resolve ]( Promise< Result >&& promise ){ resolve().then( std::move( promise ) ); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< !IsFuture< ResolveResult >::value && !std::is_void< ResolveResult >::value >::type* > Future< ResolveResult > Future< void >::_then( Resolve&& resolve, Reject&& reject ){ return then< ResolveResult >( [ resolve ]( Promise< ResolveResult >&& promise ){ promise.resolve( resolve() ); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< std::is_void< ResolveResult >::value >::type* > Future< void > Future< void >::_then( Resolve&& resolve, Reject&& reject ){ return then< void >( [ resolve ]( Promise< void >&& promise ){ resolve(); promise.resolve(); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // inline void Future< void >::then( promise_type&& promise ){ auto next = std::make_shared< promise_type >( std::move( promise ) ); auto prev = m_state; m_state->resolve = [ prev, next ]() mutable { next->resolve(); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]( const error::Exception& err ) mutable { next->reject( err ); prev->resolve = nullptr; prev.reset(); }; } } } <commit_msg>Added auto rejection for sychronous methods.<commit_after>#pragma once #include "lw/event/Promise.hpp" #include "lw/event/Promise.void.hpp" namespace lw { namespace event { template< typename T > inline Future< T > Promise< T >::future( void ){ return Future< T >( m_state ); } // -------------------------------------------------------------------------- // inline Future< void > Promise< void >::future( void ){ return Future< void >( m_state ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Result, typename Resolve, typename Reject, typename > Future< Result > Future< T >::_then( Resolve&& resolve, Reject&& reject ){ auto next = std::make_shared< Promise< Result > >(); auto prev = m_state; m_state->resolve = [ resolve, prev, next ]( T&& value ) mutable { resolve( std::move( value ), std::move( *next ) ); prev->reject = nullptr; prev.reset(); }; typedef std::function< void( const error::Exception& ) > RejectHandler; RejectHandler rejectHandler; if( std::is_same< nullptr_t, Reject >::value ){ rejectHandler = [ next ]( const error::Exception& err ){ next->reject( err ); }; } else { rejectHandler = std::forward< Reject >( reject ); } m_state->reject = [ rejectHandler, prev, next ]( const error::Exception& err ) mutable { rejectHandler( err ); prev->resolve = nullptr; prev.reset(); }; return next->future(); } // -------------------------------------------------------------------------- // template< typename T > template< typename Resolve, typename Reject, typename > inline Future<> Future< T >::_then( Resolve&& resolve, Reject&& reject ){ return then< void >( std::forward< Resolve >( resolve ), std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< IsFuture< ResolveResult >::value >::type* > Future< typename ResolveResult::result_type > Future< T >::_then( Resolve&& resolve, Reject&& reject ){ typedef typename ResolveResult::result_type Result; return then< Result >( [ resolve ]( T&& value, Promise< Result >&& promise ) mutable { resolve( std::move( value ) ).then( std::move( promise ) ); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< !IsFuture< ResolveResult >::value && !std::is_void< ResolveResult >::value >::type* > Future< ResolveResult > Future< T >::_then( Resolve&& resolve, Reject&& reject ){ return then< ResolveResult >( [ resolve ]( T&& value, Promise< ResolveResult >&& promise ) mutable { try { promise.resolve( resolve( std::move( value ) ) ); } catch( const error::Exception& err ){ promise.reject( err ); } }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename T > template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< std::is_void< ResolveResult >::value >::type* > Future<> Future< T >::_then( Resolve&& resolve, Reject&& reject ){ return then( [ resolve ]( T&& value, Promise<>&& promise ){ try { resolve( std::move( value ) ); } catch( const error::Exception& err ){ promise.reject( err ); return; } promise.resolve(); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename T > void Future< T >::then( promise_type&& promise ){ auto next = std::make_shared< promise_type >( std::move( promise ) ); auto prev = m_state; m_state->resolve = [ prev, next ]( T&& value ) mutable { next->resolve( std::move( value ) ); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]( const error::Exception& err ) mutable { next->reject( err ); prev->resolve = nullptr; prev.reset(); }; } // -------------------------------------------------------------------------- // template< typename Result, typename Resolve, typename Reject, typename > Future< Result > Future< void >::_then( Resolve&& resolve, Reject&& reject ){ auto next = std::make_shared< Promise< Result > >(); auto prev = m_state; m_state->resolve = [ resolve, prev, next ]() mutable { resolve( std::move( *next ) ); prev->reject = nullptr; prev.reset(); }; typedef std::function< void( const error::Exception& ) > RejectHandler; RejectHandler rejectHandler; if( std::is_same< nullptr_t, Reject >::value ){ rejectHandler = [ next ]( const error::Exception& err ){ next->reject( err ); }; } else { rejectHandler = std::forward< Reject >( reject ); } m_state->reject = [ rejectHandler, prev, next ]( const error::Exception& err ) mutable { rejectHandler( err ); prev->resolve = nullptr; prev.reset(); }; return next->future(); } // -------------------------------------------------------------------------- // template< typename Resolve, typename Reject, typename > Future<> Future< void >::_then( Resolve&& resolve, Reject&& reject ){ return then< void >( std::forward< Resolve >( resolve ), std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< IsFuture< ResolveResult >::value >::type* > Future< typename ResolveResult::result_type > Future< void >::_then( Resolve&& resolve, Reject&& reject ){ typedef typename ResolveResult::result_type Result; return then< Result >( [ resolve ]( Promise< Result >&& promise ){ resolve().then( std::move( promise ) ); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< !IsFuture< ResolveResult >::value && !std::is_void< ResolveResult >::value >::type* > Future< ResolveResult > Future< void >::_then( Resolve&& resolve, Reject&& reject ){ return then< ResolveResult >( [ resolve ]( Promise< ResolveResult >&& promise ){ try { promise.resolve( resolve() ); } catch( const error::Exception& err ){ promise.reject( err ); } }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // template< typename Resolve, typename Reject, typename ResolveResult, typename std::enable_if< std::is_void< ResolveResult >::value >::type* > Future< void > Future< void >::_then( Resolve&& resolve, Reject&& reject ){ return then< void >( [ resolve ]( Promise< void >&& promise ){ try { resolve(); } catch( const error::Exception& err ){ promise.reject( err ); return; } promise.resolve(); }, std::forward< Reject >( reject ) ); } // -------------------------------------------------------------------------- // inline void Future< void >::then( promise_type&& promise ){ auto next = std::make_shared< promise_type >( std::move( promise ) ); auto prev = m_state; m_state->resolve = [ prev, next ]() mutable { next->resolve(); prev->reject = nullptr; prev.reset(); }; m_state->reject = [ prev, next ]( const error::Exception& err ) mutable { next->reject( err ); prev->resolve = nullptr; prev.reset(); }; } } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/assign_op.h" #include <memory> #include <string> namespace paddle { namespace operators { class AssignOp : public framework::OperatorWithKernel { public: AssignOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorWithKernel(type, inputs, outputs, attrs) {} void InferShape(framework::InferShapeContext *ctx) const override { if (ctx->HasInput("X")) { auto type = ctx->GetInputsVarType("X")[0]; if (type == framework::proto::VarType::SELECTED_ROWS || type == framework::proto::VarType::LOD_TENSOR) { ctx->SetOutputDim("Out", ctx->GetInputDim("X")); if (type == framework::proto::VarType::LOD_TENSOR) { ctx->ShareLoD("X", /*->*/ "Out"); } } } } protected: framework::OpKernelType GetKernelTypeForVar( const std::string &var_name, const framework::Tensor &tensor, const framework::OpKernelType &expected_kernel_type) const override { return framework::OpKernelType(expected_kernel_type.data_type_, expected_kernel_type.place_, tensor.layout()); } framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext &ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.device_context()); } }; class AssignInferVarType : public framework::VarTypeInference { public: void operator()(framework::InferVarTypeContext *ctx) const override { ctx->SyncTypeAndDataType("X", "Out"); } }; class AssignKernel { public: void operator()(const framework::ExecutionContext &ctx) const { auto *x = ctx.InputVar("X"); if (x == nullptr) { return; } PADDLE_ENFORCE_EQ( ctx.HasOutput("Out"), true, platform::errors::NotFound("Output(Out) of assign_op is not found.")); auto *out = ctx.OutputVar("Out"); platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(ctx.GetPlace()); framework::VisitVarType(*x, AssignFunctor(out, dev_ctx)); } }; class AssignOpProtoMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(LoDTensor, SelectedRows or LoDTensorArray) The input variable " "could be LoDTensor, SelectedRows or LoDTensorArray.") .AsDispensable(); AddOutput("Out", "(LoDTensor, SelectedRows or LoDTensorArray) The type of output " "is the same as input X."); AddComment(R"DOC(Assign Operator Out = X, when type in [LoDTensor/SelectedRows/LoDTensorArray] raise error if the type is not listed above. )DOC"); } }; template <typename T> class AssignGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("assign"); op->SetInput("X", this->OutputGrad("Out")); op->SetOutput("Out", this->InputGrad("X")); } }; DECLARE_INPLACE_OP_INFERER(AssignOpInplaceInferer, {"X", "Out"}); } // namespace operators } // namespace paddle namespace ops = paddle::operators; namespace plat = paddle::platform; REGISTER_OPERATOR(assign, ops::AssignOp, ops::AssignGradMaker<paddle::framework::OpDesc>, ops::AssignGradMaker<paddle::imperative::OpBase>, ops::AssignOpProtoMaker, ops::AssignOpInplaceInferer, ops::AssignInferVarType); REGISTER_OP_CPU_KERNEL_FUNCTOR(assign, float, ops::AssignKernel, double, ops::AssignKernel, int, ops::AssignKernel, int64_t, ops::AssignKernel, bool, ops::AssignKernel, plat::float16, ops::AssignKernel); #ifdef PADDLE_WITH_CUDA REGISTER_OP_CUDA_KERNEL_FUNCTOR(assign, float, ops::AssignKernel, double, ops::AssignKernel, int, ops::AssignKernel, int64_t, ops::AssignKernel, bool, ops::AssignKernel, plat::float16, ops::AssignKernel); #endif <commit_msg>Fix bug in assign op: support to infer shape for LOD_TENSOR_ARRAY. (#24268)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/assign_op.h" #include <memory> #include <string> namespace paddle { namespace operators { class AssignOp : public framework::OperatorWithKernel { public: AssignOp(const std::string &type, const framework::VariableNameMap &inputs, const framework::VariableNameMap &outputs, const framework::AttributeMap &attrs) : OperatorWithKernel(type, inputs, outputs, attrs) {} void InferShape(framework::InferShapeContext *ctx) const override { if (ctx->HasInput("X")) { auto type = ctx->GetInputsVarType("X")[0]; if (type == framework::proto::VarType::SELECTED_ROWS || type == framework::proto::VarType::LOD_TENSOR) { ctx->SetOutputDim("Out", ctx->GetInputDim("X")); if (type == framework::proto::VarType::LOD_TENSOR) { ctx->ShareLoD("X", /*->*/ "Out"); } } else if (type == framework::proto::VarType::LOD_TENSOR_ARRAY) { if (ctx->IsRuntime()) { // The runtime output shape is determined in kernel. return; } else { ctx->SetOutputDim("Out", ctx->GetInputDim("X")); } } } } protected: framework::OpKernelType GetKernelTypeForVar( const std::string &var_name, const framework::Tensor &tensor, const framework::OpKernelType &expected_kernel_type) const override { return framework::OpKernelType(expected_kernel_type.data_type_, expected_kernel_type.place_, tensor.layout()); } framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext &ctx) const override { return framework::OpKernelType( OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.device_context()); } }; class AssignInferVarType : public framework::VarTypeInference { public: void operator()(framework::InferVarTypeContext *ctx) const override { ctx->SyncTypeAndDataType("X", "Out"); } }; class AssignKernel { public: void operator()(const framework::ExecutionContext &ctx) const { auto *x = ctx.InputVar("X"); if (x == nullptr) { return; } PADDLE_ENFORCE_EQ( ctx.HasOutput("Out"), true, platform::errors::NotFound("Output(Out) of assign_op is not found.")); auto *out = ctx.OutputVar("Out"); platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance(); auto &dev_ctx = *pool.Get(ctx.GetPlace()); framework::VisitVarType(*x, AssignFunctor(out, dev_ctx)); } }; class AssignOpProtoMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "(LoDTensor, SelectedRows or LoDTensorArray) The input variable " "could be LoDTensor, SelectedRows or LoDTensorArray.") .AsDispensable(); AddOutput("Out", "(LoDTensor, SelectedRows or LoDTensorArray) The type of output " "is the same as input X."); AddComment(R"DOC(Assign Operator Out = X, when type in [LoDTensor/SelectedRows/LoDTensorArray] raise error if the type is not listed above. )DOC"); } }; template <typename T> class AssignGradMaker : public framework::SingleGradOpMaker<T> { public: using framework::SingleGradOpMaker<T>::SingleGradOpMaker; protected: void Apply(GradOpPtr<T> op) const override { op->SetType("assign"); op->SetInput("X", this->OutputGrad("Out")); op->SetOutput("Out", this->InputGrad("X")); } }; DECLARE_INPLACE_OP_INFERER(AssignOpInplaceInferer, {"X", "Out"}); } // namespace operators } // namespace paddle namespace ops = paddle::operators; namespace plat = paddle::platform; REGISTER_OPERATOR(assign, ops::AssignOp, ops::AssignGradMaker<paddle::framework::OpDesc>, ops::AssignGradMaker<paddle::imperative::OpBase>, ops::AssignOpProtoMaker, ops::AssignOpInplaceInferer, ops::AssignInferVarType); REGISTER_OP_CPU_KERNEL_FUNCTOR(assign, float, ops::AssignKernel, double, ops::AssignKernel, int, ops::AssignKernel, int64_t, ops::AssignKernel, bool, ops::AssignKernel, plat::float16, ops::AssignKernel); #ifdef PADDLE_WITH_CUDA REGISTER_OP_CUDA_KERNEL_FUNCTOR(assign, float, ops::AssignKernel, double, ops::AssignKernel, int, ops::AssignKernel, int64_t, ops::AssignKernel, bool, ops::AssignKernel, plat::float16, ops::AssignKernel); #endif <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/concat_op.h" #include <memory> #include <string> #include <vector> #ifdef PADDLE_WITH_MKLDNN #include <paddle/fluid/platform/mkldnn_helper.h> #endif namespace paddle { namespace operators { using framework::Tensor; class ConcatOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE_GE(ctx->Inputs("X").size(), 1UL, "Inputs(X) of ConcatOp should be empty."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of ConcatOp should not be null."); auto ins = ctx->GetInputsDim("X"); size_t axis = static_cast<size_t>(ctx->Attrs().Get<int>("axis")); const size_t n = ins.size(); PADDLE_ENFORCE_GT(n, 0, "Input tensors count should > 0."); if (n == 1) { VLOG(3) << "Warning: concat op have only one input, may waste memory"; } auto out_dims = ins[0]; size_t in_zero_dims_size = out_dims.size(); for (size_t i = 1; i < n; i++) { for (size_t j = 0; j < in_zero_dims_size; j++) { if (j == axis) { if (ctx->IsRuntime()) { out_dims[axis] += ins[i][j]; } else { if (ins[i][j] == -1) { out_dims[axis] = -1; } else { out_dims[axis] += ins[i][j]; } } } else { bool check_shape = ctx->IsRuntime() || (out_dims[j] > 0 && ins[i][j] > 0); if (check_shape) { // check all shape in run time PADDLE_ENFORCE_EQ(out_dims[j], ins[i][j], "Input tensors should have the same " "elements except the specify axis."); } } } } if (out_dims[axis] < 0) { out_dims[axis] = -1; } ctx->SetOutputDim("Out", out_dims); ctx->ShareLoD("X", /*->*/ "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext &ctx) const override { auto vars = ctx.MultiInputVar("X"); auto input_data_type = framework::proto::VarType::Type(0); bool flag = 0; for (auto *var : vars) { if (var->IsInitialized()) { input_data_type = framework::GetDataTypeOfVar(var); flag = 1; break; } } if (flag == 0) { PADDLE_THROW("All Inputs of Concat OP are Empty!"); } #ifdef PADDLE_WITH_MKLDNN if (platform::CanMKLDNNBeUsed(ctx)) { return framework::OpKernelType(input_data_type, ctx.GetPlace(), framework::DataLayout::kMKLDNN, framework::LibraryType::kMKLDNN); } #endif return framework::OpKernelType(input_data_type, ctx.GetPlace()); } }; class ConcatOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "Input tensors of concat operator.").AsDuplicable(); AddOutput("Out", "Output tensor of concat operator."); AddAttr<bool>( "use_mkldnn", "(bool, default false) Indicates if MKL-DNN kernel will be used") .SetDefault(false); AddAttr<int>("axis", "The axis along which the input tensors will be concatenated.") .SetDefault(0); AddAttr<bool>("use_quantizer", "(bool, default false) " "Set to true for operators that should be quantized and use " "int8 kernel. " "Only used on CPU.") .SetDefault(false); AddComment(R"DOC( Concat Operator. Concatenate the input tensors along dimension axis. Examples: Input[0] = [[1,2],[3,4]] Input[1] = [[5,6]] axis = 0 Output = [[1,2], [3,4], [5,6]] )DOC"); } }; class ConcatOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { auto in_x = "X"; auto out_x_g_n = framework::GradVarName(in_x); ctx->SetOutputsDim(out_x_g_n, ctx->GetInputsDim(in_x)); auto &in_names = ctx->Inputs(in_x); auto &out_names = ctx->Outputs(out_x_g_n); PADDLE_ENFORCE_EQ( in_names.size(), out_names.size(), "The number of arguments in %s[%d] and %s[%d] is not equal.", in_x, in_names.size(), out_x_g_n, out_names.size()); for (size_t i = 0; i < in_names.size(); ++i) { if (out_names[i] != framework::kEmptyVarName) { ctx->ShareLoD(in_x, out_x_g_n, i, i); } } } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext &ctx) const override { return framework::OpKernelType( ctx.Input<Tensor>(framework::GradVarName("Out"))->type(), ctx.GetPlace()); } }; DECLARE_NO_NEED_BUFFER_VARS_INFERENCE(ConcatOpGradNoNeedBufferVarInference, "X"); class ConcatGradOpDescMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDesc> Apply() const override { std::unique_ptr<framework::OpDesc> op(new framework::OpDesc()); op->SetType("concat_grad"); op->SetInput("X", Input("X")); op->SetInput(framework::GradVarName("Out"), OutputGrad("Out")); op->SetOutput(framework::GradVarName("X"), InputGrad("X", false)); op->SetAttrMap(Attrs()); return op; } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(concat, ops::ConcatOp, ops::ConcatOpMaker, ops::ConcatGradOpDescMaker); REGISTER_OPERATOR(concat_grad, ops::ConcatOpGrad, ops::ConcatOpGradNoNeedBufferVarInference); REGISTER_OP_CPU_KERNEL( concat, ops::ConcatKernel<paddle::platform::CPUDeviceContext, double>, ops::ConcatKernel<paddle::platform::CPUDeviceContext, float>, ops::ConcatKernel<paddle::platform::CPUDeviceContext, int64_t>, ops::ConcatKernel<paddle::platform::CPUDeviceContext, int>); REGISTER_OP_CPU_KERNEL( concat_grad, ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, double>, ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, float>, ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, int64_t>, ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, int>); <commit_msg>refine GetExpectedKernelType in conat op, test=develop (#17934)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/concat_op.h" #include <memory> #include <string> #include <vector> #ifdef PADDLE_WITH_MKLDNN #include <paddle/fluid/platform/mkldnn_helper.h> #endif namespace paddle { namespace operators { using Tensor = framework::Tensor; class ConcatOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE_GE(ctx->Inputs("X").size(), 1UL, "Inputs(X) of ConcatOp should be empty."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of ConcatOp should not be null."); auto ins = ctx->GetInputsDim("X"); size_t axis = static_cast<size_t>(ctx->Attrs().Get<int>("axis")); const size_t n = ins.size(); PADDLE_ENFORCE_GT(n, 0, "Input tensors count should > 0."); if (n == 1) { VLOG(3) << "Warning: concat op have only one input, may waste memory"; } auto out_dims = ins[0]; size_t in_zero_dims_size = out_dims.size(); for (size_t i = 1; i < n; i++) { for (size_t j = 0; j < in_zero_dims_size; j++) { if (j == axis) { if (ctx->IsRuntime()) { out_dims[axis] += ins[i][j]; } else { if (ins[i][j] == -1) { out_dims[axis] = -1; } else { out_dims[axis] += ins[i][j]; } } } else { bool check_shape = ctx->IsRuntime() || (out_dims[j] > 0 && ins[i][j] > 0); if (check_shape) { // check all shape in run time PADDLE_ENFORCE_EQ(out_dims[j], ins[i][j], "Input tensors should have the same " "elements except the specify axis."); } } } } if (out_dims[axis] < 0) { out_dims[axis] = -1; } ctx->SetOutputDim("Out", out_dims); ctx->ShareLoD("X", /*->*/ "Out"); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext &ctx) const override { auto inputs = ctx.MultiInput<Tensor>("X"); auto input_data_type = framework::proto::VarType::Type(0); bool flag = 0; for (auto *input : inputs) { if (input->IsInitialized() && input->numel() > 0) { input_data_type = input->type(); flag = 1; break; } } if (flag == 0) { PADDLE_THROW("All Inputs of Concat OP are Empty!"); } #ifdef PADDLE_WITH_MKLDNN if (platform::CanMKLDNNBeUsed(ctx)) { return framework::OpKernelType(input_data_type, ctx.GetPlace(), framework::DataLayout::kMKLDNN, framework::LibraryType::kMKLDNN); } #endif return framework::OpKernelType(input_data_type, ctx.GetPlace()); } }; class ConcatOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("X", "Input tensors of concat operator.").AsDuplicable(); AddOutput("Out", "Output tensor of concat operator."); AddAttr<bool>( "use_mkldnn", "(bool, default false) Indicates if MKL-DNN kernel will be used") .SetDefault(false); AddAttr<int>("axis", "The axis along which the input tensors will be concatenated.") .SetDefault(0); AddAttr<bool>("use_quantizer", "(bool, default false) " "Set to true for operators that should be quantized and use " "int8 kernel. " "Only used on CPU.") .SetDefault(false); AddComment(R"DOC( Concat Operator. Concatenate the input tensors along dimension axis. Examples: Input[0] = [[1,2],[3,4]] Input[1] = [[5,6]] axis = 0 Output = [[1,2], [3,4], [5,6]] )DOC"); } }; class ConcatOpGrad : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { auto in_x = "X"; auto out_x_g_n = framework::GradVarName(in_x); ctx->SetOutputsDim(out_x_g_n, ctx->GetInputsDim(in_x)); auto &in_names = ctx->Inputs(in_x); auto &out_names = ctx->Outputs(out_x_g_n); PADDLE_ENFORCE_EQ( in_names.size(), out_names.size(), "The number of arguments in %s[%d] and %s[%d] is not equal.", in_x, in_names.size(), out_x_g_n, out_names.size()); for (size_t i = 0; i < in_names.size(); ++i) { if (out_names[i] != framework::kEmptyVarName) { ctx->ShareLoD(in_x, out_x_g_n, i, i); } } } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext &ctx) const override { return framework::OpKernelType( ctx.Input<Tensor>(framework::GradVarName("Out"))->type(), ctx.GetPlace()); } }; DECLARE_NO_NEED_BUFFER_VARS_INFERENCE(ConcatOpGradNoNeedBufferVarInference, "X"); class ConcatGradOpDescMaker : public framework::SingleGradOpDescMaker { public: using framework::SingleGradOpDescMaker::SingleGradOpDescMaker; protected: std::unique_ptr<framework::OpDesc> Apply() const override { std::unique_ptr<framework::OpDesc> op(new framework::OpDesc()); op->SetType("concat_grad"); op->SetInput("X", Input("X")); op->SetInput(framework::GradVarName("Out"), OutputGrad("Out")); op->SetOutput(framework::GradVarName("X"), InputGrad("X", false)); op->SetAttrMap(Attrs()); return op; } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(concat, ops::ConcatOp, ops::ConcatOpMaker, ops::ConcatGradOpDescMaker); REGISTER_OPERATOR(concat_grad, ops::ConcatOpGrad, ops::ConcatOpGradNoNeedBufferVarInference); REGISTER_OP_CPU_KERNEL( concat, ops::ConcatKernel<paddle::platform::CPUDeviceContext, double>, ops::ConcatKernel<paddle::platform::CPUDeviceContext, float>, ops::ConcatKernel<paddle::platform::CPUDeviceContext, int64_t>, ops::ConcatKernel<paddle::platform::CPUDeviceContext, int>); REGISTER_OP_CPU_KERNEL( concat_grad, ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, double>, ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, float>, ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, int64_t>, ops::ConcatGradKernel<paddle::platform::CPUDeviceContext, int>); <|endoftext|>
<commit_before> /************************************************************************* * * REDWOOD CONFIDENTIAL * Author: Aaron Edsinger * __________________ * * [2012] - [+] Redwood Robotics Incorporated * All Rights Reserved. * * All information contained herein is, and remains * the property of Redwood Robotics Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Redwood Robotics Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Redwood Robotics Incorporated. */ #include <stdio.h> #include <signal.h> #include "m3rt/base/m3ec_def.h" #include "m3rt/base/m3rt_def.h" #include "m3/vehicles/omnibase_shm_sds.h" // Rtai #ifdef __cplusplus extern "C" { #endif #include <rtai.h> #include <rtai_sem.h> #include <rtai_sched.h> #include <rtai_nam2num.h> #include <rtai_shm.h> #include <rtai_malloc.h> #ifdef __cplusplus } #endif // Needed for ROS #include <ros/ros.h> #include <nav_msgs/Odometry.h> #include <tf/transform_broadcaster.h> #define RT_TASK_FREQUENCY_MEKA_OMNI_SHM 100 #define RT_TIMER_TICKS_NS_MEKA_OMNI_SHM (1000000000 / RT_TASK_FREQUENCY_MEKA_OMNI_SHM) //Period of rt-timer #define MEKA_ODOM_SHM "OSHMM" #define MEKA_ODOM_CMD_SEM "OSHMC" #define MEKA_ODOM_STATUS_SEM "OSHMS" #define OMNIBASE_NDOF 7 #define CYCLE_TIME_SEC 4 #define VEL_TIMEOUT_SEC 1.0 //////////////////////////////////////////////////////////////////////////////////// static int sys_thread_active = 0; static int sys_thread_end=0; static int end=0; static int hst; static M3OmnibaseShmSdsCommand cmd; static M3OmnibaseShmSdsStatus status; static int sds_status_size; static int sds_cmd_size; static long step_cnt = 0; static void endme(int dummy) { std::cout << "END\n"; end=1; } static int64_t last_cmd_ts; nav_msgs::Odometry odom_g; ros::Publisher odom_publisher_g; ros::Subscriber cmd_sub_g; //tf::TransformBroadcaster odom_broadcaster; //////////////////////////////////////////////////////////////////////////////////// /////// Periodic Control Loop: void StepShm(); void commandCallback(const geometry_msgs::TwistConstPtr& msg); /////////////////////////////// void SetTimestamp(int64_t timestamp) { cmd.timestamp = timestamp; return; } int64_t GetTimestamp() { return status.timestamp; } ////////////////////////// MAIN COMPUTATION METHOD ///////////////////////////// void StepShm(int cntr) { SetTimestamp(GetTimestamp()); //Pass back timestamp as a heartbeat if (!status.calibrated) { printf("Omnibase is not calibrated. Please calibrate and run again. Exiting.\n"); endme(1); } odom_g.header.stamp = ros::Time::now(); // get from status double x = status.x; double y = status.y; double th = status.yaw; double vx = status.x_dot; double vy = status.y_dot; double vth = status.yaw_dot; //ROS_INFO("[STATUS] x,y,th:[%f,%f,%f]",x,y,th); // get from status //since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th); //first, we'll publish the transform over tf geometry_msgs::TransformStamped odom_trans; odom_trans.header.stamp = ros::Time::now(); odom_trans.header.frame_id = "odom"; odom_trans.child_frame_id = "base_link"; odom_trans.transform.translation.x = x; odom_trans.transform.translation.y = y; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = odom_quat; //send the transform //odom_broadcaster.sendTransform(odom_trans); odom_g.header.frame_id = "odom"; //set the position odom_g.pose.pose.position.x = x; odom_g.pose.pose.position.y = y; odom_g.pose.pose.position.z = 0.0; odom_g.pose.pose.orientation = odom_quat; //set the velocity odom_g.child_frame_id = "base_link"; odom_g.twist.twist.linear.x = vx; odom_g.twist.twist.linear.y = vy; odom_g.twist.twist.angular.z = vth; odom_publisher_g.publish(odom_g); if (status.timestamp - last_cmd_ts > VEL_TIMEOUT_SEC * 1000000.0) { cmd.x_velocity = 0.; cmd.y_velocity = 0.; cmd.yaw_velocity = 0.; } /* if (cntr % 100 == 0) { if (1) { printf("********************************\n"); printf("timestamp: %ld\n", (status.timestamp - last_cmd_ts)/1000000); //printf("to: %ld\n", VEL_TIMEOUT_NS); { //printf("JOINT %d\n", i); printf("------------------------------\n"); printf("X: %f\n",status.x); printf("Y: %f\n", status.y); printf("YAW: %f\n", status.yaw); printf("Vx: %f\n", odom_g.twist.twist.linear.x); printf("Vy: %f\n", odom_g.twist.twist.linear.y); printf("Va: %f\n", odom_g.twist.twist.angular.z); printf("------------------------------\n"); printf("\n"); } } } if (cntr % 100 == 0) { if (1) { printf("********************************\n"); printf("timestamp: %ld\n", status.timestamp); { //printf("JOINT %d\n", i); printf("------------------------------\n"); printf("X: %f\n", odom_g.pose.pose.position.x); printf("Y: %f\n", odom_g.pose.pose.position.y); printf("YAW: %f\n", th); printf("Vx: %f\n", odom_g.twist.twist.linear.x); printf("Vy: %f\n", odom_g.twist.twist.linear.y); printf("Va: %f\n", odom_g.twist.twist.angular.z); printf("------------------------------\n"); printf("\n"); } } }*/ } void commandCallback(const geometry_msgs::TwistConstPtr& msg) { cmd.x_velocity = msg->linear.x; cmd.y_velocity = msg->linear.y; cmd.yaw_velocity = msg->angular.z; /* printf("x: %f\n", cmd.x_velocity); printf("y: %f\n", cmd.y_velocity); printf("a: %f\n", cmd.yaw_velocity);*/ last_cmd_ts = status.timestamp; } ////////////////////////// RTAI PROCESS BOILERPLATE ///////////////////////////// static void* rt_system_thread(void * arg) { SEM * status_sem; SEM * command_sem; RT_TASK *task; int cntr=0; M3Sds * sds = (M3Sds *)arg; printf("Starting real-time thread\n"); sds_status_size = sizeof(M3OmnibaseShmSdsStatus); sds_cmd_size = sizeof(M3OmnibaseShmSdsCommand); memset(&cmd, 0, sds_cmd_size); task = rt_task_init_schmod(nam2num("OSHMP"), 0, 0, 0, SCHED_FIFO, 0xF); rt_allow_nonroot_hrt(); if (task==NULL) { printf("Failed to create RT-TASK TSHMP\n"); return 0; } status_sem=(SEM*)rt_get_adr(nam2num(MEKA_ODOM_STATUS_SEM)); command_sem=(SEM*)rt_get_adr(nam2num(MEKA_ODOM_CMD_SEM)); if (!status_sem) { printf("Unable to find the %s semaphore.\n",MEKA_ODOM_STATUS_SEM); rt_task_delete(task); return 0; } if (!command_sem) { printf("Unable to find the %s semaphore.\n",MEKA_ODOM_CMD_SEM); rt_task_delete(task); return 0; } RTIME tick_period = nano2count(RT_TIMER_TICKS_NS_MEKA_OMNI_SHM); RTIME now = rt_get_time(); rt_task_make_periodic(task, now + tick_period, tick_period); mlockall(MCL_CURRENT | MCL_FUTURE); rt_make_hard_real_time(); long long start_time, end_time, dt; long long step_cnt = 0; sys_thread_active=1; while(!sys_thread_end) { start_time = nano2count(rt_get_cpu_time_ns()); rt_sem_wait(status_sem); memcpy(&status, sds->status, sds_status_size); rt_sem_signal(status_sem); StepShm(cntr); rt_sem_wait(command_sem); memcpy(sds->cmd, &cmd, sds_cmd_size); rt_sem_signal(command_sem); end_time = nano2count(rt_get_cpu_time_ns()); dt=end_time-start_time; if(step_cnt % 50 == 0) { printf("sta[%f,%f,%f ]\n",(float)status.timestamp,status.x,status.y,status.yaw); printf("cmd[%f,%f,%f,%f]\n",(float)cmd.timestamp,cmd.x_velocity,cmd.y_velocity,cmd.yaw_velocity); } /* Check the time it takes to run components, and if it takes longer than our period, make us run slower. Otherwise this task locks up the CPU.*/ if (dt > tick_period && step_cnt>10) { printf("Step %lld: Computation time of components is too long. Forcing all components to state SafeOp.\n",step_cnt); printf("Previous period: %f. New period: %f\n", (double)count2nano(tick_period),(double)count2nano(dt)); tick_period=dt; //rt_task_make_periodic(task, end + tick_period,tick_period); } step_cnt++; if (cntr++ == CYCLE_TIME_SEC * 2 * RT_TIMER_TICKS_NS_MEKA_OMNI_SHM) cntr = 0; rt_task_wait_period(); } printf("Exiting RealTime Thread...\n",0); rt_make_soft_real_time(); rt_task_delete(task); sys_thread_active=0; return 0; } //////////////////////////////////////////////////////////////////////////////////// int main (int argc, char **argv) { //RT_TASK *task; M3Sds * sys; int cntr=0; rt_allow_nonroot_hrt(); /*ros::init(argc, argv, "base_controller"); // initialize ROS node ros::AsyncSpinner spinner(1); // Use 1 thread - check if you actually need this for only publishing spinner.start(); ros::NodeHandle root_handle;*/ ros::init(argc, argv, "base_controller", ros::init_options::NoSigintHandler); // initialize ROS node ros::AsyncSpinner spinner(1); // Use 1 thread - check if you actually need this for only publishing spinner.start(); ros::NodeHandle root_handle; ros::NodeHandle p_nh("~"); cmd_sub_g = root_handle.subscribe<geometry_msgs::Twist>("omnibase_command", 1, &commandCallback); odom_publisher_g = root_handle.advertise<nav_msgs::Odometry>("omnibase_odom", 1, true); signal(SIGINT, endme); if (sys = (M3Sds*)rt_shm_alloc(nam2num(MEKA_ODOM_SHM),sizeof(M3Sds),USE_VMALLOC)) printf("Found shared memory starting shm_omnibase_controller."); else { printf("Rtai_malloc failure for %s\n",MEKA_ODOM_SHM); return 0; } rt_allow_nonroot_hrt(); /*if (!(task = rt_task_init_schmod(nam2num("TSHM"), RT_TASK_PRIORITY, 0, 0, SCHED_FIFO, 0xF))) { rt_shm_free(nam2num(TORQUE_SHM)); printf("Cannot init the RTAI task %s\n","TSHM"); return 0; }*/ hst=rt_thread_create((void*)rt_system_thread, sys, 10000); usleep(100000); //Let start up if (!sys_thread_active) { //rt_task_delete(task); rt_shm_free(nam2num(MEKA_ODOM_SHM)); printf("Startup of thread failed.\n",0); return 0; } while(!end) { usleep(250000); } printf("Removing RT thread...\n",0); sys_thread_end=1; //rt_thread_join(hst); usleep(1250000); if (sys_thread_active)printf("Real-time thread did not shutdown correctly\n"); //rt_task_delete(task); rt_shm_free(nam2num(MEKA_ODOM_SHM)); ros::shutdown(); return 0; } <commit_msg>implemented publishing of tf from omnibase<commit_after> /************************************************************************* * * REDWOOD CONFIDENTIAL * Author: Aaron Edsinger * __________________ * * [2012] - [+] Redwood Robotics Incorporated * All Rights Reserved. * * All information contained herein is, and remains * the property of Redwood Robotics Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Redwood Robotics Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Redwood Robotics Incorporated. */ #include <stdio.h> #include <signal.h> #include "m3rt/base/m3ec_def.h" #include "m3rt/base/m3rt_def.h" #include "m3/vehicles/omnibase_shm_sds.h" // Rtai #ifdef __cplusplus extern "C" { #endif #include <rtai.h> #include <rtai_sem.h> #include <rtai_sched.h> #include <rtai_nam2num.h> #include <rtai_shm.h> #include <rtai_malloc.h> #ifdef __cplusplus } #endif // Needed for ROS #include <ros/ros.h> #include <nav_msgs/Odometry.h> #include <tf/transform_broadcaster.h> #define RT_TASK_FREQUENCY_MEKA_OMNI_SHM 100 #define RT_TIMER_TICKS_NS_MEKA_OMNI_SHM (1000000000 / RT_TASK_FREQUENCY_MEKA_OMNI_SHM) //Period of rt-timer #define MEKA_ODOM_SHM "OSHMM" #define MEKA_ODOM_CMD_SEM "OSHMC" #define MEKA_ODOM_STATUS_SEM "OSHMS" #define OMNIBASE_NDOF 7 #define CYCLE_TIME_SEC 4 #define VEL_TIMEOUT_SEC 1.0 //////////////////////////////////////////////////////////////////////////////////// static int sys_thread_active = 0; static int sys_thread_end=0; static int end=0; static int hst; static M3OmnibaseShmSdsCommand cmd; static M3OmnibaseShmSdsStatus status; static int sds_status_size; static int sds_cmd_size; static long step_cnt = 0; static void endme(int dummy) { std::cout << "END\n"; end=1; } static int64_t last_cmd_ts; nav_msgs::Odometry odom_g; ros::Publisher odom_publisher_g; ros::Subscriber cmd_sub_g; boost::shared_ptr<tf::TransformBroadcaster> odom_broadcaster_ptr; //////////////////////////////////////////////////////////////////////////////////// /////// Periodic Control Loop: void StepShm(); void commandCallback(const geometry_msgs::TwistConstPtr& msg); /////////////////////////////// void SetTimestamp(int64_t timestamp) { cmd.timestamp = timestamp; return; } int64_t GetTimestamp() { return status.timestamp; } ////////////////////////// MAIN COMPUTATION METHOD ///////////////////////////// void StepShm(int cntr) { SetTimestamp(GetTimestamp()); //Pass back timestamp as a heartbeat if (!status.calibrated) { printf("Omnibase is not calibrated. Please calibrate and run again. Exiting.\n"); endme(1); } odom_g.header.stamp = ros::Time::now(); // get from status double x = status.x; double y = status.y; double th = status.yaw; double vx = status.x_dot; double vy = status.y_dot; double vth = status.yaw_dot; //ROS_INFO("[STATUS] x,y,th:[%f,%f,%f]",x,y,th); // get from status //since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th); //first, we'll publish the transform over tf geometry_msgs::TransformStamped odom_trans; odom_trans.header.stamp = ros::Time::now(); odom_trans.header.frame_id = "odom"; odom_trans.child_frame_id = "base_link"; odom_trans.transform.translation.x = x; odom_trans.transform.translation.y = y; odom_trans.transform.translation.z = 0.0; odom_trans.transform.rotation = odom_quat; //send the transform odom_broadcaster_ptr->sendTransform(odom_trans); odom_g.header.frame_id = "odom"; //set the position odom_g.pose.pose.position.x = x; odom_g.pose.pose.position.y = y; odom_g.pose.pose.position.z = 0.0; odom_g.pose.pose.orientation = odom_quat; //set the velocity odom_g.child_frame_id = "base_link"; odom_g.twist.twist.linear.x = vx; odom_g.twist.twist.linear.y = vy; odom_g.twist.twist.angular.z = vth; odom_publisher_g.publish(odom_g); if (status.timestamp - last_cmd_ts > VEL_TIMEOUT_SEC * 1000000.0) { cmd.x_velocity = 0.; cmd.y_velocity = 0.; cmd.yaw_velocity = 0.; } /* if (cntr % 100 == 0) { if (1) { printf("********************************\n"); printf("timestamp: %ld\n", (status.timestamp - last_cmd_ts)/1000000); //printf("to: %ld\n", VEL_TIMEOUT_NS); { //printf("JOINT %d\n", i); printf("------------------------------\n"); printf("X: %f\n",status.x); printf("Y: %f\n", status.y); printf("YAW: %f\n", status.yaw); printf("Vx: %f\n", odom_g.twist.twist.linear.x); printf("Vy: %f\n", odom_g.twist.twist.linear.y); printf("Va: %f\n", odom_g.twist.twist.angular.z); printf("------------------------------\n"); printf("\n"); } } } if (cntr % 100 == 0) { if (1) { printf("********************************\n"); printf("timestamp: %ld\n", status.timestamp); { //printf("JOINT %d\n", i); printf("------------------------------\n"); printf("X: %f\n", odom_g.pose.pose.position.x); printf("Y: %f\n", odom_g.pose.pose.position.y); printf("YAW: %f\n", th); printf("Vx: %f\n", odom_g.twist.twist.linear.x); printf("Vy: %f\n", odom_g.twist.twist.linear.y); printf("Va: %f\n", odom_g.twist.twist.angular.z); printf("------------------------------\n"); printf("\n"); } } }*/ } void commandCallback(const geometry_msgs::TwistConstPtr& msg) { cmd.x_velocity = msg->linear.x; cmd.y_velocity = msg->linear.y; cmd.yaw_velocity = msg->angular.z; /* printf("x: %f\n", cmd.x_velocity); printf("y: %f\n", cmd.y_velocity); printf("a: %f\n", cmd.yaw_velocity);*/ last_cmd_ts = status.timestamp; } ////////////////////////// RTAI PROCESS BOILERPLATE ///////////////////////////// static void* rt_system_thread(void * arg) { SEM * status_sem; SEM * command_sem; RT_TASK *task; int cntr=0; M3Sds * sds = (M3Sds *)arg; printf("Starting real-time thread\n"); sds_status_size = sizeof(M3OmnibaseShmSdsStatus); sds_cmd_size = sizeof(M3OmnibaseShmSdsCommand); memset(&cmd, 0, sds_cmd_size); task = rt_task_init_schmod(nam2num("OSHMP"), 0, 0, 0, SCHED_FIFO, 0xF); rt_allow_nonroot_hrt(); if (task==NULL) { printf("Failed to create RT-TASK TSHMP\n"); return 0; } status_sem=(SEM*)rt_get_adr(nam2num(MEKA_ODOM_STATUS_SEM)); command_sem=(SEM*)rt_get_adr(nam2num(MEKA_ODOM_CMD_SEM)); if (!status_sem) { printf("Unable to find the %s semaphore.\n",MEKA_ODOM_STATUS_SEM); rt_task_delete(task); return 0; } if (!command_sem) { printf("Unable to find the %s semaphore.\n",MEKA_ODOM_CMD_SEM); rt_task_delete(task); return 0; } RTIME tick_period = nano2count(RT_TIMER_TICKS_NS_MEKA_OMNI_SHM); RTIME now = rt_get_time(); rt_task_make_periodic(task, now + tick_period, tick_period); mlockall(MCL_CURRENT | MCL_FUTURE); rt_make_hard_real_time(); long long start_time, end_time, dt; long long step_cnt = 0; sys_thread_active=1; while(!sys_thread_end) { start_time = nano2count(rt_get_cpu_time_ns()); rt_sem_wait(status_sem); memcpy(&status, sds->status, sds_status_size); rt_sem_signal(status_sem); StepShm(cntr); rt_sem_wait(command_sem); memcpy(sds->cmd, &cmd, sds_cmd_size); rt_sem_signal(command_sem); end_time = nano2count(rt_get_cpu_time_ns()); dt=end_time-start_time; if(step_cnt % 50 == 0) { printf("sta[%f,%f,%f,%f]\n",(float)status.timestamp,status.x,status.y,status.yaw); printf("cmd[%f,%f,%f,%f]\n",(float)cmd.timestamp,cmd.x_velocity,cmd.y_velocity,cmd.yaw_velocity); } /* Check the time it takes to run components, and if it takes longer than our period, make us run slower. Otherwise this task locks up the CPU.*/ if (dt > tick_period && step_cnt>10) { printf("Step %lld: Computation time of components is too long. Forcing all components to state SafeOp.\n",step_cnt); printf("Previous period: %f. New period: %f\n", (double)count2nano(tick_period),(double)count2nano(dt)); tick_period=dt; //rt_task_make_periodic(task, end + tick_period,tick_period); } step_cnt++; if (cntr++ == CYCLE_TIME_SEC * 2 * RT_TIMER_TICKS_NS_MEKA_OMNI_SHM) cntr = 0; rt_task_wait_period(); } printf("Exiting RealTime Thread...\n",0); rt_make_soft_real_time(); rt_task_delete(task); sys_thread_active=0; return 0; } //////////////////////////////////////////////////////////////////////////////////// int main (int argc, char **argv) { //RT_TASK *task; M3Sds * sys; int cntr=0; rt_allow_nonroot_hrt(); /* ros::init(argc, argv, "base_controller"); // initialize ROS node ros::AsyncSpinner spinner(1); // Use 1 thread - check if you actually need this for only publishing spinner.start(); ros::NodeHandle root_handle;*/ ros::init(argc, argv, "base_controller", ros::init_options::NoSigintHandler); // initialize ROS node // ros::AsyncSpinner spinner(1); // Use 1 thread - check if you actually need this for only publishing // spinner.start(); ros::NodeHandle root_handle; ros::NodeHandle p_nh("~"); odom_broadcaster_ptr.reset(new tf::TransformBroadcaster); cmd_sub_g = root_handle.subscribe<geometry_msgs::Twist>("omnibase_command", 1, &commandCallback); odom_publisher_g = root_handle.advertise<nav_msgs::Odometry>("omnibase_odom", 1, true); signal(SIGINT, endme); if (sys = (M3Sds*)rt_shm_alloc(nam2num(MEKA_ODOM_SHM),sizeof(M3Sds),USE_VMALLOC)) printf("Found shared memory starting shm_omnibase_controller."); else { printf("Rtai_malloc failure for %s\n",MEKA_ODOM_SHM); return 0; } rt_allow_nonroot_hrt(); /*if (!(task = rt_task_init_schmod(nam2num("TSHM"), RT_TASK_PRIORITY, 0, 0, SCHED_FIFO, 0xF))) { rt_shm_free(nam2num(TORQUE_SHM)); printf("Cannot init the RTAI task %s\n","TSHM"); return 0; }*/ hst=rt_thread_create((void*)rt_system_thread, sys, 10000); usleep(100000); //Let start up if (!sys_thread_active) { //rt_task_delete(task); rt_shm_free(nam2num(MEKA_ODOM_SHM)); printf("Startup of thread failed.\n",0); return 0; } while(!end) { usleep(250000); } printf("Removing RT thread...\n",0); sys_thread_end=1; //rt_thread_join(hst); usleep(1250000); if (sys_thread_active)printf("Real-time thread did not shutdown correctly\n"); //rt_task_delete(task); rt_shm_free(nam2num(MEKA_ODOM_SHM)); ros::shutdown(); return 0; } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2015 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. // // ======================================================================== // #include "subdivpatch1base.h" namespace embree { SubdivPatch1Base::SubdivPatch1Base (const unsigned int gID, const unsigned int pID, const unsigned int subPatch, const SubdivMesh *const mesh, const Vec2f uv[4], const float edge_level[4], const int subdiv[4], const int simd_width) : geom(gID),prim(pID),flags(0),type(INVALID_PATCH) { static_assert(sizeof(SubdivPatch1Base) == 5 * 64, "SubdivPatch1Base has wrong size"); mtx.reset(); const HalfEdge* edge = mesh->getHalfEdge(pID); if (edge->patch_type == HalfEdge::REGULAR_QUAD_PATCH) { #if PATCH_USE_BEZIER_PATCH type = BEZIER_PATCH; new (patch_v) BezierPatch3fa(BSplinePatch3fa(CatmullClarkPatch3fa(edge,mesh->getVertexBuffer()))); #else type = BSPLINE_PATCH; new (patch_v) BSplinePatch3fa(CatmullClarkPatch3fa(edge,mesh->getVertexBuffer())); #endif } #if PATCH_USE_GREGORY == 2 else if (edge->patch_type == HalfEdge::IRREGULAR_QUAD_PATCH) { type = GREGORY_PATCH; new (patch_v) DenseGregoryPatch3fa(GregoryPatch3fa(CatmullClarkPatch3fa(edge,mesh->getVertexBuffer()))); } #endif else { type = EVAL_PATCH; set_edge(mesh->getHalfEdge(pID)); set_subPatch(subPatch); } for (size_t i=0; i<4; i++) { u[i] = (unsigned short)(uv[i].x * 65535.0f); v[i] = (unsigned short)(uv[i].y * 65535.0f); } updateEdgeLevels(edge_level,subdiv,mesh,simd_width); } void SubdivPatch1Base::computeEdgeLevels(const float edge_level[4], const int subdiv[4], float level[4]) { /* init discrete edge tessellation levels and grid resolution */ assert( edge_level[0] >= 0.0f ); assert( edge_level[1] >= 0.0f ); assert( edge_level[2] >= 0.0f ); assert( edge_level[3] >= 0.0f ); level[0] = max(ceilf(adjustTessellationLevel(edge_level[0],subdiv[0])),1.0f); level[1] = max(ceilf(adjustTessellationLevel(edge_level[1],subdiv[1])),1.0f); level[2] = max(ceilf(adjustTessellationLevel(edge_level[2],subdiv[2])),1.0f); level[3] = max(ceilf(adjustTessellationLevel(edge_level[3],subdiv[3])),1.0f); } Vec2i SubdivPatch1Base::computeGridSize(const float level[4]) { unsigned width = max(level[0],level[2])+1; // n segments -> n+1 points unsigned height = max(level[1],level[3])+1; /* workaround for 2x2 intersection stencil */ #if !defined(__MIC__) width = max(width,3); // FIXME: this triggers stitching height = max(height,3); #endif return Vec2i(width,height); } void SubdivPatch1Base::updateEdgeLevels(const float edge_level[4], const int subdiv[4], const SubdivMesh *const mesh, const int simd_width) { computeEdgeLevels(edge_level,subdiv,level); Vec2i res = computeGridSize(level); grid_u_res = res.x; grid_v_res = res.y; grid_size_simd_blocks = ((grid_u_res*grid_v_res+simd_width-1)&(-simd_width)) / simd_width; grid_bvh_size_64b_blocks = getSubTreeSize64bBlocks( 0 ); const size_t grid_size_xyzuv = (grid_size_simd_blocks * simd_width) * 4; grid_subtree_size_64b_blocks = grid_bvh_size_64b_blocks + ((grid_size_xyzuv+15) / 16); /* need stiching? */ flags &= ~TRANSITION_PATCH; const unsigned int int_edge_points0 = (unsigned int)level[0] + 1; const unsigned int int_edge_points1 = (unsigned int)level[1] + 1; const unsigned int int_edge_points2 = (unsigned int)level[2] + 1; const unsigned int int_edge_points3 = (unsigned int)level[3] + 1; if (int_edge_points0 < (unsigned int)grid_u_res || int_edge_points2 < (unsigned int)grid_u_res || int_edge_points1 < (unsigned int)grid_v_res || int_edge_points3 < (unsigned int)grid_v_res) { flags |= TRANSITION_PATCH; } } size_t SubdivPatch1Base::get64BytesBlocksForGridSubTree(const GridRange& range, const unsigned int leafBlocks) { if (range.hasLeafSize()) return leafBlocks; __aligned(64) GridRange r[4]; const unsigned int children = range.splitIntoSubRanges(r); size_t blocks = 2; /* 128 bytes bvh4 node layout */ for (unsigned int i=0;i<children;i++) blocks += get64BytesBlocksForGridSubTree(r[i],leafBlocks); return blocks; } size_t SubdivPatch1Base::getSubTreeSize64bBlocks(const unsigned int leafBlocks) { #if defined(__MIC__) const unsigned int U_BLOCK_SIZE = 5; const unsigned int V_BLOCK_SIZE = 3; const unsigned int grid_u_blocks = (grid_u_res + U_BLOCK_SIZE-2) / (U_BLOCK_SIZE-1); const unsigned int grid_v_blocks = (grid_v_res + V_BLOCK_SIZE-2) / (V_BLOCK_SIZE-1); return get64BytesBlocksForGridSubTree(GridRange(0,grid_u_blocks,0,grid_v_blocks),leafBlocks); #else return get64BytesBlocksForGridSubTree(GridRange(0,grid_u_res-1,0,grid_v_res-1),leafBlocks); #endif } } <commit_msg>compile fix for VS2013 Win32<commit_after>// ======================================================================== // // Copyright 2009-2015 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. // // ======================================================================== // #include "subdivpatch1base.h" namespace embree { SubdivPatch1Base::SubdivPatch1Base (const unsigned int gID, const unsigned int pID, const unsigned int subPatch, const SubdivMesh *const mesh, const Vec2f uv[4], const float edge_level[4], const int subdiv[4], const int simd_width) : geom(gID),prim(pID),flags(0),type(INVALID_PATCH) { static_assert(sizeof(SubdivPatch1Base) == 5 * 64, "SubdivPatch1Base has wrong size"); mtx.reset(); const HalfEdge* edge = mesh->getHalfEdge(pID); if (edge->patch_type == HalfEdge::REGULAR_QUAD_PATCH) { #if PATCH_USE_BEZIER_PATCH type = BEZIER_PATCH; new (patch_v) BezierPatch3fa(BSplinePatch3fa(CatmullClarkPatch3fa(edge,mesh->getVertexBuffer()))); #else type = BSPLINE_PATCH; new (patch_v) BSplinePatch3fa(CatmullClarkPatch3fa(edge,mesh->getVertexBuffer())); #endif } #if PATCH_USE_GREGORY == 2 else if (edge->patch_type == HalfEdge::IRREGULAR_QUAD_PATCH) { type = GREGORY_PATCH; new (patch_v) DenseGregoryPatch3fa(GregoryPatch3fa(CatmullClarkPatch3fa(edge,mesh->getVertexBuffer()))); } #endif else { type = EVAL_PATCH; set_edge(mesh->getHalfEdge(pID)); set_subPatch(subPatch); } for (size_t i=0; i<4; i++) { u[i] = (unsigned short)(uv[i].x * 65535.0f); v[i] = (unsigned short)(uv[i].y * 65535.0f); } updateEdgeLevels(edge_level,subdiv,mesh,simd_width); } void SubdivPatch1Base::computeEdgeLevels(const float edge_level[4], const int subdiv[4], float level[4]) { /* init discrete edge tessellation levels and grid resolution */ assert( edge_level[0] >= 0.0f ); assert( edge_level[1] >= 0.0f ); assert( edge_level[2] >= 0.0f ); assert( edge_level[3] >= 0.0f ); level[0] = max(ceilf(adjustTessellationLevel(edge_level[0],subdiv[0])),1.0f); level[1] = max(ceilf(adjustTessellationLevel(edge_level[1],subdiv[1])),1.0f); level[2] = max(ceilf(adjustTessellationLevel(edge_level[2],subdiv[2])),1.0f); level[3] = max(ceilf(adjustTessellationLevel(edge_level[3],subdiv[3])),1.0f); } Vec2i SubdivPatch1Base::computeGridSize(const float level[4]) { int width = max(level[0],level[2])+1; // n segments -> n+1 points int height = max(level[1],level[3])+1; /* workaround for 2x2 intersection stencil */ #if !defined(__MIC__) width = max(width,3); // FIXME: this triggers stitching height = max(height,3); #endif return Vec2i(width,height); } void SubdivPatch1Base::updateEdgeLevels(const float edge_level[4], const int subdiv[4], const SubdivMesh *const mesh, const int simd_width) { computeEdgeLevels(edge_level,subdiv,level); Vec2i res = computeGridSize(level); grid_u_res = res.x; grid_v_res = res.y; grid_size_simd_blocks = ((grid_u_res*grid_v_res+simd_width-1)&(-simd_width)) / simd_width; grid_bvh_size_64b_blocks = getSubTreeSize64bBlocks( 0 ); const size_t grid_size_xyzuv = (grid_size_simd_blocks * simd_width) * 4; grid_subtree_size_64b_blocks = grid_bvh_size_64b_blocks + ((grid_size_xyzuv+15) / 16); /* need stiching? */ flags &= ~TRANSITION_PATCH; const unsigned int int_edge_points0 = (unsigned int)level[0] + 1; const unsigned int int_edge_points1 = (unsigned int)level[1] + 1; const unsigned int int_edge_points2 = (unsigned int)level[2] + 1; const unsigned int int_edge_points3 = (unsigned int)level[3] + 1; if (int_edge_points0 < (unsigned int)grid_u_res || int_edge_points2 < (unsigned int)grid_u_res || int_edge_points1 < (unsigned int)grid_v_res || int_edge_points3 < (unsigned int)grid_v_res) { flags |= TRANSITION_PATCH; } } size_t SubdivPatch1Base::get64BytesBlocksForGridSubTree(const GridRange& range, const unsigned int leafBlocks) { if (range.hasLeafSize()) return leafBlocks; __aligned(64) GridRange r[4]; const unsigned int children = range.splitIntoSubRanges(r); size_t blocks = 2; /* 128 bytes bvh4 node layout */ for (unsigned int i=0;i<children;i++) blocks += get64BytesBlocksForGridSubTree(r[i],leafBlocks); return blocks; } size_t SubdivPatch1Base::getSubTreeSize64bBlocks(const unsigned int leafBlocks) { #if defined(__MIC__) const unsigned int U_BLOCK_SIZE = 5; const unsigned int V_BLOCK_SIZE = 3; const unsigned int grid_u_blocks = (grid_u_res + U_BLOCK_SIZE-2) / (U_BLOCK_SIZE-1); const unsigned int grid_v_blocks = (grid_v_res + V_BLOCK_SIZE-2) / (V_BLOCK_SIZE-1); return get64BytesBlocksForGridSubTree(GridRange(0,grid_u_blocks,0,grid_v_blocks),leafBlocks); #else return get64BytesBlocksForGridSubTree(GridRange(0,grid_u_res-1,0,grid_v_res-1),leafBlocks); #endif } } <|endoftext|>
<commit_before>/* -*- Mode: C++; indent-tabs-mode:nil; c-basic-offset:4; -*- */ /* * gtkmm-utils - tile-page-navigator.cc * * Copyright (C) 2007 Marko Anastasov * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <gtkmm/alignment.h> #include <gtkmm/button.h> #include <gtkmm/image.h> #include <gtkmm/label.h> #include <gtkmm/stock.h> #include "tile-page-navigator.hh" namespace Gtk { namespace Util { /* TilePageNavigator::Private */ class TilePageNavigator::Private { public: Private(); ~Private() {} void connect_signals(); void on_button_next_clicked(); void on_button_previous_clicked(); TilePageNavigator::SignalClickedNext signal_clicked_next; TilePageNavigator::SignalClickedPrevious signal_clicked_previous; Glib::ustring title; Gtk::Alignment align_box; Gtk::HBox label_hbox; Gtk::Label label; Gtk::Button button_previous; Gtk::Image image_previous; Gtk::Button button_next; Gtk::Image image_next; }; TilePageNavigator::Private::Private() : title(), align_box(0.0, 1.0, 1.0, 1.0), label_hbox(false, 0), label(title), button_previous(), image_previous(Gtk::Stock::GO_BACK, Gtk::ICON_SIZE_SMALL_TOOLBAR), button_next(), image_next(Gtk::Stock::GO_FORWARD, Gtk::ICON_SIZE_SMALL_TOOLBAR) { align_box.set_padding(18, 3, 0, 0); align_box.add(label_hbox); label_hbox.pack_start(label, false, true, 0); label.set_justify(Gtk::JUSTIFY_LEFT); button_next.set_relief(Gtk::RELIEF_NONE); button_next.add(image_next); button_previous.set_relief(Gtk::RELIEF_NONE); button_previous.add(image_previous); } void TilePageNavigator::Private::on_button_next_clicked() { signal_clicked_next.emit(); } void TilePageNavigator::Private::on_button_previous_clicked() { signal_clicked_previous.emit(); } void TilePageNavigator::Private::connect_signals() { button_next.signal_clicked().connect( sigc::mem_fun(*this, &TilePageNavigator::Private::on_button_next_clicked)); button_previous.signal_clicked().connect( sigc::mem_fun(*this, &TilePageNavigator::Private::on_button_previous_clicked)); } /* TilePageNavigator */ TilePageNavigator::TilePageNavigator() { priv_.reset(new Private()); pack_start(priv_->align_box, false, true, 0); pack_end(priv_->button_next, false, true, 0); pack_end(priv_->button_previous, false, true, 0); show_all(); } TilePageNavigator::~TilePageNavigator() { } void TilePageNavigator::set_title(const Glib::ustring& title) { priv_->label.set_text(title); } void TilePageNavigator::set_title_markup(const Glib::ustring& marked_up_title) { priv_->label.set_markup(marked_up_title); } TilePageNavigator::SignalClickedNext& TilePageNavigator::signal_clicked_next() { return priv_->signal_clicked_next; } TilePageNavigator::SignalClickedPrevious& TilePageNavigator::signal_clicked_previous() { return priv_->signal_clicked_previous; } } // namespace Util } // namespace Gtk <commit_msg>Call forgotten connect_signals() in TPN::Private() ctor.<commit_after>/* -*- Mode: C++; indent-tabs-mode:nil; c-basic-offset:4; -*- */ /* * gtkmm-utils - tile-page-navigator.cc * * Copyright (C) 2007 Marko Anastasov * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <gtkmm/alignment.h> #include <gtkmm/button.h> #include <gtkmm/image.h> #include <gtkmm/label.h> #include <gtkmm/stock.h> #include "tile-page-navigator.hh" namespace Gtk { namespace Util { /* TilePageNavigator::Private */ class TilePageNavigator::Private { public: Private(); ~Private() {} void connect_signals(); void on_button_next_clicked(); void on_button_previous_clicked(); TilePageNavigator::SignalClickedNext signal_clicked_next; TilePageNavigator::SignalClickedPrevious signal_clicked_previous; Glib::ustring title; Gtk::Alignment align_box; Gtk::HBox label_hbox; Gtk::Label label; Gtk::Button button_previous; Gtk::Image image_previous; Gtk::Button button_next; Gtk::Image image_next; }; TilePageNavigator::Private::Private() : title(), align_box(0.0, 1.0, 1.0, 1.0), label_hbox(false, 0), label(title), button_previous(), image_previous(Gtk::Stock::GO_BACK, Gtk::ICON_SIZE_SMALL_TOOLBAR), button_next(), image_next(Gtk::Stock::GO_FORWARD, Gtk::ICON_SIZE_SMALL_TOOLBAR) { align_box.set_padding(18, 3, 0, 0); align_box.add(label_hbox); label_hbox.pack_start(label, false, true, 0); label.set_justify(Gtk::JUSTIFY_LEFT); button_next.set_relief(Gtk::RELIEF_NONE); button_next.add(image_next); button_previous.set_relief(Gtk::RELIEF_NONE); button_previous.add(image_previous); connect_signals(); } void TilePageNavigator::Private::on_button_next_clicked() { signal_clicked_next.emit(); } void TilePageNavigator::Private::on_button_previous_clicked() { signal_clicked_previous.emit(); } void TilePageNavigator::Private::connect_signals() { button_next.signal_clicked().connect( sigc::mem_fun(*this, &TilePageNavigator::Private::on_button_next_clicked)); button_previous.signal_clicked().connect( sigc::mem_fun(*this, &TilePageNavigator::Private::on_button_previous_clicked)); } /* TilePageNavigator */ TilePageNavigator::TilePageNavigator() { priv_.reset(new Private()); pack_start(priv_->align_box, false, true, 0); pack_end(priv_->button_next, false, true, 0); pack_end(priv_->button_previous, false, true, 0); show_all(); } TilePageNavigator::~TilePageNavigator() { } void TilePageNavigator::set_title(const Glib::ustring& title) { priv_->label.set_text(title); } void TilePageNavigator::set_title_markup(const Glib::ustring& marked_up_title) { priv_->label.set_markup(marked_up_title); } TilePageNavigator::SignalClickedNext& TilePageNavigator::signal_clicked_next() { return priv_->signal_clicked_next; } TilePageNavigator::SignalClickedPrevious& TilePageNavigator::signal_clicked_previous() { return priv_->signal_clicked_previous; } } // namespace Util } // namespace Gtk <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <cstring> #include <bh.h> #include "bh_fuse.h" #include "bh_fuse_cache.h" #include <fstream> #include <exception> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/vector.hpp> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <boost/version.hpp> #include <boost/algorithm/string/predicate.hpp> //For iequals() using namespace std; using namespace boost; using namespace boost::filesystem; namespace bohrium { /* * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * When designing an instruction hash function REMEMBER: * The hash string should either be of fixed length and all feilds * contained also be of fixed legth OR unique seperators should be * used for each variable length field and to seperate instruction * hashed. The function hashOpcodeIdShapeSweepdim may be used as * inspiration. */ static const size_t inst_sep = SIZE_MAX; static const size_t op_sep = SIZE_MAX-1; static void hashOpcodeOpidShapeSweepdim(std::ostream& os, const bh_instruction& instr, seqset<bh_view>& views) { /* The Instruction hash consists of the following fields: * <opcode> (<operant-id> <ndim> <shape> <op_sep>)[1] <sweep-dim>[2] <inst_sep> * 1: for each operand * 2: if the operation is a sweep operation */ int noperands = bh_operands(instr.opcode); os.write((const char*)&instr.opcode, sizeof(instr.opcode)); // <opcode> for(int oidx=0; oidx<noperands; ++oidx) { const bh_view& view = instr.operand[oidx]; if (bh_is_constant(&view)) continue; // Ignore constants std::pair<size_t,bool> vid = views.insert(view); size_t id = vid.first; os.write((char*)&id, sizeof(id)); // <operant-id> os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim> os.write((char*)&view.shape, sizeof(bh_index)*view.ndim); // <shape> os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep> } if (bh_opcode_is_sweep(instr.opcode)) os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim> os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep> } static void hashOpidSweepdim(std::ostream& os, const bh_instruction& instr, seqset<bh_view>& views) { /* The Instruction hash consists of the following fields: * (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator> * 1: for each operand * 2: if the operation is a sweep operation */ int noperands = bh_operands(instr.opcode); for(int oidx=0; oidx<noperands; ++oidx) { const bh_view& view = instr.operand[oidx]; if (bh_is_constant(&view)) continue; // Ignore constants std::pair<size_t,bool> vid = views.insert(view); size_t id = vid.first; os.write((char*)&id, sizeof(id)); // <operant-id> } os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep> if (bh_opcode_is_sweep(instr.opcode)) { const bh_view& view = instr.operand[1]; os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim> os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim> } os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep> } static void hashScalarOpidSweepdim(std::ostream& os, const bh_instruction& instr, seqset<bh_view>& views) { /* The Instruction hash consists of the following fields: * <is_scalar> (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator> * 1: for each operand * 2: if the operation is a sweep operation */ bool scalar = (bh_is_scalar(&(instr.operand[0])) || (bh_opcode_is_accumulate(instr.opcode) && instr.operand[0].ndim == 1)); os.write((char*)&scalar, sizeof(scalar)); // <op_sep> int noperands = bh_operands(instr.opcode); for(int oidx=0; oidx<noperands; ++oidx) { const bh_view& view = instr.operand[oidx]; if (bh_is_constant(&view)) continue; // Ignore constants std::pair<size_t,bool> vid = views.insert(view); size_t id = vid.first; os.write((char*)&id, sizeof(id)); // <operant-id> } os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep> if (bh_opcode_is_sweep(instr.opcode)) { const bh_view& view = instr.operand[1]; os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim> os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim> } os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep> } static void hashOpid(std::ostream& os, const bh_instruction& instr, seqset<bh_view>& views) { /* The Instruction hash consists of the following fields: * (<operant-id>)[1] <seperator> * 1: for each operand */ int noperands = bh_operands(instr.opcode); for(int oidx=0; oidx<noperands; ++oidx) { const bh_view& view = instr.operand[oidx]; if (bh_is_constant(&view)) continue; // Ignore constants std::pair<size_t,bool> vid = views.insert(view); size_t id = vid.first; os.write((char*)&id, sizeof(id)); // <operant-id> } os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep> } #define __scalar(i) (bh_is_scalar(&(i)->operand[0]) || \ (bh_opcode_is_accumulate((i)->opcode) && (i)->operand[0].ndim == 1)) typedef void (*InstrHash)(std::ostream& os, const bh_instruction &instr, seqset<bh_view>& views); static InstrHash getInstrHash(FuseModel fuseModel) { switch(fuseModel) { case BROADEST: return &hashOpid; case NO_XSWEEP: return &hashOpidSweepdim; case NO_XSWEEP_SCALAR_SEPERATE: return &hashScalarOpidSweepdim; case SAME_SHAPE: case SAME_SHAPE_RANGE: case SAME_SHAPE_RANDOM: case SAME_SHAPE_RANGE_RANDOM: case SAME_SHAPE_GENERATE_1DREDUCE: return &hashOpcodeOpidShapeSweepdim; default: throw runtime_error("Could not find valid hash function for fuse model."); } } //Constructor of the BatchHash class BatchHash::BatchHash(const vector<bh_instruction> &instr_list) { InstrHash hashFn = getInstrHash(fuse_get_selected_model()); std::ostringstream data(std::ios_base::ate); for(const bh_instruction& instr: instr_list) { hashFn(data, instr, views); } boost::hash<string> hasher; _hash = hasher(data.str()); } InstrIndexesList &FuseCache::insert(const BatchHash &batch, const vector<bh_ir_kernel> &kernel_list) { cache[batch.hash()] = InstrIndexesList(kernel_list, batch.hash(), fuser_name); return cache[batch.hash()]; } bool FuseCache::lookup(const BatchHash &batch, bh_ir &bhir, vector<bh_ir_kernel> &kernel_list) const { assert(kernel_list.size() == 0); CacheMap::const_iterator it = cache.find(batch.hash()); if(deactivated or it == cache.end()) { return false; } else { it->second.fill_kernel_list(bhir, kernel_list); return true; } } void FuseCache::write_to_files() const { if(deactivated) return; if(dir_path == NULL) { cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in " \ "the configure file thus no cache files are written to disk!" << endl; return; } path cache_dir(dir_path); if(create_directories(cache_dir)) { cout << "[FUSE-CACHE] Creating cache diretory " << cache_dir << endl; #if BOOST_VERSION > 104900 permissions(cache_dir, all_all); #endif } path tmp_dir = cache_dir / unique_path(); create_directories(tmp_dir); for(CacheMap::const_iterator it=cache.begin(); it != cache.end(); ++it) { string name; it->second.get_filename(name); path shared_name = cache_dir / name; if(exists(shared_name)) continue;//No need to overwrite an existing file path unique_name = tmp_dir / name; ofstream ofs(unique_name.string().c_str()); boost::archive::text_oarchive oa(ofs); oa << it->second; ofs.close(); #if BOOST_VERSION > 104900 permissions(unique_name, all_all); #endif rename(unique_name, shared_name); } remove(tmp_dir); } void FuseCache::load_from_files() { if(dir_path == NULL) { cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in " \ "the configure file thus no cache files are loaded from disk!" << endl; return; } path p(dir_path); if(not (exists(p) and is_directory(p))) return; string fuse_model_name; fuse_model_text(fuse_get_selected_model(), fuse_model_name); //Iterate the 'dir_path' diretory and load each file directory_iterator it(p), eod; BOOST_FOREACH(const path &f, make_pair(it, eod)) { if(is_regular_file(f)) { int tries = 0; while(1) { try { ifstream ifs(f.string().c_str()); boost::archive::text_iarchive ia(ifs); InstrIndexesList t; ia >> t; if(iequals(t.fuser_name(), fuser_name) and iequals(t.fuse_model(), fuse_model_name)) { cache[t.hash()] = t; } } catch(const std::exception &e) { if(++tries >= 10) { cerr << "[FUSE-CACHE] failed to open file '" << f.string(); cerr << "' (" << tries << " tries): " << e.what() << endl; } else continue; } break; } } } } } //namespace bohrium <commit_msg>bh_fuse_cache changed prototype of instruction hash functions<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <cstring> #include <bh.h> #include "bh_fuse.h" #include "bh_fuse_cache.h" #include <fstream> #include <exception> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/vector.hpp> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <boost/version.hpp> #include <boost/algorithm/string/predicate.hpp> //For iequals() using namespace std; using namespace boost; using namespace boost::filesystem; namespace bohrium { /* * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * OBS * When designing an instruction hash function REMEMBER: * The hash string should either be of fixed length and all feilds * contained also be of fixed legth OR unique seperators should be * used for each variable length field and to seperate instruction * hashed. The function hashOpcodeIdShapeSweepdim may be used as * inspiration. */ static const size_t inst_sep = SIZE_MAX; static const size_t op_sep = SIZE_MAX-1; static void hashOpcodeOpidShapeSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash) { /* The Instruction hash consists of the following fields: * <opcode> (<operant-id> <ndim> <shape> <op_sep>)[1] <sweep-dim>[2] <inst_sep> * 1: for each operand * 2: if the operation is a sweep operation */ int noperands = bh_operands(instr.opcode); os.write((const char*)&instr.opcode, sizeof(instr.opcode)); // <opcode> for(int oidx=0; oidx<noperands; ++oidx) { const bh_view& view = instr.operand[oidx]; if (bh_is_constant(&view)) continue; // Ignore constants std::pair<size_t,bool> vid = batchHash.views.insert(view); size_t id = vid.first; os.write((char*)&id, sizeof(id)); // <operant-id> os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim> os.write((char*)&view.shape, sizeof(bh_index)*view.ndim); // <shape> os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep> } if (bh_opcode_is_sweep(instr.opcode)) os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim> os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep> } static void hashOpidSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash) { /* The Instruction hash consists of the following fields: * (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator> * 1: for each operand * 2: if the operation is a sweep operation */ int noperands = bh_operands(instr.opcode); for(int oidx=0; oidx<noperands; ++oidx) { const bh_view& view = instr.operand[oidx]; if (bh_is_constant(&view)) continue; // Ignore constants std::pair<size_t,bool> vid = batchHash.views.insert(view); size_t id = vid.first; os.write((char*)&id, sizeof(id)); // <operant-id> } os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep> if (bh_opcode_is_sweep(instr.opcode)) { const bh_view& view = instr.operand[1]; os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim> os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim> } os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep> } static void hashScalarOpidSweepdim(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash) { /* The Instruction hash consists of the following fields: * <is_scalar> (<operant-id>)[1] <op_sep> (<ndim> <sweep-dim>)[2] <seperator> * 1: for each operand * 2: if the operation is a sweep operation */ bool scalar = (bh_is_scalar(&(instr.operand[0])) || (bh_opcode_is_accumulate(instr.opcode) && instr.operand[0].ndim == 1)); os.write((char*)&scalar, sizeof(scalar)); // <op_sep> int noperands = bh_operands(instr.opcode); for(int oidx=0; oidx<noperands; ++oidx) { const bh_view& view = instr.operand[oidx]; if (bh_is_constant(&view)) continue; // Ignore constants std::pair<size_t,bool> vid = batchHash.views.insert(view); size_t id = vid.first; os.write((char*)&id, sizeof(id)); // <operant-id> } os.write((char*)&op_sep, sizeof(op_sep)); // <op_sep> if (bh_opcode_is_sweep(instr.opcode)) { const bh_view& view = instr.operand[1]; os.write((char*)&view.ndim, sizeof(view.ndim)); // <ndim> os.write((char*)&instr.constant.value.int64, sizeof(bh_int64)); // <sweep-dim> } os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep> } static void hashOpid(std::ostream& os, const bh_instruction& instr, BatchHash& batchHash) { /* The Instruction hash consists of the following fields: * (<operant-id>)[1] <seperator> * 1: for each operand */ int noperands = bh_operands(instr.opcode); for(int oidx=0; oidx<noperands; ++oidx) { const bh_view& view = instr.operand[oidx]; if (bh_is_constant(&view)) continue; // Ignore constants std::pair<size_t,bool> vid = batchHash.views.insert(view); size_t id = vid.first; os.write((char*)&id, sizeof(id)); // <operant-id> } os.write((char*)&inst_sep, sizeof(inst_sep)); // <inst_sep> } #define __scalar(i) (bh_is_scalar(&(i)->operand[0]) || \ (bh_opcode_is_accumulate((i)->opcode) && (i)->operand[0].ndim == 1)) typedef void (*InstrHash)(std::ostream& os, const bh_instruction &instr, BatchHash& batchHash); static InstrHash getInstrHash(FuseModel fuseModel) { switch(fuseModel) { case BROADEST: return &hashOpid; case NO_XSWEEP: return &hashOpidSweepdim; case NO_XSWEEP_SCALAR_SEPERATE: return &hashScalarOpidSweepdim; case NO_XSWEEP_SCALAR_SEPERATE_SHAPE_MATCH: return &hashScalarOpidSweepdim; case SAME_SHAPE: case SAME_SHAPE_RANGE: case SAME_SHAPE_RANDOM: case SAME_SHAPE_RANGE_RANDOM: case SAME_SHAPE_GENERATE_1DREDUCE: return &hashOpcodeOpidShapeSweepdim; default: throw runtime_error("Could not find valid hash function for fuse model."); } } //Constructor of the BatchHash class BatchHash::BatchHash(const vector<bh_instruction> &instr_list) { InstrHash hashFn = getInstrHash(fuse_get_selected_model()); std::ostringstream data(std::ios_base::ate); for(const bh_instruction& instr: instr_list) { hashFn(data, instr, *this); } boost::hash<string> hasher; _hash = hasher(data.str()); } InstrIndexesList &FuseCache::insert(const BatchHash &batch, const vector<bh_ir_kernel> &kernel_list) { cache[batch.hash()] = InstrIndexesList(kernel_list, batch.hash(), fuser_name); return cache[batch.hash()]; } bool FuseCache::lookup(const BatchHash &batch, bh_ir &bhir, vector<bh_ir_kernel> &kernel_list) const { assert(kernel_list.size() == 0); CacheMap::const_iterator it = cache.find(batch.hash()); if(deactivated or it == cache.end()) { return false; } else { it->second.fill_kernel_list(bhir, kernel_list); return true; } } void FuseCache::write_to_files() const { if(deactivated) return; if(dir_path == NULL) { cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in " \ "the configure file thus no cache files are written to disk!" << endl; return; } path cache_dir(dir_path); if(create_directories(cache_dir)) { cout << "[FUSE-CACHE] Creating cache diretory " << cache_dir << endl; #if BOOST_VERSION > 104900 permissions(cache_dir, all_all); #endif } path tmp_dir = cache_dir / unique_path(); create_directories(tmp_dir); for(CacheMap::const_iterator it=cache.begin(); it != cache.end(); ++it) { string name; it->second.get_filename(name); path shared_name = cache_dir / name; if(exists(shared_name)) continue;//No need to overwrite an existing file path unique_name = tmp_dir / name; ofstream ofs(unique_name.string().c_str()); boost::archive::text_oarchive oa(ofs); oa << it->second; ofs.close(); #if BOOST_VERSION > 104900 permissions(unique_name, all_all); #endif rename(unique_name, shared_name); } remove(tmp_dir); } void FuseCache::load_from_files() { if(dir_path == NULL) { cout << "[FUSE-CACHE] Couldn't find the 'cache_path' key in " \ "the configure file thus no cache files are loaded from disk!" << endl; return; } path p(dir_path); if(not (exists(p) and is_directory(p))) return; string fuse_model_name; fuse_model_text(fuse_get_selected_model(), fuse_model_name); //Iterate the 'dir_path' diretory and load each file directory_iterator it(p), eod; BOOST_FOREACH(const path &f, make_pair(it, eod)) { if(is_regular_file(f)) { int tries = 0; while(1) { try { ifstream ifs(f.string().c_str()); boost::archive::text_iarchive ia(ifs); InstrIndexesList t; ia >> t; if(iequals(t.fuser_name(), fuser_name) and iequals(t.fuse_model(), fuse_model_name)) { cache[t.hash()] = t; } } catch(const std::exception &e) { if(++tries >= 10) { cerr << "[FUSE-CACHE] failed to open file '" << f.string(); cerr << "' (" << tries << " tries): " << e.what() << endl; } else continue; } break; } } } } } //namespace bohrium <|endoftext|>
<commit_before>/* This file is part of kdepim. Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kde-features.h" #include "kde-features_parser.h" #include <kapplication.h> #include <kcmdlineargs.h> #include <kaboutdata.h> #include <kdebug.h> #include <qfile.h> #include <qtextstream.h> #include <iostream> static const KCmdLineOptions options[] = { { "+featurelist", "Name of featurelist XML file", 0 }, KCmdLineLastOption }; void displayFeature( Feature *f ) { std::cout << "FEATURE: " << f->summary().local8Bit() << std::endl; Responsible::List r = f->responsibleList(); Responsible::List::ConstIterator it; for( it = r.begin(); it != r.end(); ++it ) { std::cout << " RESPONSIBLE: " << (*it)->name().local8Bit() << " (" << (*it)->email().local8Bit() << ")" << std::endl; } std::cout << " TARGET: " << f->target().local8Bit() << std::endl; std::cout << " STATUS: " << f->status().local8Bit() << std::endl; } void displayCategory( const QList<Category *> categories ) { Category::List::ConstIterator it; for( it = categories.begin(); it != categories.end(); ++it ) { std::cout << "CATEGORY: " << (*it)->name().local8Bit() << std::endl; Feature::List features = (*it)->featureList(); Feature::List::ConstIterator it2; for( it2 = features.begin(); it2 != features.end(); ++it2 ) { displayFeature( *it2 ); } displayCategory( (*it)->categoryList() ); } } int main( int argc, char **argv ) { KAboutData aboutData( "dumpfeaturelist", "Dump XML feature list to stdout", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); KApplication app( false, false ); KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if ( args->count() != 1 ) { args->usage( "Wrong number of arguments." ); } QString filename = QFile::decodeName( args->arg( 0 ) ); FeaturesParser parser; Features *features = parser.parseFile( filename ); if ( !features ) { kError() << "Parse error" << endl; } else { QList<Category *> categories = features->categoryList(); displayCategory( categories ); } QString out = filename + ".out"; if ( !features->writeFile( out ) ) { kError() << "Write error" << endl; } } <commit_msg>port<commit_after>/* This file is part of kdepim. Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kde-features.h" #include "kde-features_parser.h" #include <kapplication.h> #include <kcmdlineargs.h> #include <kaboutdata.h> #include <kdebug.h> #include <qfile.h> #include <qtextstream.h> #include <iostream> static const KCmdLineOptions options[] = { { "+featurelist", "Name of featurelist XML file", 0 }, KCmdLineLastOption }; void displayFeature( Feature *f ) { std::cout << "FEATURE: " << f->summary().local8Bit().data() << std::endl; Responsible::List r = f->responsibleList(); Responsible::List::ConstIterator it; for( it = r.begin(); it != r.end(); ++it ) { std::cout << " RESPONSIBLE: " << (*it)->name().local8Bit().data() << " (" << (*it)->email().local8Bit().data() << ")" << std::endl; } std::cout << " TARGET: " << f->target().local8Bit().data() << std::endl; std::cout << " STATUS: " << f->status().local8Bit().data() << std::endl; } void displayCategory( const QList<Category *> categories ) { Category::List::ConstIterator it; for( it = categories.begin(); it != categories.end(); ++it ) { std::cout << "CATEGORY: " << (*it)->name().local8Bit().data() << std::endl; Feature::List features = (*it)->featureList(); Feature::List::ConstIterator it2; for( it2 = features.begin(); it2 != features.end(); ++it2 ) { displayFeature( *it2 ); } displayCategory( (*it)->categoryList() ); } } int main( int argc, char **argv ) { KAboutData aboutData( "dumpfeaturelist", "Dump XML feature list to stdout", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData, KCmdLineArgs::CmdLineArgNone ); KCmdLineArgs::addCmdLineOptions( options ); KApplication app( false ); KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if ( args->count() != 1 ) { args->usage( "Wrong number of arguments." ); } QString filename = QFile::decodeName( args->arg( 0 ) ); FeaturesParser parser; Features *features = parser.parseFile( filename ); if ( !features ) { kError() << "Parse error" << endl; } else { QList<Category *> categories = features->categoryList(); displayCategory( categories ); } QString out = filename + ".out"; if ( !features->writeFile( out ) ) { kError() << "Write error" << endl; } } <|endoftext|>
<commit_before>#include "bind.hpp" #include "ast.hpp" #include "context.hpp" #include "eval.hpp" #include <map> #include <iostream> #include <sstream> #include "to_string.hpp" namespace Sass { using namespace std; void bind(string callee, Parameters* ps, Arguments* as, Context& ctx, Env* env, Eval* eval) { map<string, Parameter*> param_map; // Set up a map to ensure named arguments refer to actual parameters. Also // eval each default value left-to-right, wrt env, populating env as we go. for (size_t i = 0, L = ps->length(); i < L; ++i) { Parameter* p = (*ps)[i]; param_map[p->name()] = p; // if (p->default_value()) { // env->local_frame()[p->name()] = p->default_value()->perform(eval->with(env)); // } } // plug in all args; if we have leftover params, deal with it later size_t ip = 0, LP = ps->length(); size_t ia = 0, LA = as->length(); while (ia < LA) { Argument* a = (*as)[ia]; if (ip >= LP) { // skip empty rest arguments if (a->is_rest_argument()) { if (List* l = dynamic_cast<List*>(a->value())) { if (l->length() == 0) { ++ ia; continue; } } } stringstream msg; msg << callee << " only takes " << LP << " arguments; " << "given " << LA; error(msg.str(), as->pstate()); } Parameter* p = (*ps)[ip]; // If the current parameter is the rest parameter, process and break the loop if (p->is_rest_parameter()) { if (a->is_rest_argument()) { // rest param and rest arg -- just add one to the other if (env->has_local(p->name())) { *static_cast<List*>(env->local_frame()[p->name()]) += static_cast<List*>(a->value()); } else { env->local_frame()[p->name()] = a->value(); } } else if (a->is_keyword_argument()) { // expand keyword arguments into their parameters List* arglist = new (ctx.mem) List(p->pstate(), 0, List::COMMA, true); env->local_frame()[p->name()] = arglist; Map* argmap = static_cast<Map*>(a->value()); for (auto key : argmap->keys()) { string name = unquote(static_cast<String_Constant*>(key)->value()); (*arglist) << new (ctx.mem) Argument(key->pstate(), argmap->at(key), name, false); } } else { // copy all remaining arguments into the rest parameter, preserving names List* arglist = new (ctx.mem) List(p->pstate(), 0, List::COMMA, true); env->local_frame()[p->name()] = arglist; while (ia < LA) { a = (*as)[ia]; (*arglist) << new (ctx.mem) Argument(a->pstate(), a->value(), a->name(), false); ++ia; } } ++ip; break; } // If the current argument is the rest argument, extract a value for processing else if (a->is_rest_argument()) { // normal param and rest arg List* arglist = static_cast<List*>(a->value()); // empty rest arg - treat all args as default values if (!arglist->length()) { break; } // otherwise move one of the rest args into the param, converting to argument if necessary if (arglist->is_arglist()) { a = static_cast<Argument*>((*arglist)[0]); } else { Expression* a_to_convert = (*arglist)[0]; a = new (ctx.mem) Argument(a_to_convert->pstate(), a_to_convert, "", false); } arglist->elements().erase(arglist->elements().begin()); if (!arglist->length() || (!arglist->is_arglist() && ip + 1 == LP)) { ++ia; } } else if (a->is_keyword_argument()) { Map* argmap = static_cast<Map*>(a->value()); for (auto key : argmap->keys()) { string name = "$" + unquote(static_cast<String_Constant*>(key)->value()); if (!param_map.count(name)) { stringstream msg; msg << callee << " has no parameter named " << name; error(msg.str(), a->pstate()); } env->local_frame()[name] = argmap->at(key); } ++ia; continue; } else { ++ia; } if (a->name().empty()) { if (env->has_local(p->name())) { stringstream msg; msg << "parameter " << p->name() << " provided more than once in call to " << callee; error(msg.str(), a->pstate()); } // ordinal arg -- bind it to the next param env->local_frame()[p->name()] = a->value(); ++ip; } else { // named arg -- bind it to the appropriately named param if (!param_map.count(a->name())) { stringstream msg; msg << callee << " has no parameter named " << a->name(); error(msg.str(), a->pstate()); } if (param_map[a->name()]->is_rest_parameter()) { stringstream msg; msg << "argument " << a->name() << " of " << callee << "cannot be used as named argument"; error(msg.str(), a->pstate()); } if (env->has_local(a->name())) { stringstream msg; msg << "parameter " << p->name() << "provided more than once in call to " << callee; error(msg.str(), a->pstate()); } env->local_frame()[a->name()] = a->value(); } } // If we make it here, we're out of args but may have leftover params. // That's only okay if they have default values, or were already bound by // named arguments, or if it's a single rest-param. for (size_t i = ip; i < LP; ++i) { To_String to_string(&ctx); Parameter* leftover = (*ps)[i]; // cerr << "env for default params:" << endl; // env->print(); // cerr << "********" << endl; if (!env->has_local(leftover->name())) { if (leftover->is_rest_parameter()) { env->local_frame()[leftover->name()] = new (ctx.mem) List(leftover->pstate(), 0, List::COMMA, true); } else if (leftover->default_value()) { // make sure to eval the default value in the env that we've been populating Env* old_env = eval->env; Backtrace* old_bt = eval->backtrace; Contextualize* old_context = eval->contextualize; Expression* dv = leftover->default_value()->perform(eval->with(env, eval->backtrace)); eval->env = old_env; eval->backtrace = old_bt; eval->contextualize = old_context; // dv->perform(&to_string); env->local_frame()[leftover->name()] = dv; } else { // param is unbound and has no default value -- error stringstream msg; msg << "required parameter " << leftover->name() << " is missing in call to " << callee; error(msg.str(), as->pstate()); } } } return; } } <commit_msg>Fix separator preserving with rest args<commit_after>#include "bind.hpp" #include "ast.hpp" #include "context.hpp" #include "eval.hpp" #include <map> #include <iostream> #include <sstream> #include "to_string.hpp" namespace Sass { using namespace std; void bind(string callee, Parameters* ps, Arguments* as, Context& ctx, Env* env, Eval* eval) { map<string, Parameter*> param_map; // Set up a map to ensure named arguments refer to actual parameters. Also // eval each default value left-to-right, wrt env, populating env as we go. for (size_t i = 0, L = ps->length(); i < L; ++i) { Parameter* p = (*ps)[i]; param_map[p->name()] = p; // if (p->default_value()) { // env->local_frame()[p->name()] = p->default_value()->perform(eval->with(env)); // } } // plug in all args; if we have leftover params, deal with it later size_t ip = 0, LP = ps->length(); size_t ia = 0, LA = as->length(); while (ia < LA) { Argument* a = (*as)[ia]; if (ip >= LP) { // skip empty rest arguments if (a->is_rest_argument()) { if (List* l = dynamic_cast<List*>(a->value())) { if (l->length() == 0) { ++ ia; continue; } } } stringstream msg; msg << callee << " only takes " << LP << " arguments; " << "given " << LA; error(msg.str(), as->pstate()); } Parameter* p = (*ps)[ip]; // If the current parameter is the rest parameter, process and break the loop if (p->is_rest_parameter()) { if (a->is_rest_argument()) { // rest param and rest arg -- just add one to the other if (env->has_local(p->name())) { *static_cast<List*>(env->local_frame()[p->name()]) += static_cast<List*>(a->value()); } else { env->local_frame()[p->name()] = a->value(); } } else if (a->is_keyword_argument()) { // expand keyword arguments into their parameters List* arglist = new (ctx.mem) List(p->pstate(), 0, List::COMMA, true); env->local_frame()[p->name()] = arglist; Map* argmap = static_cast<Map*>(a->value()); for (auto key : argmap->keys()) { string name = unquote(static_cast<String_Constant*>(key)->value()); (*arglist) << new (ctx.mem) Argument(key->pstate(), argmap->at(key), name, false); } } else { // copy all remaining arguments into the rest parameter, preserving names List* arglist = new (ctx.mem) List(p->pstate(), 0, List::COMMA, true); env->local_frame()[p->name()] = arglist; while (ia < LA) { a = (*as)[ia]; if (a->is_rest_argument()) { if (List* rest = dynamic_cast<List*>(a->value())) { arglist->separator(rest->separator()); } } (*arglist) << new (ctx.mem) Argument(a->pstate(), a->value(), a->name(), false); ++ia; } } ++ip; break; } // If the current argument is the rest argument, extract a value for processing else if (a->is_rest_argument()) { // normal param and rest arg List* arglist = static_cast<List*>(a->value()); // empty rest arg - treat all args as default values if (!arglist->length()) { break; } // otherwise move one of the rest args into the param, converting to argument if necessary if (arglist->is_arglist()) { a = static_cast<Argument*>((*arglist)[0]); } else { Expression* a_to_convert = (*arglist)[0]; a = new (ctx.mem) Argument(a_to_convert->pstate(), a_to_convert, "", false); } arglist->elements().erase(arglist->elements().begin()); if (!arglist->length() || (!arglist->is_arglist() && ip + 1 == LP)) { ++ia; } } else if (a->is_keyword_argument()) { Map* argmap = static_cast<Map*>(a->value()); for (auto key : argmap->keys()) { string name = "$" + unquote(static_cast<String_Constant*>(key)->value()); if (!param_map.count(name)) { stringstream msg; msg << callee << " has no parameter named " << name; error(msg.str(), a->pstate()); } env->local_frame()[name] = argmap->at(key); } ++ia; continue; } else { ++ia; } if (a->name().empty()) { if (env->has_local(p->name())) { stringstream msg; msg << "parameter " << p->name() << " provided more than once in call to " << callee; error(msg.str(), a->pstate()); } // ordinal arg -- bind it to the next param env->local_frame()[p->name()] = a->value(); ++ip; } else { // named arg -- bind it to the appropriately named param if (!param_map.count(a->name())) { stringstream msg; msg << callee << " has no parameter named " << a->name(); error(msg.str(), a->pstate()); } if (param_map[a->name()]->is_rest_parameter()) { stringstream msg; msg << "argument " << a->name() << " of " << callee << "cannot be used as named argument"; error(msg.str(), a->pstate()); } if (env->has_local(a->name())) { stringstream msg; msg << "parameter " << p->name() << "provided more than once in call to " << callee; error(msg.str(), a->pstate()); } env->local_frame()[a->name()] = a->value(); } } // If we make it here, we're out of args but may have leftover params. // That's only okay if they have default values, or were already bound by // named arguments, or if it's a single rest-param. for (size_t i = ip; i < LP; ++i) { To_String to_string(&ctx); Parameter* leftover = (*ps)[i]; // cerr << "env for default params:" << endl; // env->print(); // cerr << "********" << endl; if (!env->has_local(leftover->name())) { if (leftover->is_rest_parameter()) { env->local_frame()[leftover->name()] = new (ctx.mem) List(leftover->pstate(), 0, List::COMMA, true); } else if (leftover->default_value()) { // make sure to eval the default value in the env that we've been populating Env* old_env = eval->env; Backtrace* old_bt = eval->backtrace; Contextualize* old_context = eval->contextualize; Expression* dv = leftover->default_value()->perform(eval->with(env, eval->backtrace)); eval->env = old_env; eval->backtrace = old_bt; eval->contextualize = old_context; // dv->perform(&to_string); env->local_frame()[leftover->name()] = dv; } else { // param is unbound and has no default value -- error stringstream msg; msg << "required parameter " << leftover->name() << " is missing in call to " << callee; error(msg.str(), as->pstate()); } } } return; } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2010 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2005-01-14 // Updated : 2010-05-30 // Licence : This source is under MIT License // File : glm/glm.hpp /////////////////////////////////////////////////////////////////////////////////////////////////// /*! \mainpage OpenGL Mathematics * * OpenGL Mathematics (GLM) is a C++ mathematics library for 3D applications based on the OpenGL Shading Language (GLSL) specification. * * GLM provides 3D programmers with math classes and functions that are similar to GLSL or any high level GPU programming language. The idea is to have a library that has identical naming conventions and functionalities than GLSL so that when developers know GLSL, they know how to use GLM. * * However, this project isn't limited by GLSL features. An extension system, based on the GLSL extension conventions, allows extended capabilities. * * This library can be used with OpenGL but also for software rendering (Raytracing / Rasterisation), image processing and as much contexts as a simple math library could be used for. * * GLM is written as a platform independent library and supports the following compilers: * - GNU GCC 3.4 and higher * - Microsoft Visual Studio 8.0 and higher * * The source code is under the MIT licence. * * Any feedback is welcome and can be sent to glm@g-truc.net. * */ #ifndef glm_glm #define glm_glm #ifdef max #undef max #endif #ifdef min #undef min #endif #define GLMvalType typename genType::value_type #define GLMcolType typename genType::col_type #define GLMrowType typename genType::row_type #include <cmath> #include <climits> #include <cfloat> #include <limits> #include "./setup.hpp" //! GLM namespace, it contains all GLSL based features. namespace glm { namespace test { bool main_bug(); bool main_core(); }//namespace test //! GLM core. Namespace that includes all the feature define by GLSL 1.30.8 specification. This namespace is included in glm namespace. namespace core { //! Scalar, vectors and matrices //! from section 4.1.2 Booleans, 4.1.3 Integers section, 4.1.4 Floats section, //! 4.1.5 Vectors and section 4.1.6 Matrices of GLSL 1.30.8 specification. //! This namespace resolves precision qualifier define in section 4.5 of GLSL 1.30.8 specification. namespace type{} //! Some of the functions defined in section 8 Built-in Functions of GLSL 1.30.8 specification. //! Angle and trigonometry, exponential, common, geometric, matrix and vector relational functions. namespace function{} } //namespace core //! G-Truc Creation stable extensions. namespace gtc{} //! G-Truc Creation experimental extensions. //! The interface could change between releases. namespace gtx{} //! IMG extensions. namespace img{} //! VIRTREV extensions. namespace img{} } //namespace glm #include "./core/_detail.hpp" #include "./core/type.hpp" #include "./core/func_trigonometric.hpp" #include "./core/func_exponential.hpp" #include "./core/func_common.hpp" #include "./core/func_packing.hpp" #include "./core/func_geometric.hpp" #include "./core/func_matrix.hpp" #include "./core/func_vector_relational.hpp" #include "./core/func_integer.hpp" #include "./core/func_noise.hpp" #include "./core/_swizzle.hpp" #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_CORE | GLM_MESSAGE_NOTIFICATION))) # pragma message("GLM message: Core library included") #endif//GLM_MESSAGE #if(defined(GLM_COMPILER) && (GLM_COMPILER & GLM_COMPILER_VC)) # define GLM_DEPRECATED __declspec(deprecated) # define GLM_RESTRICT __restrict # define GLM_ALIGN(x) __declspec(align(x)) //# define aligned(x) __declspec(align(x)) struct #else # define GLM_DEPRECATED # define GLM_RESTRICT # define GLM_ALIGN(x) #endif//GLM_COMPILER //////////////////// // check type sizes #ifndef GLM_STATIC_ASSERT_NULL GLM_STATIC_ASSERT(sizeof(glm::detail::int8)==1, "int8 size isn't 1 byte on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::int16)==2, "int16 size isn't 2 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::int32)==4, "int32 size isn't 4 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::int64)==8, "int64 size isn't 8 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::uint8)==1, "uint8 size isn't 1 byte on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::uint16)==2, "uint16 size isn't 2 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::uint32)==4, "uint32 size isn't 4 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::uint64)==8, "uint64 size isn't 8 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::float16)==2, "float16 size isn't 2 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::float32)==4, "float32 size isn't 4 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::float64)==8, "float64 size isn't 8 bytes on this platform"); #endif//GLM_STATIC_ASSERT_NULL #endif //glm_glm <commit_msg>Fixed GCC static assert<commit_after>/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2010 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2005-01-14 // Updated : 2010-05-30 // Licence : This source is under MIT License // File : glm/glm.hpp /////////////////////////////////////////////////////////////////////////////////////////////////// /*! \mainpage OpenGL Mathematics * * OpenGL Mathematics (GLM) is a C++ mathematics library for 3D applications based on the OpenGL Shading Language (GLSL) specification. * * GLM provides 3D programmers with math classes and functions that are similar to GLSL or any high level GPU programming language. The idea is to have a library that has identical naming conventions and functionalities than GLSL so that when developers know GLSL, they know how to use GLM. * * However, this project isn't limited by GLSL features. An extension system, based on the GLSL extension conventions, allows extended capabilities. * * This library can be used with OpenGL but also for software rendering (Raytracing / Rasterisation), image processing and as much contexts as a simple math library could be used for. * * GLM is written as a platform independent library and supports the following compilers: * - GNU GCC 3.4 and higher * - Microsoft Visual Studio 8.0 and higher * * The source code is under the MIT licence. * * Any feedback is welcome and can be sent to glm@g-truc.net. * */ #ifndef glm_glm #define glm_glm #ifdef max #undef max #endif #ifdef min #undef min #endif #define GLMvalType typename genType::value_type #define GLMcolType typename genType::col_type #define GLMrowType typename genType::row_type #include <cmath> #include <climits> #include <cfloat> #include <limits> #include "./setup.hpp" //! GLM namespace, it contains all GLSL based features. namespace glm { namespace test { bool main_bug(); bool main_core(); }//namespace test //! GLM core. Namespace that includes all the feature define by GLSL 1.30.8 specification. This namespace is included in glm namespace. namespace core { //! Scalar, vectors and matrices //! from section 4.1.2 Booleans, 4.1.3 Integers section, 4.1.4 Floats section, //! 4.1.5 Vectors and section 4.1.6 Matrices of GLSL 1.30.8 specification. //! This namespace resolves precision qualifier define in section 4.5 of GLSL 1.30.8 specification. namespace type{} //! Some of the functions defined in section 8 Built-in Functions of GLSL 1.30.8 specification. //! Angle and trigonometry, exponential, common, geometric, matrix and vector relational functions. namespace function{} } //namespace core //! G-Truc Creation stable extensions. namespace gtc{} //! G-Truc Creation experimental extensions. //! The interface could change between releases. namespace gtx{} //! IMG extensions. namespace img{} //! VIRTREV extensions. namespace img{} } //namespace glm #include "./core/_detail.hpp" #include "./core/type.hpp" #include "./core/func_trigonometric.hpp" #include "./core/func_exponential.hpp" #include "./core/func_common.hpp" #include "./core/func_packing.hpp" #include "./core/func_geometric.hpp" #include "./core/func_matrix.hpp" #include "./core/func_vector_relational.hpp" #include "./core/func_integer.hpp" #include "./core/func_noise.hpp" #include "./core/_swizzle.hpp" #if(defined(GLM_MESSAGE) && (GLM_MESSAGE & (GLM_MESSAGE_CORE | GLM_MESSAGE_NOTIFICATION))) # pragma message("GLM message: Core library included") #endif//GLM_MESSAGE #if(defined(GLM_COMPILER) && (GLM_COMPILER & GLM_COMPILER_VC)) # define GLM_DEPRECATED __declspec(deprecated) # define GLM_RESTRICT __restrict # define GLM_ALIGN(x) __declspec(align(x)) //# define aligned(x) __declspec(align(x)) struct #elif(defined(GLM_COMPILER) && (GLM_COMPILER & GLM_COMPILER_GCC)) # define GLM_DEPRECATED deprecated # define GLM_RESTRICT # define GLM_ALIGN(x) __attribute__(aligned(x)) #else # define GLM_DEPRECATED # define GLM_RESTRICT # define GLM_ALIGN(x) #endif//GLM_COMPILER //////////////////// // check type sizes GLM_STATIC_ASSERT(sizeof(glm::detail::int8) == 1, "int8 size isn't 1 byte on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::int16) == 2, "int16 size isn't 2 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::int32) == 4, "int32 size isn't 4 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::int64) == 8, "int64 size isn't 8 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::uint8) == 1, "uint8 size isn't 1 byte on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::uint16) == 2, "uint16 size isn't 2 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::uint32) == 4, "uint32 size isn't 4 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::uint64) == 8, "uint64 size isn't 8 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::float16) == 2, "float16 size isn't 2 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::float32) == 4, "float32 size isn't 4 bytes on this platform"); GLM_STATIC_ASSERT(sizeof(glm::detail::float64) == 8, "float64 size isn't 8 bytes on this platform"); #endif //glm_glm <|endoftext|>
<commit_before>/* This file is part of VROOM. Copyright (c) 2015-2022, Julien Coupey. All rights reserved (see LICENSE). */ #include "problems/cvrp/operators/intra_cross_exchange.h" namespace vroom { namespace cvrp { IntraCrossExchange::IntraCrossExchange(const Input& input, const utils::SolutionState& sol_state, RawRoute& s_raw_route, Index s_vehicle, Index s_rank, Index t_rank, bool check_s_reverse, bool check_t_reverse) : Operator(OperatorName::IntraCrossExchange, input, sol_state, s_raw_route, s_vehicle, s_rank, s_raw_route, s_vehicle, t_rank), _gain_upper_bound_computed(false), // Required for consistency in compute_gain if check_s_reverse or // check_t_reverse are false. _reversed_s_gain(NO_GAIN), _reversed_t_gain(NO_GAIN), reverse_s_edge(false), reverse_t_edge(false), check_s_reverse(check_s_reverse), check_t_reverse(check_t_reverse), s_normal_t_normal_is_valid(false), s_normal_t_reverse_is_valid(false), s_reverse_t_reverse_is_valid(false), s_reverse_t_normal_is_valid(false), _moved_jobs(t_rank - s_rank + 2), _first_rank(s_rank), _last_rank(t_rank + 2) { // Use s_rank as smallest rank for symmetry reasons. assert(s_rank + 2 < t_rank); // Avoid common edge. assert(s_route.size() >= 5); assert(t_rank < s_route.size() - 1); // Either moving edges of single jobs or whole shipments. assert((_input.jobs[this->s_route[s_rank]].type == JOB_TYPE::SINGLE and _input.jobs[this->s_route[s_rank + 1]].type == JOB_TYPE::SINGLE and check_s_reverse) or (_input.jobs[this->s_route[s_rank]].type == JOB_TYPE::PICKUP and _input.jobs[this->s_route[s_rank + 1]].type == JOB_TYPE::DELIVERY and !check_s_reverse and _sol_state.matching_delivery_rank[s_vehicle][s_rank] == s_rank + 1)); assert((_input.jobs[this->t_route[t_rank]].type == JOB_TYPE::SINGLE and _input.jobs[this->t_route[t_rank + 1]].type == JOB_TYPE::SINGLE and check_t_reverse) or (_input.jobs[this->t_route[t_rank]].type == JOB_TYPE::PICKUP and _input.jobs[this->t_route[t_rank + 1]].type == JOB_TYPE::DELIVERY and !check_t_reverse and _sol_state.matching_delivery_rank[t_vehicle][t_rank] == t_rank + 1)); _moved_jobs[0] = s_route[t_rank]; _moved_jobs[1] = s_route[t_rank + 1]; std::copy(s_route.begin() + s_rank + 2, s_route.begin() + t_rank, _moved_jobs.begin() + 2); _moved_jobs[_moved_jobs.size() - 2] = s_route[s_rank]; _moved_jobs[_moved_jobs.size() - 1] = s_route[s_rank + 1]; } Eval IntraCrossExchange::gain_upper_bound() { const auto& v = _input.vehicles[s_vehicle]; // Consider the cost of replacing edge starting at rank s_rank with // target edge. Part of that cost (for adjacent edges) is stored in // _sol_state.edge_evals_around_edge. reverse_* checks whether we // should change the target edge order. Index s_index = _input.jobs[s_route[s_rank]].index(); Index s_after_index = _input.jobs[s_route[s_rank + 1]].index(); Index t_index = _input.jobs[s_route[t_rank]].index(); Index t_after_index = _input.jobs[s_route[t_rank + 1]].index(); // Determine costs added with target edge. Eval previous_cost; Eval next_cost; Eval reverse_previous_cost; Eval reverse_next_cost; if (s_rank == 0) { if (v.has_start()) { auto p_index = v.start.value().index(); previous_cost = v.eval(p_index, t_index); reverse_previous_cost = v.eval(p_index, t_after_index); } } else { auto p_index = _input.jobs[s_route[s_rank - 1]].index(); previous_cost = v.eval(p_index, t_index); reverse_previous_cost = v.eval(p_index, t_after_index); } auto n_index = _input.jobs[s_route[s_rank + 2]].index(); next_cost = v.eval(t_after_index, n_index); reverse_next_cost = v.eval(t_index, n_index); _normal_s_gain = _sol_state.edge_evals_around_edge[s_vehicle][s_rank] - previous_cost - next_cost; auto s_gain_upper_bound = _normal_s_gain; if (check_t_reverse) { const auto reverse_edge_cost = v.eval(t_index, t_after_index) - v.eval(t_after_index, t_index); _reversed_s_gain = _sol_state.edge_evals_around_edge[s_vehicle][s_rank] + reverse_edge_cost - reverse_previous_cost - reverse_next_cost; s_gain_upper_bound = std::max(_normal_s_gain, _reversed_s_gain); } // Consider the cost of replacing edge starting at rank t_rank with // source edge. Part of that cost (for adjacent edges) is stored in // _sol_state.edge_evals_around_edge. reverse_* checks whether we // should change the source edge order. next_cost = Eval(); reverse_previous_cost = Eval(); reverse_next_cost = Eval(); auto p_index = _input.jobs[s_route[t_rank - 1]].index(); previous_cost = v.eval(p_index, s_index); reverse_previous_cost = v.eval(p_index, s_after_index); if (t_rank == s_route.size() - 2) { if (v.has_end()) { auto n_index = v.end.value().index(); next_cost = v.eval(s_after_index, n_index); reverse_next_cost = v.eval(s_index, n_index); } } else { auto n_index = _input.jobs[s_route[t_rank + 2]].index(); next_cost = v.eval(s_after_index, n_index); reverse_next_cost = v.eval(s_index, n_index); } _normal_t_gain = _sol_state.edge_evals_around_edge[t_vehicle][t_rank] - previous_cost - next_cost; auto t_gain_upper_bound = _normal_t_gain; if (check_s_reverse) { const auto reverse_edge_cost = v.eval(s_index, s_after_index) - v.eval(s_after_index, s_index); _reversed_t_gain = _sol_state.edge_evals_around_edge[t_vehicle][t_rank] + reverse_edge_cost - reverse_previous_cost - reverse_next_cost; t_gain_upper_bound = std::max(_normal_t_gain, _reversed_t_gain); } _gain_upper_bound_computed = true; return s_gain_upper_bound + t_gain_upper_bound; } void IntraCrossExchange::compute_gain() { assert(_gain_upper_bound_computed); assert(s_normal_t_normal_is_valid or s_normal_t_reverse_is_valid or s_reverse_t_reverse_is_valid or s_reverse_t_normal_is_valid); stored_gain = NO_GAIN; if (s_normal_t_normal_is_valid) { const auto current_gain = _normal_s_gain + _normal_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = false; reverse_t_edge = false; } } if (s_normal_t_reverse_is_valid) { const auto current_gain = _reversed_s_gain + _normal_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = false; reverse_t_edge = true; } } if (s_reverse_t_reverse_is_valid) { const auto current_gain = _reversed_s_gain + _reversed_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = true; reverse_t_edge = true; } } if (s_reverse_t_normal_is_valid) { const auto current_gain = _normal_s_gain + _reversed_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = true; reverse_t_edge = false; } } gain_computed = true; } bool IntraCrossExchange::is_valid() { assert(_gain_upper_bound_computed); const auto delivery = source.delivery_in_range(_first_rank, _last_rank); const auto& s_v = _input.vehicles[s_vehicle]; const auto s_travel_time = _sol_state.route_evals[s_vehicle].duration; const auto s_normal_t_normal_duration = _normal_s_gain.duration + _normal_t_gain.duration; s_normal_t_normal_is_valid = (s_travel_time <= s_v.max_travel_time + s_normal_t_normal_duration) and source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); const auto s_normal_t_reverse_duration = _reversed_s_gain.duration + _normal_t_gain.duration; if (s_travel_time <= s_v.max_travel_time + s_normal_t_reverse_duration) { std::swap(_moved_jobs[0], _moved_jobs[1]); if (check_t_reverse) { s_normal_t_reverse_is_valid = source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } std::swap(_moved_jobs[_moved_jobs.size() - 2], _moved_jobs[_moved_jobs.size() - 1]); } if (check_s_reverse and check_t_reverse) { const auto s_reversed_t_reversed_duration = _reversed_s_gain.duration + _reversed_t_gain.duration; s_reverse_t_reverse_is_valid = (s_travel_time <= s_v.max_travel_time + s_reversed_t_reversed_duration) and source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } const auto s_reverse_t_normal_duration = _normal_s_gain.duration + _reversed_t_gain.duration; if (s_travel_time <= s_v.max_travel_time + s_reverse_t_normal_duration) { std::swap(_moved_jobs[0], _moved_jobs[1]); if (check_s_reverse) { s_reverse_t_normal_is_valid = source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } // Reset to initial situation before potential application and TW // checks. std::swap(_moved_jobs[_moved_jobs.size() - 2], _moved_jobs[_moved_jobs.size() - 1]); } return s_normal_t_normal_is_valid or s_normal_t_reverse_is_valid or s_reverse_t_reverse_is_valid or s_reverse_t_normal_is_valid; } void IntraCrossExchange::apply() { assert(!reverse_s_edge or (_input.jobs[s_route[s_rank]].type == JOB_TYPE::SINGLE and _input.jobs[s_route[s_rank + 1]].type == JOB_TYPE::SINGLE)); assert(!reverse_t_edge or (_input.jobs[t_route[t_rank]].type == JOB_TYPE::SINGLE and _input.jobs[t_route[t_rank + 1]].type == JOB_TYPE::SINGLE)); std::swap(s_route[s_rank], s_route[t_rank]); std::swap(s_route[s_rank + 1], s_route[t_rank + 1]); if (reverse_s_edge) { std::swap(s_route[t_rank], s_route[t_rank + 1]); } if (reverse_t_edge) { std::swap(s_route[s_rank], s_route[s_rank + 1]); } source.update_amounts(_input); } std::vector<Index> IntraCrossExchange::addition_candidates() const { return {}; } std::vector<Index> IntraCrossExchange::update_candidates() const { return {s_vehicle}; } } // namespace cvrp } // namespace vroom <commit_msg>Fix missing swaps in IntraCrossExchange::is_valid.<commit_after>/* This file is part of VROOM. Copyright (c) 2015-2022, Julien Coupey. All rights reserved (see LICENSE). */ #include "problems/cvrp/operators/intra_cross_exchange.h" namespace vroom { namespace cvrp { IntraCrossExchange::IntraCrossExchange(const Input& input, const utils::SolutionState& sol_state, RawRoute& s_raw_route, Index s_vehicle, Index s_rank, Index t_rank, bool check_s_reverse, bool check_t_reverse) : Operator(OperatorName::IntraCrossExchange, input, sol_state, s_raw_route, s_vehicle, s_rank, s_raw_route, s_vehicle, t_rank), _gain_upper_bound_computed(false), // Required for consistency in compute_gain if check_s_reverse or // check_t_reverse are false. _reversed_s_gain(NO_GAIN), _reversed_t_gain(NO_GAIN), reverse_s_edge(false), reverse_t_edge(false), check_s_reverse(check_s_reverse), check_t_reverse(check_t_reverse), s_normal_t_normal_is_valid(false), s_normal_t_reverse_is_valid(false), s_reverse_t_reverse_is_valid(false), s_reverse_t_normal_is_valid(false), _moved_jobs(t_rank - s_rank + 2), _first_rank(s_rank), _last_rank(t_rank + 2) { // Use s_rank as smallest rank for symmetry reasons. assert(s_rank + 2 < t_rank); // Avoid common edge. assert(s_route.size() >= 5); assert(t_rank < s_route.size() - 1); // Either moving edges of single jobs or whole shipments. assert((_input.jobs[this->s_route[s_rank]].type == JOB_TYPE::SINGLE and _input.jobs[this->s_route[s_rank + 1]].type == JOB_TYPE::SINGLE and check_s_reverse) or (_input.jobs[this->s_route[s_rank]].type == JOB_TYPE::PICKUP and _input.jobs[this->s_route[s_rank + 1]].type == JOB_TYPE::DELIVERY and !check_s_reverse and _sol_state.matching_delivery_rank[s_vehicle][s_rank] == s_rank + 1)); assert((_input.jobs[this->t_route[t_rank]].type == JOB_TYPE::SINGLE and _input.jobs[this->t_route[t_rank + 1]].type == JOB_TYPE::SINGLE and check_t_reverse) or (_input.jobs[this->t_route[t_rank]].type == JOB_TYPE::PICKUP and _input.jobs[this->t_route[t_rank + 1]].type == JOB_TYPE::DELIVERY and !check_t_reverse and _sol_state.matching_delivery_rank[t_vehicle][t_rank] == t_rank + 1)); _moved_jobs[0] = s_route[t_rank]; _moved_jobs[1] = s_route[t_rank + 1]; std::copy(s_route.begin() + s_rank + 2, s_route.begin() + t_rank, _moved_jobs.begin() + 2); _moved_jobs[_moved_jobs.size() - 2] = s_route[s_rank]; _moved_jobs[_moved_jobs.size() - 1] = s_route[s_rank + 1]; } Eval IntraCrossExchange::gain_upper_bound() { const auto& v = _input.vehicles[s_vehicle]; // Consider the cost of replacing edge starting at rank s_rank with // target edge. Part of that cost (for adjacent edges) is stored in // _sol_state.edge_evals_around_edge. reverse_* checks whether we // should change the target edge order. Index s_index = _input.jobs[s_route[s_rank]].index(); Index s_after_index = _input.jobs[s_route[s_rank + 1]].index(); Index t_index = _input.jobs[s_route[t_rank]].index(); Index t_after_index = _input.jobs[s_route[t_rank + 1]].index(); // Determine costs added with target edge. Eval previous_cost; Eval next_cost; Eval reverse_previous_cost; Eval reverse_next_cost; if (s_rank == 0) { if (v.has_start()) { auto p_index = v.start.value().index(); previous_cost = v.eval(p_index, t_index); reverse_previous_cost = v.eval(p_index, t_after_index); } } else { auto p_index = _input.jobs[s_route[s_rank - 1]].index(); previous_cost = v.eval(p_index, t_index); reverse_previous_cost = v.eval(p_index, t_after_index); } auto n_index = _input.jobs[s_route[s_rank + 2]].index(); next_cost = v.eval(t_after_index, n_index); reverse_next_cost = v.eval(t_index, n_index); _normal_s_gain = _sol_state.edge_evals_around_edge[s_vehicle][s_rank] - previous_cost - next_cost; auto s_gain_upper_bound = _normal_s_gain; if (check_t_reverse) { const auto reverse_edge_cost = v.eval(t_index, t_after_index) - v.eval(t_after_index, t_index); _reversed_s_gain = _sol_state.edge_evals_around_edge[s_vehicle][s_rank] + reverse_edge_cost - reverse_previous_cost - reverse_next_cost; s_gain_upper_bound = std::max(_normal_s_gain, _reversed_s_gain); } // Consider the cost of replacing edge starting at rank t_rank with // source edge. Part of that cost (for adjacent edges) is stored in // _sol_state.edge_evals_around_edge. reverse_* checks whether we // should change the source edge order. next_cost = Eval(); reverse_previous_cost = Eval(); reverse_next_cost = Eval(); auto p_index = _input.jobs[s_route[t_rank - 1]].index(); previous_cost = v.eval(p_index, s_index); reverse_previous_cost = v.eval(p_index, s_after_index); if (t_rank == s_route.size() - 2) { if (v.has_end()) { auto n_index = v.end.value().index(); next_cost = v.eval(s_after_index, n_index); reverse_next_cost = v.eval(s_index, n_index); } } else { auto n_index = _input.jobs[s_route[t_rank + 2]].index(); next_cost = v.eval(s_after_index, n_index); reverse_next_cost = v.eval(s_index, n_index); } _normal_t_gain = _sol_state.edge_evals_around_edge[t_vehicle][t_rank] - previous_cost - next_cost; auto t_gain_upper_bound = _normal_t_gain; if (check_s_reverse) { const auto reverse_edge_cost = v.eval(s_index, s_after_index) - v.eval(s_after_index, s_index); _reversed_t_gain = _sol_state.edge_evals_around_edge[t_vehicle][t_rank] + reverse_edge_cost - reverse_previous_cost - reverse_next_cost; t_gain_upper_bound = std::max(_normal_t_gain, _reversed_t_gain); } _gain_upper_bound_computed = true; return s_gain_upper_bound + t_gain_upper_bound; } void IntraCrossExchange::compute_gain() { assert(_gain_upper_bound_computed); assert(s_normal_t_normal_is_valid or s_normal_t_reverse_is_valid or s_reverse_t_reverse_is_valid or s_reverse_t_normal_is_valid); stored_gain = NO_GAIN; if (s_normal_t_normal_is_valid) { const auto current_gain = _normal_s_gain + _normal_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = false; reverse_t_edge = false; } } if (s_normal_t_reverse_is_valid) { const auto current_gain = _reversed_s_gain + _normal_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = false; reverse_t_edge = true; } } if (s_reverse_t_reverse_is_valid) { const auto current_gain = _reversed_s_gain + _reversed_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = true; reverse_t_edge = true; } } if (s_reverse_t_normal_is_valid) { const auto current_gain = _normal_s_gain + _reversed_t_gain; if (current_gain > stored_gain) { stored_gain = current_gain; reverse_s_edge = true; reverse_t_edge = false; } } gain_computed = true; } bool IntraCrossExchange::is_valid() { assert(_gain_upper_bound_computed); const auto delivery = source.delivery_in_range(_first_rank, _last_rank); const auto& s_v = _input.vehicles[s_vehicle]; const auto s_travel_time = _sol_state.route_evals[s_vehicle].duration; const auto s_normal_t_normal_duration = _normal_s_gain.duration + _normal_t_gain.duration; s_normal_t_normal_is_valid = (s_travel_time <= s_v.max_travel_time + s_normal_t_normal_duration) and source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); std::swap(_moved_jobs[0], _moved_jobs[1]); if (check_t_reverse) { const auto s_normal_t_reverse_duration = _reversed_s_gain.duration + _normal_t_gain.duration; s_normal_t_reverse_is_valid = (s_travel_time <= s_v.max_travel_time + s_normal_t_reverse_duration) && source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } std::swap(_moved_jobs[_moved_jobs.size() - 2], _moved_jobs[_moved_jobs.size() - 1]); if (check_s_reverse and check_t_reverse) { const auto s_reversed_t_reversed_duration = _reversed_s_gain.duration + _reversed_t_gain.duration; s_reverse_t_reverse_is_valid = (s_travel_time <= s_v.max_travel_time + s_reversed_t_reversed_duration) and source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } std::swap(_moved_jobs[0], _moved_jobs[1]); if (check_s_reverse) { const auto s_reverse_t_normal_duration = _normal_s_gain.duration + _reversed_t_gain.duration; s_reverse_t_normal_is_valid = (s_travel_time <= s_v.max_travel_time + s_reverse_t_normal_duration) && source.is_valid_addition_for_capacity_inclusion(_input, delivery, _moved_jobs.begin(), _moved_jobs.end(), _first_rank, _last_rank); } // Reset to initial situation before potential application and TW // checks. std::swap(_moved_jobs[_moved_jobs.size() - 2], _moved_jobs[_moved_jobs.size() - 1]); return s_normal_t_normal_is_valid or s_normal_t_reverse_is_valid or s_reverse_t_reverse_is_valid or s_reverse_t_normal_is_valid; } void IntraCrossExchange::apply() { assert(!reverse_s_edge or (_input.jobs[s_route[s_rank]].type == JOB_TYPE::SINGLE and _input.jobs[s_route[s_rank + 1]].type == JOB_TYPE::SINGLE)); assert(!reverse_t_edge or (_input.jobs[t_route[t_rank]].type == JOB_TYPE::SINGLE and _input.jobs[t_route[t_rank + 1]].type == JOB_TYPE::SINGLE)); std::swap(s_route[s_rank], s_route[t_rank]); std::swap(s_route[s_rank + 1], s_route[t_rank + 1]); if (reverse_s_edge) { std::swap(s_route[t_rank], s_route[t_rank + 1]); } if (reverse_t_edge) { std::swap(s_route[s_rank], s_route[s_rank + 1]); } source.update_amounts(_input); } std::vector<Index> IntraCrossExchange::addition_candidates() const { return {}; } std::vector<Index> IntraCrossExchange::update_candidates() const { return {s_vehicle}; } } // namespace cvrp } // namespace vroom <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <fnord-base/io/file.h> #include <fnord-base/io/fileutil.h> #include <fnord-base/io/mmappedfile.h> #include <fnord-base/logging.h> #include <fnord-base/io/fileutil.h> #include <fnord-dproc/LocalScheduler.h> namespace fnord { namespace dproc { LocalScheduler::LocalScheduler( const String& tempdir /* = "/tmp" */, size_t max_threads /* = 8 */, size_t max_requests /* = 32 */) : tempdir_(tempdir), tpool_(max_threads), req_tpool_(max_requests) {} void LocalScheduler::start() { req_tpool_.start(); tpool_.start(); } void LocalScheduler::stop() { req_tpool_.stop(); tpool_.stop(); } RefPtr<TaskResult> LocalScheduler::run( RefPtr<Application> app, const TaskSpec& task) { RefPtr<TaskResult> result(new TaskResult()); try { auto instance = mkRef( new LocalTaskRef( app, task.task_name(), Buffer(task.params().data(), task.params().size()))); req_tpool_.run([this, app, result, instance] () { try { LocalTaskPipeline pipeline; pipeline.tasks.push_back(instance); run(app.get(), &pipeline); result->returnResult( new io::MmappedFile( File::openFile(instance->output_filename, File::O_READ))); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } }); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } return result; } void LocalScheduler::run( Application* app, LocalTaskPipeline* pipeline) { fnord::logInfo( "fnord.dproc", "Starting local pipeline id=$0 tasks=$1", (void*) pipeline, pipeline->tasks.size()); std::unique_lock<std::mutex> lk(pipeline->mutex); while (pipeline->tasks.size() > 0) { bool waiting = true; size_t num_waiting = 0; size_t num_running = 0; size_t num_completed = 0; for (auto& taskref : pipeline->tasks) { if (taskref->finished) { ++num_completed; continue; } if (taskref->running) { ++num_running; continue; } if (!taskref->expanded) { taskref->expanded = true; auto parent_task = taskref; for (const auto& dep : taskref->task->dependencies()) { RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params)); parent_task->dependencies.emplace_back(depref); pipeline->tasks.emplace_back(depref); } waiting = false; break; } bool deps_finished = true; for (const auto& dep : taskref->dependencies) { if (!dep->finished) { deps_finished = false; } } if (!deps_finished) { ++num_waiting; continue; } taskref->running = true; tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref)); waiting = false; } fnord::logInfo( "fnord.dproc", "Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4", (void*) pipeline, pipeline->tasks.size(), num_running, num_waiting, num_completed); if (waiting) { pipeline->wakeup.wait(lk); } while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) { pipeline->tasks.pop_back(); } } fnord::logInfo( "fnord.dproc", "Completed local pipeline id=$0", (void*) pipeline); } void LocalScheduler::runTask( LocalTaskPipeline* pipeline, RefPtr<LocalTaskRef> task) { auto cache_key = task->task->cacheKey(); String output_file; if (cache_key.isEmpty()) { auto tmpid = Random::singleton()->hex128(); output_file = FileUtil::joinPaths( tempdir_, StringUtil::format("tmp_$0", tmpid)); } else { output_file = FileUtil::joinPaths( tempdir_, StringUtil::format("cache_$0", cache_key.get())); } auto cached = !cache_key.isEmpty() && FileUtil::exists(output_file); fnord::logDebug( "fnord.dproc", "Running task: $0 (cached=$1)", task->debug_name, cached); if (!cached) { try { auto res = task->task->run(task.get()); auto file = File::openFile( output_file + "~", File::O_CREATEOROPEN | File::O_WRITE); file.write(res->data(), res->size()); FileUtil::mv(output_file + "~", output_file); } catch (const std::exception& e) { fnord::logError("fnord.dproc", e, "error"); } } std::unique_lock<std::mutex> lk(pipeline->mutex); task->output_filename = output_file; task->finished = true; lk.unlock(); pipeline->wakeup.notify_all(); } LocalScheduler::LocalTaskRef::LocalTaskRef( RefPtr<Application> app, const String& task_name, const Buffer& params) : task(app->getTaskInstance(task_name, params)), debug_name(StringUtil::format("$0#$1", app->name(), task_name)), running(false), expanded(false), finished(false) {} RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) { if (index >= dependencies.size()) { RAISEF(kIndexError, "invalid dependecy index: $0", index); } const auto& dep = dependencies[index]; if (!FileUtil::exists(dep->output_filename)) { RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename); } return RefPtr<VFSFile>( new io::MmappedFile( File::openFile(dep->output_filename, File::O_READ))); } size_t LocalScheduler::LocalTaskRef::numDependencies() const { return dependencies.size(); } } // namespace dproc } // namespace fnord <commit_msg>check cache before expanding deps<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <unistd.h> #include <fnord-base/io/file.h> #include <fnord-base/io/fileutil.h> #include <fnord-base/io/mmappedfile.h> #include <fnord-base/logging.h> #include <fnord-base/io/fileutil.h> #include <fnord-dproc/LocalScheduler.h> namespace fnord { namespace dproc { LocalScheduler::LocalScheduler( const String& tempdir /* = "/tmp" */, size_t max_threads /* = 8 */, size_t max_requests /* = 32 */) : tempdir_(tempdir), tpool_(max_threads), req_tpool_(max_requests) {} void LocalScheduler::start() { req_tpool_.start(); tpool_.start(); } void LocalScheduler::stop() { req_tpool_.stop(); tpool_.stop(); } RefPtr<TaskResult> LocalScheduler::run( RefPtr<Application> app, const TaskSpec& task) { RefPtr<TaskResult> result(new TaskResult()); try { auto instance = mkRef( new LocalTaskRef( app, task.task_name(), Buffer(task.params().data(), task.params().size()))); req_tpool_.run([this, app, result, instance] () { try { LocalTaskPipeline pipeline; pipeline.tasks.push_back(instance); run(app.get(), &pipeline); result->returnResult( new io::MmappedFile( File::openFile(instance->output_filename, File::O_READ))); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } }); } catch (const StandardException& e) { fnord::logError("dproc.scheduler", e, "task failed"); result->returnError(e); } return result; } void LocalScheduler::run( Application* app, LocalTaskPipeline* pipeline) { fnord::logInfo( "fnord.dproc", "Starting local pipeline id=$0 tasks=$1", (void*) pipeline, pipeline->tasks.size()); std::unique_lock<std::mutex> lk(pipeline->mutex); while (pipeline->tasks.size() > 0) { bool waiting = true; size_t num_waiting = 0; size_t num_running = 0; size_t num_completed = 0; for (auto& taskref : pipeline->tasks) { if (taskref->finished) { ++num_completed; continue; } if (taskref->running) { ++num_running; continue; } if (!taskref->expanded) { taskref->expanded = true; auto cache_key = taskref->task->cacheKey(); if (cache_key.isEmpty()) { auto tmpid = Random::singleton()->hex128(); taskref->output_filename = FileUtil::joinPaths( tempdir_, StringUtil::format("tmp_$0", tmpid)); } else { taskref->output_filename = FileUtil::joinPaths( tempdir_, StringUtil::format("cache_$0", cache_key.get())); } auto cached = !cache_key.isEmpty() && FileUtil::exists(taskref->output_filename); if (cached) { fnord::logDebug( "fnord.dproc", "Running task [cached]: $0", taskref->debug_name); taskref->finished = true; continue; } auto parent_task = taskref; for (const auto& dep : taskref->task->dependencies()) { RefPtr<LocalTaskRef> depref(new LocalTaskRef(app, dep.task_name, dep.params)); parent_task->dependencies.emplace_back(depref); pipeline->tasks.emplace_back(depref); } waiting = false; break; } bool deps_finished = true; for (const auto& dep : taskref->dependencies) { if (!dep->finished) { deps_finished = false; } } if (!deps_finished) { ++num_waiting; continue; } fnord::logDebug("fnord.dproc", "Running task: $0", taskref->debug_name); taskref->running = true; tpool_.run(std::bind(&LocalScheduler::runTask, this, pipeline, taskref)); waiting = false; } fnord::logInfo( "fnord.dproc", "Running local pipeline... id=$0 tasks=$1, running=$2, waiting=$3, completed=$4", (void*) pipeline, pipeline->tasks.size(), num_running, num_waiting, num_completed); if (waiting) { pipeline->wakeup.wait(lk); } while (pipeline->tasks.size() > 0 && pipeline->tasks.back()->finished) { pipeline->tasks.pop_back(); } } fnord::logInfo( "fnord.dproc", "Completed local pipeline id=$0", (void*) pipeline); } void LocalScheduler::runTask( LocalTaskPipeline* pipeline, RefPtr<LocalTaskRef> task) { auto output_file = task->output_filename; try { auto res = task->task->run(task.get()); auto file = File::openFile( output_file + "~", File::O_CREATEOROPEN | File::O_WRITE); file.write(res->data(), res->size()); FileUtil::mv(output_file + "~", output_file); } catch (const std::exception& e) { fnord::logError("fnord.dproc", e, "error"); } std::unique_lock<std::mutex> lk(pipeline->mutex); task->finished = true; lk.unlock(); pipeline->wakeup.notify_all(); } LocalScheduler::LocalTaskRef::LocalTaskRef( RefPtr<Application> app, const String& task_name, const Buffer& params) : task(app->getTaskInstance(task_name, params)), debug_name(StringUtil::format("$0#$1", app->name(), task_name)), running(false), expanded(false), finished(false) {} RefPtr<VFSFile> LocalScheduler::LocalTaskRef::getDependency(size_t index) { if (index >= dependencies.size()) { RAISEF(kIndexError, "invalid dependecy index: $0", index); } const auto& dep = dependencies[index]; if (!FileUtil::exists(dep->output_filename)) { RAISEF(kRuntimeError, "missing upstream output: $0", dep->output_filename); } return RefPtr<VFSFile>( new io::MmappedFile( File::openFile(dep->output_filename, File::O_READ))); } size_t LocalScheduler::LocalTaskRef::numDependencies() const { return dependencies.size(); } } // namespace dproc } // namespace fnord <|endoftext|>
<commit_before>/* * Copyright (C) 2017 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. */ #include "host/commands/wifirouter/router.h" #include <cerrno> #include <cstddef> #include <map> #include <memory> #include <set> #include <gflags/gflags.h> #include <glog/logging.h> #include <netlink/genl/ctrl.h> #include <netlink/genl/family.h> #include <netlink/genl/genl.h> #include <netlink/netlink.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> DEFINE_string(socket_name, "cvd-wifirouter", "Name of the unix-domain socket providing access for routing. " "Socket will be created in abstract namespace."); namespace cvd { namespace { using MacHash = uint64_t; using MacToClientsTable = std::multimap<MacHash, int>; using ClientsTable = std::set<int>; // Copied out of mac80211_hwsim.h header. constexpr int HWSIM_CMD_REGISTER = 1; constexpr int HWSIM_ATTR_ADDR_TRANSMITTER = 2; constexpr int HWSIM_ATTR_MAX = 19; // Name of the WIFI SIM Netlink Family. constexpr char kWifiSimFamilyName[] = "MAC80211_HWSIM"; const int kMaxSupportedPacketSize = getpagesize(); // Get hash for mac address serialized to 6 bytes of data starting at specified // location. // We don't care about byte ordering as much as we do about having all bytes // there. Byte order does not matter, we want to use it as a key in our map. uint64_t GetMacHash(const void* macaddr) { auto typed = reinterpret_cast<const uint16_t*>(macaddr); return (1ull * typed[0] << 32) | (typed[1] << 16) | typed[2]; } // Enable asynchronous notifications from MAC80211_HWSIM. // - `sock` is a valid netlink socket connected to NETLINK_GENERIC, // - `family` is MAC80211_HWSIM genl family number. // // Upon failure, this function will terminate execution of the program. void RegisterForHWSimNotifications(nl_sock* sock, int family) { std::unique_ptr<nl_msg, void (*)(nl_msg*)> msg( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(msg.get(), NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, HWSIM_CMD_REGISTER, 0); nl_send_auto(sock, msg.get()); auto res = nl_wait_for_ack(sock); if (res < 0) { LOG(ERROR) << "Could not register for notifications: " << nl_geterror(res); exit(1); } } // Create and configure WIFI Router server socket. // This function is guaranteed to success. If at any point an error is detected, // the function will terminate execution of the program. int CreateWifiRouterServerSocket() { auto fd = socket(AF_UNIX, SOCK_SEQPACKET, 0); if (fd <= 0) { LOG(ERROR) << "Could not create unix socket: " << strerror(-fd); exit(1); } sockaddr_un addr{}; addr.sun_family = AF_UNIX; auto len = std::min(sizeof(addr.sun_path) - 2, FLAGS_socket_name.size()); strncpy(&addr.sun_path[1], FLAGS_socket_name.c_str(), len); len += offsetof(sockaddr_un, sun_path) + 1; // include heading \0 byte. auto res = bind(fd, reinterpret_cast<sockaddr*>(&addr), len); if (res < 0) { LOG(ERROR) << "Could not bind unix socket: " << strerror(-res); exit(1); } listen(fd, 4); return fd; } // Accept new WIFI Router client. When successful, client will be placed in // clients table. void AcceptNewClient(int server_fd, ClientsTable* clients) { auto client = accept(server_fd, nullptr, nullptr); if (client < 0) { LOG(ERROR) << "Could not accept client: " << strerror(errno); return; } clients->insert(client); LOG(INFO) << "Client " << client << " added."; } // Disconnect and remove client from list of registered clients and recipients // of WLAN traffic. void RemoveClient(int client, ClientsTable* clients, MacToClientsTable* targets) { close(client); clients->erase(client); for (auto iter = targets->begin(); iter != targets->end();) { if (iter->second == client) { iter = targets->erase(iter); } else { ++iter; } } LOG(INFO) << "Client " << client << " removed."; } // Read MAC80211HWSIM packet, find the originating MAC address and redirect it // to proper sink. void RouteWIFIPacket(nl_sock* nl, int simfamily, ClientsTable* clients, MacToClientsTable* targets) { sockaddr_nl tmp; uint8_t* buf; const auto len = nl_recv(nl, &tmp, &buf, nullptr); if (len < 0) { LOG(ERROR) << "Could not read from netlink: " << nl_geterror(len); return; } std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(buf), [](nlmsghdr* m) { free(m); }); // Discard messages that originate from anything else than MAC80211_HWSIM. if (msg->nlmsg_type != simfamily) return; std::unique_ptr<nl_msg, void (*)(nl_msg*)> rep( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(rep.get(), 0, 0, 0, 0, 0, WIFIROUTER_CMD_NOTIFY, 0); // Note, this is generic netlink message, and uses different parsing // technique. nlattr* attrs[HWSIM_ATTR_MAX + 1]; if (genlmsg_parse(msg.get(), 0, attrs, HWSIM_ATTR_MAX, nullptr)) return; std::set<int> pending_removals; auto addr = attrs[HWSIM_ATTR_ADDR_TRANSMITTER]; if (addr != nullptr) { nla_put(rep.get(), WIFIROUTER_ATTR_MAC, nla_len(addr), nla_data(addr)); nla_put(rep.get(), WIFIROUTER_ATTR_PACKET, len, buf); auto hdr = nlmsg_hdr(rep.get()); auto key = GetMacHash(nla_data(attrs[HWSIM_ATTR_ADDR_TRANSMITTER])); LOG(INFO) << "Received netlink packet from " << std::hex << key; for (auto it = targets->find(key); it != targets->end() && it->first == key; ++it) { auto num_written = send(it->second, hdr, hdr->nlmsg_len, MSG_NOSIGNAL); if (num_written != static_cast<int64_t>(hdr->nlmsg_len)) { pending_removals.insert(it->second); } } for (auto client : pending_removals) { RemoveClient(client, clients, targets); } } } bool HandleClientMessage(int client, MacToClientsTable* targets) { std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(malloc(kMaxSupportedPacketSize)), [](nlmsghdr* h) { free(h); }); int64_t size = recv(client, msg.get(), kMaxSupportedPacketSize, 0); // Invalid message or no data -> client invalid or disconnected. if (size == 0 || size != msg->nlmsg_len || size < sizeof(nlmsghdr)) { return false; } int result = -EINVAL; genlmsghdr* ghdr = reinterpret_cast<genlmsghdr*>(nlmsg_data(msg.get())); switch (ghdr->cmd) { case WIFIROUTER_CMD_REGISTER: // Register client to receive notifications for specified MAC address. nlattr* attrs[WIFIROUTER_ATTR_MAX]; if (!nlmsg_parse(msg.get(), sizeof(genlmsghdr), attrs, WIFIROUTER_ATTR_MAX - 1, nullptr)) { if (attrs[WIFIROUTER_ATTR_MAC] != nullptr) { targets->emplace(GetMacHash(nla_data(attrs[WIFIROUTER_ATTR_MAC])), client); result = 0; } } break; default: break; } nlmsgerr err{.error = result}; std::unique_ptr<nl_msg, void (*)(nl_msg*)> rsp(nlmsg_alloc(), nlmsg_free); nlmsg_put(rsp.get(), msg->nlmsg_pid, msg->nlmsg_seq, NLMSG_ERROR, 0, 0); nlmsg_append(rsp.get(), &err, sizeof(err), 0); auto hdr = nlmsg_hdr(rsp.get()); if (send(client, hdr, hdr->nlmsg_len, MSG_NOSIGNAL) != static_cast<int64_t>(hdr->nlmsg_len)) { return false; } return true; } // Process incoming requests from netlink, server or clients. void ServerLoop(int server_fd, nl_sock* netlink_sock, int family) { ClientsTable clients; MacToClientsTable targets; int netlink_fd = nl_socket_get_fd(netlink_sock); while (true) { auto max_fd = server_fd; fd_set reads{}; auto fdset = [&max_fd, &reads](int fd) { FD_SET(fd, &reads); max_fd = std::max(max_fd, fd); }; fdset(server_fd); fdset(netlink_fd); for (int client : clients) fdset(client); if (select(max_fd + 1, &reads, nullptr, nullptr, nullptr) <= 0) continue; if (FD_ISSET(server_fd, &reads)) AcceptNewClient(server_fd, &clients); if (FD_ISSET(netlink_fd, &reads)) RouteWIFIPacket(netlink_sock, family, &clients, &targets); // Process any client messages left. Drop any client that is no longer // talking with us. for (auto client = clients.begin(); client != clients.end();) { auto cfd = *client++; // Is our client sending us data? if (FD_ISSET(cfd, &reads)) { if (!HandleClientMessage(cfd, &targets)) { // Client should be disconnected. RemoveClient(cfd, &clients, &targets); } } } } } } // namespace } // namespace cvd int main(int argc, char* argv[]) { using namespace cvd; google::ParseCommandLineFlags(&argc, &argv, true); #if !defined(ANDROID) // We should check for legitimate google logging here. google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); #endif std::unique_ptr<nl_sock, void (*)(nl_sock*)> sock(nl_socket_alloc(), nl_socket_free); auto res = nl_connect(sock.get(), NETLINK_GENERIC); if (res < 0) { LOG(ERROR) << "Could not connect to netlink generic: " << nl_geterror(res); exit(1); } auto mac80211_family = genl_ctrl_resolve(sock.get(), kWifiSimFamilyName); if (mac80211_family <= 0) { LOG(ERROR) << "Could not find MAC80211 HWSIM. Please make sure module " << "'mac80211_hwsim' is loaded on your system."; exit(1); } RegisterForHWSimNotifications(sock.get(), mac80211_family); auto server_fd = CreateWifiRouterServerSocket(); ServerLoop(server_fd, sock.get(), mac80211_family); } <commit_msg>Re-register for HWSIM notifications upon creation of wifi interface.<commit_after>/* * Copyright (C) 2017 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. */ #include "host/commands/wifirouter/router.h" #include <cerrno> #include <cstddef> #include <map> #include <memory> #include <set> #include <gflags/gflags.h> #include <glog/logging.h> #include <netlink/genl/ctrl.h> #include <netlink/genl/family.h> #include <netlink/genl/genl.h> #include <netlink/netlink.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> DEFINE_string(socket_name, "cvd-wifirouter", "Name of the unix-domain socket providing access for routing. " "Socket will be created in abstract namespace."); namespace cvd { namespace { using MacHash = uint64_t; using MacToClientsTable = std::multimap<MacHash, int>; using ClientsTable = std::set<int>; // Copied out of mac80211_hwsim.h header. constexpr int HWSIM_CMD_REGISTER = 1; constexpr int HWSIM_ATTR_ADDR_TRANSMITTER = 2; constexpr int HWSIM_ATTR_MAX = 19; // Name of the WIFI SIM Netlink Family. constexpr char kWifiSimFamilyName[] = "MAC80211_HWSIM"; const int kMaxSupportedPacketSize = getpagesize(); class WifiRouter { public: using MacHash = uint16_t; using MacToClientsTable = std::multimap<MacHash, int>; using ClientsTable = std::set<int>; WifiRouter() : sock_(nullptr, nl_socket_free) {} ~WifiRouter() = default; void Init(); void ServerLoop(); private: MacHash GetMacHash(const void* macaddr); void CreateWifiRouterServerSocket(); void RegisterForHWSimNotifications(); void RouteWIFIPacket(); void AcceptNewClient(); bool HandleClientMessage(int client); void RemoveClient(int client); std::unique_ptr<nl_sock, void(*)(nl_sock*)> sock_; int server_fd_ = 0; int mac80211_family_ = 0; ClientsTable registered_clients_; MacToClientsTable registered_addresses_; }; MacHash WifiRouter::GetMacHash(const void* macaddr) { const uint8_t* t = reinterpret_cast<const uint8_t*>(macaddr); // This is guaranteed to be unique. Address here is assigned at creation time // and is (well) non-mutable. This is a unique ID of the MAC80211 HWSIM // interface. return t[3] << 8 | t[4]; } void WifiRouter::Init() { CreateWifiRouterServerSocket(); RegisterForHWSimNotifications(); } // Enable asynchronous notifications from MAC80211_HWSIM. // - `sock` is a valid netlink socket connected to NETLINK_GENERIC, // - `family` is MAC80211_HWSIM genl family number. // // Upon failure, this function will terminate execution of the program. void WifiRouter::RegisterForHWSimNotifications() { sock_.reset(nl_socket_alloc()); auto res = nl_connect(sock_.get(), NETLINK_GENERIC); if (res < 0) { LOG(ERROR) << "Could not connect to netlink generic: " << nl_geterror(res); exit(1); } mac80211_family_ = genl_ctrl_resolve(sock_.get(), kWifiSimFamilyName); if (mac80211_family_ <= 0) { LOG(ERROR) << "Could not find MAC80211 HWSIM. Please make sure module " << "'mac80211_hwsim' is loaded on your system."; exit(1); } std::unique_ptr<nl_msg, void (*)(nl_msg*)> msg( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(msg.get(), NL_AUTO_PID, NL_AUTO_SEQ, mac80211_family_, 0, NLM_F_REQUEST, HWSIM_CMD_REGISTER, 0); nl_send_auto(sock_.get(), msg.get()); res = nl_wait_for_ack(sock_.get()); if (res < 0) { LOG(ERROR) << "Could not register for notifications: " << nl_geterror(res); exit(1); } } // Create and configure WIFI Router server socket. // This function is guaranteed to success. If at any point an error is detected, // the function will terminate execution of the program. void WifiRouter::CreateWifiRouterServerSocket() { server_fd_ = socket(AF_UNIX, SOCK_SEQPACKET, 0); if (server_fd_ < 0) { LOG(ERROR) << "Could not create unix socket: " << strerror(-errno); exit(1); } sockaddr_un addr{}; addr.sun_family = AF_UNIX; auto len = std::min(sizeof(addr.sun_path) - 2, FLAGS_socket_name.size()); strncpy(&addr.sun_path[1], FLAGS_socket_name.c_str(), len); len += offsetof(sockaddr_un, sun_path) + 1; // include heading \0 byte. auto res = bind(server_fd_, reinterpret_cast<sockaddr*>(&addr), len); if (res < 0) { LOG(ERROR) << "Could not bind unix socket: " << strerror(-errno); exit(1); } listen(server_fd_, 4); } // Accept new WIFI Router client. When successful, client will be placed in // clients table. void WifiRouter::AcceptNewClient() { auto client = accept(server_fd_, nullptr, nullptr); if (client < 0) { LOG(ERROR) << "Could not accept client: " << strerror(-errno); return; } registered_clients_.insert(client); LOG(INFO) << "Client " << client << " added."; } // Disconnect and remove client from list of registered clients and recipients // of WLAN traffic. void WifiRouter::RemoveClient(int client) { close(client); registered_clients_.erase(client); for (auto iter = registered_addresses_.begin(); iter != registered_addresses_.end();) { if (iter->second == client) { iter = registered_addresses_.erase(iter); } else { ++iter; } } LOG(INFO) << "Client " << client << " removed."; } // Read MAC80211HWSIM packet, find the originating MAC address and redirect it // to proper sink. void WifiRouter::RouteWIFIPacket() { sockaddr_nl tmp; uint8_t* buf; const auto len = nl_recv(sock_.get(), &tmp, &buf, nullptr); if (len < 0) { LOG(ERROR) << "Could not read from netlink: " << nl_geterror(len); return; } std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(buf), [](nlmsghdr* m) { free(m); }); // Discard messages that originate from anything else than MAC80211_HWSIM. if (msg->nlmsg_type != mac80211_family_) return; std::unique_ptr<nl_msg, void (*)(nl_msg*)> rep( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(rep.get(), 0, 0, 0, 0, 0, WIFIROUTER_CMD_NOTIFY, 0); // Note, this is generic netlink message, and uses different parsing // technique. nlattr* attrs[HWSIM_ATTR_MAX + 1]; if (genlmsg_parse(msg.get(), 0, attrs, HWSIM_ATTR_MAX, nullptr)) return; std::set<int> pending_removals; auto addr = attrs[HWSIM_ATTR_ADDR_TRANSMITTER]; if (addr != nullptr) { nla_put(rep.get(), WIFIROUTER_ATTR_MAC, nla_len(addr), nla_data(addr)); nla_put(rep.get(), WIFIROUTER_ATTR_PACKET, len, buf); auto hdr = nlmsg_hdr(rep.get()); auto key = GetMacHash(nla_data(attrs[HWSIM_ATTR_ADDR_TRANSMITTER])); LOG(INFO) << "Received netlink packet from " << std::hex << key; for (auto it = registered_addresses_.find(key); it != registered_addresses_.end() && it->first == key; ++it) { auto num_written = send(it->second, hdr, hdr->nlmsg_len, MSG_NOSIGNAL); if (num_written != static_cast<int64_t>(hdr->nlmsg_len)) { pending_removals.insert(it->second); } } for (auto client : pending_removals) RemoveClient(client); } } bool WifiRouter::HandleClientMessage(int client) { std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(malloc(kMaxSupportedPacketSize)), [](nlmsghdr* h) { free(h); }); int64_t size = recv(client, msg.get(), kMaxSupportedPacketSize, 0); // Invalid message or no data -> client invalid or disconnected. if (size == 0 || size != msg->nlmsg_len || size < sizeof(nlmsghdr)) { return false; } int result = -EINVAL; genlmsghdr* ghdr = reinterpret_cast<genlmsghdr*>(nlmsg_data(msg.get())); switch (ghdr->cmd) { case WIFIROUTER_CMD_REGISTER: // Register client to receive notifications for specified MAC address. nlattr* attrs[WIFIROUTER_ATTR_MAX]; if (!nlmsg_parse(msg.get(), sizeof(genlmsghdr), attrs, WIFIROUTER_ATTR_MAX - 1, nullptr)) { if (attrs[WIFIROUTER_ATTR_MAC] != nullptr) { LOG(INFO) << "Registering new client to receive data for " << GetMacHash(nla_data(attrs[WIFIROUTER_ATTR_MAC])); registered_addresses_.emplace( GetMacHash(nla_data(attrs[WIFIROUTER_ATTR_MAC])), client); // This is unfortunate, but it is a bug in mac80211_hwsim stack. // Apparently, the imperfect medium will not receive notifications for // newly created wifi interfaces. How about that... RegisterForHWSimNotifications(); result = 0; } } break; default: break; } nlmsgerr err{.error = result}; std::unique_ptr<nl_msg, void (*)(nl_msg*)> rsp(nlmsg_alloc(), nlmsg_free); nlmsg_put(rsp.get(), msg->nlmsg_pid, msg->nlmsg_seq, NLMSG_ERROR, 0, 0); nlmsg_append(rsp.get(), &err, sizeof(err), 0); auto hdr = nlmsg_hdr(rsp.get()); if (send(client, hdr, hdr->nlmsg_len, MSG_NOSIGNAL) != static_cast<int64_t>(hdr->nlmsg_len)) { return false; } return true; } // Process incoming requests from netlink, server or clients. void WifiRouter::ServerLoop() { while (true) { auto max_fd = 0; fd_set reads{}; auto fdset = [&max_fd, &reads](int fd) { FD_SET(fd, &reads); max_fd = std::max(max_fd, fd); }; fdset(server_fd_); fdset(nl_socket_get_fd(sock_.get())); for (int client : registered_clients_) fdset(client); if (select(max_fd + 1, &reads, nullptr, nullptr, nullptr) <= 0) continue; if (FD_ISSET(server_fd_, &reads)) AcceptNewClient(); if (FD_ISSET(nl_socket_get_fd(sock_.get()), &reads)) RouteWIFIPacket(); // Process any client messages left. Drop any client that is no longer // talking with us. for (auto client = registered_clients_.begin(); client != registered_clients_.end();) { auto cfd = *client++; // Is our client sending us data? if (FD_ISSET(cfd, &reads)) { if (!HandleClientMessage(cfd)) RemoveClient(cfd); } } } } } // namespace } // namespace cvd int main(int argc, char* argv[]) { using namespace cvd; google::ParseCommandLineFlags(&argc, &argv, true); #if !defined(ANDROID) // We should check for legitimate google logging here. google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); #endif WifiRouter r; r.Init(); r.ServerLoop(); } <|endoftext|>
<commit_before> #include <iostream> #include <string> #include <sstream> #include <fstream> #include <map> #include <set> #include "parse.h" #include "braceexpr.h" class Flags; std::vector<std::string> parseOpts(int argc, char ** argv, Flags & flags); int findParam(int argc, char ** argv); int validate(int argc, char ** argv); int format(int argc, char ** argv); int main(int argc, char ** argv) { if (argc < 2) { std::cerr << "must specify a subcommand\n"; return 1; } std::string subcmd(argv[1]); if (subcmd == "find") return findParam(argc - 2, argv + 2); else if (subcmd == "validate") return validate(argc - 2, argv + 2); else if (subcmd == "format") return format(argc - 2, argv + 2); else if (subcmd == "braceexpr") { std::stringstream ss; for (std::string line; std::getline(std::cin, line);) ss << line << std::endl; hit::BraceExpander expander; hit::EnvEvaler env; hit::RawEvaler raw; expander.registerEvaler("env", env); expander.registerEvaler("raw", raw); std::cout << expander.expand(nullptr, ss.str()) << "\n"; return 0; } std::cerr << "unrecognized subcommand '" << subcmd << "'\n"; return 1; } struct Flag { bool arg; bool have; std::string val; std::string help; }; class Flags { public: Flags(const std::string & usage) : usage_msg(usage) {} void add(std::string name, std::string help, std::string def = "__NONE__") { if (def == "__NONE__") flags[name] = {false, false, "", help}; else flags[name] = {true, false, def, help}; } bool have(std::string flag) { return flags.count(flag) > 0 && flags[flag].have; } std::string val(std::string flag) { return flags[flag].val; } std::string usage() { std::stringstream ss; ss << usage_msg << "\n"; for (auto & pair : flags) { auto flag = pair.second; if (flag.arg) ss << "-" << pair.first << " <arg> " << flag.help << " (default='" << flag.val << "')\n"; else ss << "-" << pair.first << " " << flag.help << " (default=false)\n"; } return ss.str(); } std::map<std::string, Flag> flags; std::string usage_msg; }; std::vector<std::string> parseOpts(int argc, char ** argv, Flags & flags) { int i = 0; for (; i < argc; i++) { std::string arg = argv[i]; if (arg[0] != '-') break; std::string flagname = arg.substr(1); if (flagname[0] == '-') flagname = flagname.substr(1); if (flags.flags.count(flagname) == 0) throw std::runtime_error("unknown flag '" + arg); auto & flag = flags.flags[flagname]; flag.have = true; if (flag.arg) { i++; flag.val = argv[i]; } } std::vector<std::string> positional; for (; i < argc; i++) positional.push_back(argv[i]); return positional; } class DupParamWalker : public hit::Walker { public: DupParamWalker(std::string fname) : _fname(fname) {} void walk(const std::string & fullpath, const std::string & /*nodepath*/, hit::Node * n) override { std::string prefix = n->type() == hit::NodeType::Field ? "parameter" : "section"; if (_have.count(fullpath) > 0) { auto existing = _have[fullpath]; if (_duplicates.count(fullpath) == 0) { errors.push_back( hit::errormsg(_fname, existing, prefix, " '", fullpath, "' supplied multiple times")); _duplicates.insert(fullpath); } errors.push_back( hit::errormsg(_fname, n, prefix, " '", fullpath, "' supplied multiple times")); } _have[n->fullpath()] = n; } std::vector<std::string> errors; private: std::string _fname; std::set<std::string> _duplicates; std::map<std::string, hit::Node *> _have; }; int findParam(int argc, char ** argv) { Flags flags("hit find [flags] <parameter-path> <file>..."); flags.add("f", "only show file name"); auto positional = parseOpts(argc, argv, flags); if (positional.size() < 2) { std::cerr << flags.usage(); return 1; } std::string srcpath(positional[0]); int ret = 0; for (int i = 1; i < positional.size(); i++) { std::string fname(positional[i]); std::ifstream f(fname); std::string input((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); hit::Node * root = nullptr; try { root = hit::parse(fname, input); } catch (std::exception & err) { std::cerr << err.what() << "\n"; ret = 1; continue; } auto n = root->find(srcpath); if (n) { if (flags.have("f")) std::cout << fname << "\n"; else std::cout << fname << ":" << n->line() << "\n"; } } return ret; } // the style file is of the format: // // [format] // indent_string = " " // line_length = 100 // canonical_section_markers = true // // [sorting] // [pattern] // section = "[^/]+/[^/]+" // order = "type" // [] // [pattern] // section = "" // order = "Mesh ** Executioner Outputs" // [] // [] // [] // // where all fields are optional and the sorting section is also optional. If the sorting section // is present, you can have as many patterns as you want, but each pattern section must have // 'section' and 'order' fields. int format(int argc, char ** argv) { Flags flags("hit format [flags] <file>..."); flags.add("h", "print help"); flags.add("help", "print help"); flags.add("i", "modify file(s) inplace"); flags.add("style", "hit style file detailing format to use", ""); auto positional = parseOpts(argc, argv, flags); if (flags.have("h") || flags.have("help")) { std::cout << flags.usage(); return 0; } if (positional.size() < 1) { std::cout << flags.usage(); return 1; } hit::Formatter fmt; if (flags.have("style")) { try { std::string fname(flags.val("style")); std::ifstream f(fname); std::string input((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); fmt = hit::Formatter(flags.val("style"), input); } catch (std::exception & err) { std::cerr << "invalid format style " << err.what() << "\n"; return 1; } } int ret = 0; for (int i = 0; i < positional.size(); i++) { std::string fname(positional[i]); std::ifstream f(fname); std::string input(std::istreambuf_iterator<char>(f), {}); try { auto fmted = fmt.format(fname, input); if (flags.have("i")) { std::ofstream output(fname); output << fmted; } else std::cout << fmted; } catch (std::exception & err) { std::cerr << err.what() << "\n"; ret = 1; continue; } } return ret; } int validate(int argc, char ** argv) { if (argc < 1) { std::cerr << "please pass in an input file argument\n"; return 1; } int ret = 0; for (int i = 0; i < argc; i++) { std::string fname(argv[i]); std::ifstream f(fname); std::string input((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); std::unique_ptr<hit::Node> root; try { root.reset(hit::parse(fname, input)); } catch (std::exception & err) { std::cout << err.what() << "\n"; ret = 1; continue; } DupParamWalker w(fname); root->walk(&w, hit::NodeType::Field); for (auto & msg : w.errors) std::cout << msg << "\n"; } return ret; } <commit_msg>Update HIT main so that we can use it to format test specs<commit_after> #include <iostream> #include <string> #include <sstream> #include <fstream> #include <map> #include <set> #include <memory> #include "parse.h" #include "braceexpr.h" class Flags; std::vector<std::string> parseOpts(int argc, char ** argv, Flags & flags); int findParam(int argc, char ** argv); int validate(int argc, char ** argv); int format(int argc, char ** argv); int main(int argc, char ** argv) { if (argc < 2) { std::cerr << "must specify a subcommand\n"; return 1; } std::string subcmd(argv[1]); if (subcmd == "find") return findParam(argc - 2, argv + 2); else if (subcmd == "validate") return validate(argc - 2, argv + 2); else if (subcmd == "format") return format(argc - 2, argv + 2); else if (subcmd == "braceexpr") { std::stringstream ss; for (std::string line; std::getline(std::cin, line);) ss << line << std::endl; hit::BraceExpander expander("STDIN"); hit::EnvEvaler env; hit::RawEvaler raw; expander.registerEvaler("env", env); expander.registerEvaler("raw", raw); std::cout << expander.expand(nullptr, ss.str()) << "\n"; return 0; } std::cerr << "unrecognized subcommand '" << subcmd << "'\n"; return 1; } struct Flag { bool arg; bool have; std::string val; std::string help; }; class Flags { public: Flags(const std::string & usage) : usage_msg(usage) {} void add(std::string name, std::string help, std::string def = "__NONE__") { if (def == "__NONE__") flags[name] = {false, false, "", help}; else flags[name] = {true, false, def, help}; } bool have(std::string flag) { return flags.count(flag) > 0 && flags[flag].have; } std::string val(std::string flag) { return flags[flag].val; } std::string usage() { std::stringstream ss; ss << usage_msg << "\n"; for (auto & pair : flags) { auto flag = pair.second; if (flag.arg) ss << "-" << pair.first << " <arg> " << flag.help << " (default='" << flag.val << "')\n"; else ss << "-" << pair.first << " " << flag.help << " (default=false)\n"; } return ss.str(); } std::map<std::string, Flag> flags; std::string usage_msg; }; std::vector<std::string> parseOpts(int argc, char ** argv, Flags & flags) { int i = 0; for (; i < argc; i++) { std::string arg = argv[i]; if (arg[0] != '-') break; std::string flagname = arg.substr(1); if (flagname[0] == '-') flagname = flagname.substr(1); if (flags.flags.count(flagname) == 0) throw std::runtime_error("unknown flag '" + arg); auto & flag = flags.flags[flagname]; flag.have = true; if (flag.arg) { i++; flag.val = argv[i]; } } std::vector<std::string> positional; for (; i < argc; i++) positional.push_back(argv[i]); return positional; } class DupParamWalker : public hit::Walker { public: DupParamWalker(std::string fname) : _fname(fname) {} void walk(const std::string & fullpath, const std::string & /*nodepath*/, hit::Node * n) override { std::string prefix = n->type() == hit::NodeType::Field ? "parameter" : "section"; if (_have.count(fullpath) > 0) { auto existing = _have[fullpath]; if (_duplicates.count(fullpath) == 0) { errors.push_back( hit::errormsg(_fname, existing, prefix, " '", fullpath, "' supplied multiple times")); _duplicates.insert(fullpath); } errors.push_back( hit::errormsg(_fname, n, prefix, " '", fullpath, "' supplied multiple times")); } _have[n->fullpath()] = n; } std::vector<std::string> errors; private: std::string _fname; std::set<std::string> _duplicates; std::map<std::string, hit::Node *> _have; }; int findParam(int argc, char ** argv) { Flags flags("hit find [flags] <parameter-path> <file>..."); flags.add("f", "only show file name"); auto positional = parseOpts(argc, argv, flags); if (positional.size() < 2) { std::cerr << flags.usage(); return 1; } std::string srcpath(positional[0]); int ret = 0; for (int i = 1; i < positional.size(); i++) { std::string fname(positional[i]); std::ifstream f(fname); std::string input((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); hit::Node * root = nullptr; try { root = hit::parse(fname, input); } catch (std::exception & err) { std::cerr << err.what() << "\n"; ret = 1; continue; } auto n = root->find(srcpath); if (n) { if (flags.have("f")) std::cout << fname << "\n"; else std::cout << fname << ":" << n->line() << "\n"; } } return ret; } // the style file is of the format: // // [format] // indent_string = " " // line_length = 100 // canonical_section_markers = true // // [sorting] // [pattern] // section = "[^/]+/[^/]+" // order = "type" // [] // [pattern] // section = "" // order = "Mesh ** Executioner Outputs" // [] // [] // [] // // where all fields are optional and the sorting section is also optional. If the sorting section // is present, you can have as many patterns as you want, but each pattern section must have // 'section' and 'order' fields. int format(int argc, char ** argv) { Flags flags("hit format [flags] <file>..."); flags.add("h", "print help"); flags.add("help", "print help"); flags.add("i", "modify file(s) inplace"); flags.add("style", "hit style file detailing format to use", ""); auto positional = parseOpts(argc, argv, flags); if (flags.have("h") || flags.have("help")) { std::cout << flags.usage(); return 0; } if (positional.size() < 1) { std::cout << flags.usage(); return 1; } hit::Formatter fmt; if (flags.have("style")) { try { std::string fname(flags.val("style")); std::ifstream f(fname); std::string input((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); fmt = hit::Formatter(flags.val("style"), input); } catch (std::exception & err) { std::cerr << "invalid format style " << err.what() << "\n"; return 1; } } int ret = 0; for (int i = 0; i < positional.size(); i++) { std::string fname(positional[i]); std::ifstream f(fname); std::string input(std::istreambuf_iterator<char>(f), {}); try { auto fmted = fmt.format(fname, input); if (flags.have("i")) { std::ofstream output(fname); output << fmted; } else std::cout << fmted; } catch (std::exception & err) { std::cerr << err.what() << "\n"; ret = 1; continue; } } return ret; } int validate(int argc, char ** argv) { if (argc < 1) { std::cerr << "please pass in an input file argument\n"; return 1; } int ret = 0; for (int i = 0; i < argc; i++) { std::string fname(argv[i]); std::ifstream f(fname); std::string input((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); std::unique_ptr<hit::Node> root; try { root.reset(hit::parse(fname, input)); } catch (std::exception & err) { std::cout << err.what() << "\n"; ret = 1; continue; } DupParamWalker w(fname); root->walk(&w, hit::NodeType::Field); for (auto & msg : w.errors) std::cout << msg << "\n"; } return ret; } <|endoftext|>
<commit_before>/********************************************************************************************************* * FileManagerController.cpp * Note: iBurnMgr FileManagerController * E-mail:<forcemz@outlook.com> * Data: @2015.03 * Copyright (C) 2015 The ForceStudio All Rights Reserved. **********************************************************************************************************/ #include "Precompiled.h" #include <Uxtheme.h> #include <strsafe.h> #include <ShlObj.h> #include <Shlwapi.h> #include "APIController.h" #pragma comment(lib,"propsys.lib") #pragma comment(lib,"shlwapi.lib") typedef COMDLG_FILTERSPEC FileType; typedef struct _DialogInfo{ wchar_t DlgTitle[256]; wchar_t DefualtType[256]; //FileType* filetype; }DialogInfo; const FileType FileArg[] = { { L"ISO/UDF file (*.iso)", L"*.iso" }, { L"Onther Image file (*.img;*.dvd*.bin)", L"*.img;*.dvd;*.bin" }, { L"All Files (*.*)", L"*.*" } }; UINT Argc = ARRAYSIZE(FileArg); //DialogInfo dlf={L"Դļ",L"cpp"}; void ReportErrorEx(LPCWSTR pszFunction, HRESULT hr) { wchar_t szMessage[200]; if (SUCCEEDED(StringCchPrintf(szMessage, ARRAYSIZE(szMessage), L"%s failed w/hr 0x%08lx", pszFunction, hr))) { MessageBox(NULL, szMessage, L"Error", MB_ICONERROR); } } LRESULT OpenImageFile(HWND hWnd, PWSTR Imagename) { HRESULT hr = S_OK; // Create a new common open file dialog. IFileDialog *pfd = NULL; hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd)); if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) { hr = pfd->SetTitle(L"Select the Image file"); } // Specify file types for the file dialog. if (SUCCEEDED(hr)) { hr = pfd->SetFileTypes(Argc, FileArg); if (SUCCEEDED(hr)) { // Set the selected file type index to ISO Image. hr = pfd->SetFileTypeIndex(1); } } // Set the default extension to be added to file names as ".iso" if (SUCCEEDED(hr)) { hr = pfd->SetDefaultExtension(L"*.iso"); } // Show the open file dialog. if (SUCCEEDED(hr)) { hr = pfd->Show(hWnd); if (SUCCEEDED(hr)) { // Get the result of the open file dialog. IShellItem *psiResult = NULL; hr = pfd->GetResult(&psiResult); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { wcscpy_s(Imagename, (1024*32-1), pszPath); //MessageBox(hWnd, pszPath, L"The selected file is", MB_OK); CoTaskMemFree(pszPath); } psiResult->Release(); } } else { if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) { // User cancelled the dialog... } } } pfd->Release(); } // Report the error. if (FAILED(hr)) { // If it's not that the user cancelled the dialog, report the error in a // message box. if (hr != HRESULT_FROM_WIN32(ERROR_CANCELLED)) { ReportErrorEx(L"OnOpenAFile", hr); } } return hr; }<commit_msg>Update FileManagerController.cpp<commit_after>/********************************************************************************************************* * FileManagerController.cpp * Note: iBurnMgr FileManagerController * E-mail:<forcemz@outlook.com> * Date: @2015.03 * Copyright (C) 2015 The ForceStudio All Rights Reserved. **********************************************************************************************************/ #include "Precompiled.h" #include <Uxtheme.h> #include <strsafe.h> #include <ShlObj.h> #include <Shlwapi.h> #include "APIController.h" #pragma comment(lib,"propsys.lib") #pragma comment(lib,"shlwapi.lib") typedef COMDLG_FILTERSPEC FileType; typedef struct _DialogInfo{ wchar_t DlgTitle[256]; wchar_t DefualtType[256]; //FileType* filetype; }DialogInfo; const FileType FileArg[] = { { L"ISO/UDF file (*.iso)", L"*.iso" }, { L"Onther Image file (*.img;*.dvd£»*.bin)", L"*.img;*.dvd;*.bin" }, { L"All Files (*.*)", L"*.*" } }; UINT Argc = ARRAYSIZE(FileArg); //DialogInfo dlf={L"´ò¿ªÔ´Îļþ",L"cpp"}; void ReportErrorEx(LPCWSTR pszFunction, HRESULT hr) { wchar_t szMessage[200]; if (SUCCEEDED(StringCchPrintf(szMessage, ARRAYSIZE(szMessage), L"%s failed w/hr 0x%08lx", pszFunction, hr))) { MessageBox(NULL, szMessage, L"Error", MB_ICONERROR); } } LRESULT OpenImageFile(HWND hWnd, PWSTR Imagename) { HRESULT hr = S_OK; // Create a new common open file dialog. IFileDialog *pfd = NULL; hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd)); if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) { hr = pfd->SetTitle(L"Select the Image file"); } // Specify file types for the file dialog. if (SUCCEEDED(hr)) { hr = pfd->SetFileTypes(Argc, FileArg); if (SUCCEEDED(hr)) { // Set the selected file type index to ISO Image. hr = pfd->SetFileTypeIndex(1); } } // Set the default extension to be added to file names as ".iso" if (SUCCEEDED(hr)) { hr = pfd->SetDefaultExtension(L"*.iso"); } // Show the open file dialog. if (SUCCEEDED(hr)) { hr = pfd->Show(hWnd); if (SUCCEEDED(hr)) { // Get the result of the open file dialog. IShellItem *psiResult = NULL; hr = pfd->GetResult(&psiResult); if (SUCCEEDED(hr)) { PWSTR pszPath = NULL; hr = psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath); if (SUCCEEDED(hr)) { wcscpy_s(Imagename, (1024*32-1), pszPath); //MessageBox(hWnd, pszPath, L"The selected file is", MB_OK); CoTaskMemFree(pszPath); } psiResult->Release(); } } else { if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) { // User cancelled the dialog... } } } pfd->Release(); } // Report the error. if (FAILED(hr)) { // If it's not that the user cancelled the dialog, report the error in a // message box. if (hr != HRESULT_FROM_WIN32(ERROR_CANCELLED)) { ReportErrorEx(L"OnOpenAFile", hr); } } return hr; } <|endoftext|>
<commit_before>#include <string> #include <map> #include "Parser.h" #include "getpot.h" #include "parameters.h" #include "ParserBlockFactory.h" Parser::Parser(std::string input_filename) :_input_filename(input_filename), _input_tree(NULL) {} Parser::~Parser() { if (_input_tree != NULL) { delete (_input_tree); } } void Parser::parse() { std::vector<std::string> elements; std::string curr_value, curr_identifier; ParserBlock *curr_block, *t; GetPot input_file(_input_filename); _input_tree = new ParserBlock("/", "/", NULL, input_file); _section_names = input_file.get_section_names(); // The variable_names function returns section names and variable names in // one large string so we can build the data structure in one pass for (std::vector<std::string>::iterator i=_section_names.begin(); i != _section_names.end(); ++i) { elements.clear(); tokenize(*i, elements); curr_block = _input_tree; curr_identifier = ""; for (int j=0; j<elements.size(); ++j) { // We don't want a leading slash if (j) curr_identifier += "/"; curr_identifier += elements[j]; std::vector<ParserBlock *>::reverse_iterator last = curr_block->_children.rbegin(); if (last == curr_block->_children.rend() || (*last)->getID() != curr_identifier) { // Add the new block to the parse tree std::string matched_identifier = ParserBlockFactory::instance()->isRegistered(curr_identifier); if (matched_identifier.length()) curr_block->_children.push_back(ParserBlockFactory::instance()->add(matched_identifier, curr_identifier, curr_block, input_file)); else curr_block->_children.push_back(new ParserBlock(curr_identifier, curr_identifier, curr_block, input_file)); } curr_block = *(curr_block->_children.rbegin()); } // Extract all the requested parameters from the input file extractParams(curr_block->getID(), curr_block->_block_params, input_file); extractParams(curr_block->getID(), curr_block->_class_params, input_file); } fixupOptionalBlocks(input_file); #ifdef DEBUG _input_tree->printBlockData(); #endif // Make a second pass through the tree to setup the various MOOSE objects execute(); } void Parser::extractParams(const std::string & prefix, Parameters &p, const GetPot & input_file) { for (Parameters::iterator iter = p.begin(); iter != p.end(); ++iter) { setParameters(prefix + "/" + iter->first, iter, input_file); } } void Parser::tokenize(const std::string &str, std::vector<std::string> &elements, const std::string &delims) { std::string::size_type last_pos = str.find_first_not_of(delims, 0); std::string::size_type pos = str.find_first_of(delims, last_pos); while (pos != std::string::npos || last_pos != std::string::npos) { elements.push_back(str.substr(last_pos, pos - last_pos)); // skip delims between tokens last_pos = str.find_first_not_of(delims, pos); pos = str.find_first_of(delims, last_pos); } } void Parser::fixupOptionalBlocks(const GetPot & input_file) { /* Create a map of Optional Blocks to fill in if they don't exist in the tree and where * they should fit (before the second id listed) */ std::map<std::string, std::string> optionalBlocks; std::map<std::string, std::string>::iterator i; ParserBlock *block_ptr; optionalBlocks["AuxVariables"] = "Kernels"; optionalBlocks["AuxKernels"] = "BCs"; // First see if the Optional Block exists for (i = optionalBlocks.begin(); i != optionalBlocks.end(); ++i) { if (_input_tree->locateBlock(i->first) == NULL) { // Get a pointer to the required block to prepare for insertion // The newly constructed block will be the sibling before this block // which means it better exist and it better not be the root block_ptr = _input_tree->locateBlock(i->second); if (block_ptr == NULL || block_ptr->_parent == NULL) mooseError(); ParserBlock::PBChildIterator position = find(block_ptr->_parent->_children.begin(), block_ptr->_parent->_children.end(), block_ptr); block_ptr->_parent->_children.insert(position, ParserBlockFactory::instance()->add(i->first, i->first, block_ptr->_parent, input_file)); } } } void Parser::execute() { _input_tree->execute(); } // function to set parameters with arbitrary type bool Parser::setParameters(std::string name, Parameters::iterator &it, const GetPot &input_file) { Parameters::Parameter<Real> * real_param = dynamic_cast<Parameters::Parameter<Real>*>(it->second); Parameters::Parameter<int> * int_param = dynamic_cast<Parameters::Parameter<int>*>(it->second); Parameters::Parameter<bool> * bool_param = dynamic_cast<Parameters::Parameter<bool>*>(it->second); Parameters::Parameter<std::string> * string_param = dynamic_cast<Parameters::Parameter<std::string>*>(it->second); Parameters::Parameter<std::vector<Real> > * vec_real_param = dynamic_cast<Parameters::Parameter<std::vector<Real> >*>(it->second); Parameters::Parameter<std::vector<int> > * vec_int_param = dynamic_cast<Parameters::Parameter<std::vector<int> >*>(it->second); Parameters::Parameter<std::vector<bool> > * vec_bool_param = dynamic_cast<Parameters::Parameter<std::vector<bool> >*>(it->second); Parameters::Parameter<std::vector<std::string> > * vec_string_param = dynamic_cast<Parameters::Parameter<std::vector<std::string> >*>(it->second); Parameters::Parameter<std::vector<std::vector<Real> > > * tensor_real_param = dynamic_cast<Parameters::Parameter<std::vector<std::vector<Real> > >*>(it->second); Parameters::Parameter<std::vector<std::vector<int> > > * tensor_int_param = dynamic_cast<Parameters::Parameter<std::vector<std::vector<int> > >*>(it->second); Parameters::Parameter<std::vector<std::vector<bool> > > * tensor_bool_param = dynamic_cast<Parameters::Parameter<std::vector<std::vector<bool> > >*>(it->second); bool default_flag = false; if( real_param ) { Real from_input; from_input = input_file((name).c_str(), real_param->get()); //check whether parameter exists in inputfile. if( real_param->get() == from_input ) default_flag = true; real_param->set()= from_input; return default_flag; } else if( int_param ) { int from_input; from_input = input_file((name).c_str(), int_param->get()); if( int_param->get() == from_input ) default_flag = true; int_param->set() = from_input; return default_flag; } else if( bool_param ) { bool from_input; from_input = input_file((name).c_str(), bool_param->get()); if( bool_param->get() == from_input ) default_flag = true; bool_param->set() = from_input; return default_flag; } else if( string_param ) { std::string from_input; from_input = input_file((name).c_str(), string_param->get()); if( string_param->get() == from_input ) default_flag = true; string_param->set() = from_input; return default_flag; } else if( vec_real_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_real_param->set().resize(vec_size); if( vec_size == 0) default_flag = true; for(int j=0;j<vec_size;j++) vec_real_param->set()[j] = input_file((name).c_str(), 0.0, j); return default_flag; } else if( vec_int_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_int_param->set().resize(vec_size); if( vec_size == 0 ) default_flag = true; for(int j=0;j<vec_size;j++) vec_int_param->set()[j] = input_file((name).c_str(), vec_int_param->get()[j], j); return default_flag; } else if( vec_bool_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_bool_param->set().resize(vec_size); if( vec_size == 0 ) default_flag = true; for(int j=0;j<vec_size;j++) vec_bool_param->set()[j] = input_file((name).c_str(), vec_bool_param->get()[j], j); return default_flag; } else if( vec_string_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_string_param->set().resize(vec_size); if( vec_size == 0 ) default_flag = true; for(int j=0;j<vec_size;j++) vec_string_param->set()[j] = input_file((name).c_str(), vec_string_param->get()[j].c_str(), j); return default_flag; } else if( tensor_real_param) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_size = pow(vec_size,0.5); if( vec_size == 0 ) default_flag = true; tensor_real_param->set().resize(vec_size); for(int j=0;j<vec_size;j++) tensor_real_param->set()[j].resize(vec_size); unsigned int cntr = 0; for(int j=0;j<vec_size;j++) { for(int i=0;i<vec_size;i++) { tensor_real_param->set()[i][j] = input_file((name).c_str(), tensor_real_param->get()[i][j], cntr); cntr++; } } return default_flag; } else if( tensor_int_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_size = pow(vec_size,0.5); if( vec_size == 0 ) default_flag = true; if( vec_size == 0 ) { tensor_int_param->set().resize(1); tensor_int_param->set()[0].resize(1); } else { tensor_int_param->set().resize(vec_size); for(int j=0;j<vec_size;j++) tensor_int_param->set()[j].resize(vec_size); } unsigned int cntr = 0; for(int j=0;j<vec_size;j++) { for(int i=0;i<vec_size;i++) { tensor_int_param->set()[i][j] = input_file((name).c_str(), tensor_int_param->get()[i][j], cntr); cntr++; } } return default_flag; } else if( tensor_bool_param) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_size = pow(vec_size,0.5); if( vec_size == 0 ) default_flag = true; if( vec_size == 0 ) { tensor_bool_param->set().resize(1); tensor_bool_param->set()[0].resize(1); } else { tensor_bool_param->set().resize(vec_size); for(int j=0;j<vec_size;j++) tensor_bool_param->set()[j].resize(vec_size); } unsigned int cntr = 0; for(int j=0;j<vec_size;j++) { for(int i=0;i<vec_size;i++) { tensor_bool_param->set()[i][j] = input_file((name).c_str(), tensor_bool_param->get()[i][j], cntr); cntr++; } } return default_flag; } else return true; } <commit_msg>allow unsigned int parameters<commit_after>#include <string> #include <map> #include "Parser.h" #include "getpot.h" #include "parameters.h" #include "ParserBlockFactory.h" Parser::Parser(std::string input_filename) :_input_filename(input_filename), _input_tree(NULL) {} Parser::~Parser() { if (_input_tree != NULL) { delete (_input_tree); } } void Parser::parse() { std::vector<std::string> elements; std::string curr_value, curr_identifier; ParserBlock *curr_block, *t; GetPot input_file(_input_filename); _input_tree = new ParserBlock("/", "/", NULL, input_file); _section_names = input_file.get_section_names(); // The variable_names function returns section names and variable names in // one large string so we can build the data structure in one pass for (std::vector<std::string>::iterator i=_section_names.begin(); i != _section_names.end(); ++i) { elements.clear(); tokenize(*i, elements); curr_block = _input_tree; curr_identifier = ""; for (int j=0; j<elements.size(); ++j) { // We don't want a leading slash if (j) curr_identifier += "/"; curr_identifier += elements[j]; std::vector<ParserBlock *>::reverse_iterator last = curr_block->_children.rbegin(); if (last == curr_block->_children.rend() || (*last)->getID() != curr_identifier) { // Add the new block to the parse tree std::string matched_identifier = ParserBlockFactory::instance()->isRegistered(curr_identifier); if (matched_identifier.length()) curr_block->_children.push_back(ParserBlockFactory::instance()->add(matched_identifier, curr_identifier, curr_block, input_file)); else curr_block->_children.push_back(new ParserBlock(curr_identifier, curr_identifier, curr_block, input_file)); } curr_block = *(curr_block->_children.rbegin()); } // Extract all the requested parameters from the input file extractParams(curr_block->getID(), curr_block->_block_params, input_file); extractParams(curr_block->getID(), curr_block->_class_params, input_file); } fixupOptionalBlocks(input_file); #ifdef DEBUG _input_tree->printBlockData(); #endif // Make a second pass through the tree to setup the various MOOSE objects execute(); } void Parser::extractParams(const std::string & prefix, Parameters &p, const GetPot & input_file) { for (Parameters::iterator iter = p.begin(); iter != p.end(); ++iter) { setParameters(prefix + "/" + iter->first, iter, input_file); } } void Parser::tokenize(const std::string &str, std::vector<std::string> &elements, const std::string &delims) { std::string::size_type last_pos = str.find_first_not_of(delims, 0); std::string::size_type pos = str.find_first_of(delims, last_pos); while (pos != std::string::npos || last_pos != std::string::npos) { elements.push_back(str.substr(last_pos, pos - last_pos)); // skip delims between tokens last_pos = str.find_first_not_of(delims, pos); pos = str.find_first_of(delims, last_pos); } } void Parser::fixupOptionalBlocks(const GetPot & input_file) { /* Create a map of Optional Blocks to fill in if they don't exist in the tree and where * they should fit (before the second id listed) */ std::map<std::string, std::string> optionalBlocks; std::map<std::string, std::string>::iterator i; ParserBlock *block_ptr; optionalBlocks["AuxVariables"] = "Kernels"; optionalBlocks["AuxKernels"] = "BCs"; // First see if the Optional Block exists for (i = optionalBlocks.begin(); i != optionalBlocks.end(); ++i) { if (_input_tree->locateBlock(i->first) == NULL) { // Get a pointer to the required block to prepare for insertion // The newly constructed block will be the sibling before this block // which means it better exist and it better not be the root block_ptr = _input_tree->locateBlock(i->second); if (block_ptr == NULL || block_ptr->_parent == NULL) mooseError(); ParserBlock::PBChildIterator position = find(block_ptr->_parent->_children.begin(), block_ptr->_parent->_children.end(), block_ptr); block_ptr->_parent->_children.insert(position, ParserBlockFactory::instance()->add(i->first, i->first, block_ptr->_parent, input_file)); } } } void Parser::execute() { _input_tree->execute(); } // function to set parameters with arbitrary type bool Parser::setParameters(std::string name, Parameters::iterator &it, const GetPot &input_file) { Parameters::Parameter<Real> * real_param = dynamic_cast<Parameters::Parameter<Real>*>(it->second); Parameters::Parameter<int> * int_param = dynamic_cast<Parameters::Parameter<int>*>(it->second); Parameters::Parameter<unsigned int> * uint_param = dynamic_cast<Parameters::Parameter<unsigned int>*>(it->second); Parameters::Parameter<bool> * bool_param = dynamic_cast<Parameters::Parameter<bool>*>(it->second); Parameters::Parameter<std::string> * string_param = dynamic_cast<Parameters::Parameter<std::string>*>(it->second); Parameters::Parameter<std::vector<Real> > * vec_real_param = dynamic_cast<Parameters::Parameter<std::vector<Real> >*>(it->second); Parameters::Parameter<std::vector<int> > * vec_int_param = dynamic_cast<Parameters::Parameter<std::vector<int> >*>(it->second); Parameters::Parameter<std::vector<bool> > * vec_bool_param = dynamic_cast<Parameters::Parameter<std::vector<bool> >*>(it->second); Parameters::Parameter<std::vector<std::string> > * vec_string_param = dynamic_cast<Parameters::Parameter<std::vector<std::string> >*>(it->second); Parameters::Parameter<std::vector<std::vector<Real> > > * tensor_real_param = dynamic_cast<Parameters::Parameter<std::vector<std::vector<Real> > >*>(it->second); Parameters::Parameter<std::vector<std::vector<int> > > * tensor_int_param = dynamic_cast<Parameters::Parameter<std::vector<std::vector<int> > >*>(it->second); Parameters::Parameter<std::vector<std::vector<bool> > > * tensor_bool_param = dynamic_cast<Parameters::Parameter<std::vector<std::vector<bool> > >*>(it->second); bool default_flag = false; if( real_param ) { Real from_input; from_input = input_file((name).c_str(), real_param->get()); //check whether parameter exists in inputfile. if( real_param->get() == from_input ) default_flag = true; real_param->set()= from_input; return default_flag; } else if( int_param ) { int from_input; from_input = input_file((name).c_str(), int_param->get()); if( int_param->get() == from_input ) default_flag = true; int_param->set() = from_input; return default_flag; } else if( uint_param ) { unsigned int from_input; from_input = input_file((name).c_str(), uint_param->get()); if( uint_param->get() == from_input ) default_flag = true; uint_param->set() = from_input; return default_flag; } else if( bool_param ) { bool from_input; from_input = input_file((name).c_str(), bool_param->get()); if( bool_param->get() == from_input ) default_flag = true; bool_param->set() = from_input; return default_flag; } else if( string_param ) { std::string from_input; from_input = input_file((name).c_str(), string_param->get()); if( string_param->get() == from_input ) default_flag = true; string_param->set() = from_input; return default_flag; } else if( vec_real_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_real_param->set().resize(vec_size); if( vec_size == 0) default_flag = true; for(int j=0;j<vec_size;j++) vec_real_param->set()[j] = input_file((name).c_str(), 0.0, j); return default_flag; } else if( vec_int_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_int_param->set().resize(vec_size); if( vec_size == 0 ) default_flag = true; for(int j=0;j<vec_size;j++) vec_int_param->set()[j] = input_file((name).c_str(), vec_int_param->get()[j], j); return default_flag; } else if( vec_bool_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_bool_param->set().resize(vec_size); if( vec_size == 0 ) default_flag = true; for(int j=0;j<vec_size;j++) vec_bool_param->set()[j] = input_file((name).c_str(), vec_bool_param->get()[j], j); return default_flag; } else if( vec_string_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_string_param->set().resize(vec_size); if( vec_size == 0 ) default_flag = true; for(int j=0;j<vec_size;j++) vec_string_param->set()[j] = input_file((name).c_str(), vec_string_param->get()[j].c_str(), j); return default_flag; } else if( tensor_real_param) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_size = pow(vec_size,0.5); if( vec_size == 0 ) default_flag = true; tensor_real_param->set().resize(vec_size); for(int j=0;j<vec_size;j++) tensor_real_param->set()[j].resize(vec_size); unsigned int cntr = 0; for(int j=0;j<vec_size;j++) { for(int i=0;i<vec_size;i++) { tensor_real_param->set()[i][j] = input_file((name).c_str(), tensor_real_param->get()[i][j], cntr); cntr++; } } return default_flag; } else if( tensor_int_param ) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_size = pow(vec_size,0.5); if( vec_size == 0 ) default_flag = true; if( vec_size == 0 ) { tensor_int_param->set().resize(1); tensor_int_param->set()[0].resize(1); } else { tensor_int_param->set().resize(vec_size); for(int j=0;j<vec_size;j++) tensor_int_param->set()[j].resize(vec_size); } unsigned int cntr = 0; for(int j=0;j<vec_size;j++) { for(int i=0;i<vec_size;i++) { tensor_int_param->set()[i][j] = input_file((name).c_str(), tensor_int_param->get()[i][j], cntr); cntr++; } } return default_flag; } else if( tensor_bool_param) { int vec_size = input_file.vector_variable_size((name).c_str()); vec_size = pow(vec_size,0.5); if( vec_size == 0 ) default_flag = true; if( vec_size == 0 ) { tensor_bool_param->set().resize(1); tensor_bool_param->set()[0].resize(1); } else { tensor_bool_param->set().resize(vec_size); for(int j=0;j<vec_size;j++) tensor_bool_param->set()[j].resize(vec_size); } unsigned int cntr = 0; for(int j=0;j<vec_size;j++) { for(int i=0;i<vec_size;i++) { tensor_bool_param->set()[i][j] = input_file((name).c_str(), tensor_bool_param->get()[i][j], cntr); cntr++; } } return default_flag; } else return true; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pcrcomponentcontext.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef EXTENSIONS_SOURCE_PROPCTRLR_PCROMPONENTCONTEXT_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_PCROMPONENTCONTEXT_HXX /** === begin UNO includes === **/ #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> /** === end UNO includes === **/ //........................................................................ namespace pcr { //........................................................................ //==================================================================== //= ComponentContext //==================================================================== /** a helper class for working with a component context */ class ComponentContext { private: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory > m_xORB; public: /** constructs an instance @param _rxContext the component context to manage @throws ::com::sun::star::lang::NullPointerException if the given context, or its component factory, are <NULL/> */ ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext ); /** constructs an instance @param _rxLegacyFactory the legacy service factor to obtain the <type scope="com::sun::star::uno">XComponentContext</type> from @throws ::com::sun::star::uno::RuntimeException if the given factory or does not have a DefaultContext property to obtain a component context @throws ::com::sun::star::lang::NullPointerException if the given factory is <NULL/>, or provides a component context being <NULL/>, or provides a component context whose component factory is <NULL/> */ ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxLegacyFactory ); /** returns the ->XComponentContext interface */ inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > getUNOContext() const { return m_xContext; } /** determines whether the context is not <NULL/> */ inline sal_Bool is() const { return m_xContext.is(); } /** creates a component using our component factory/context @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < class INTERFACE > bool createComponent( const ::rtl::OUString& _rServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { _out_rxComponent.clear(); _out_rxComponent = _out_rxComponent.query( m_xORB->createInstanceWithContext( _rServiceName, m_xContext ) ); return _out_rxComponent.is(); } /** creates a component using our component factory/context @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < class INTERFACE > bool createComponent( const sal_Char* _pAsciiServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _out_rxComponent ); } /** creates a component using our component factory/context @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const ::rtl::OUString& _rServiceName ) const; /** creates a component using our component factory/context @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const sal_Char* _pAsciiServiceName ) const { return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ) ); } /** returns the ->XMultiServiceFactory interface of ->m_xORB, for passing to older code which does not yet support ->XMultiComponentFactory @throws ::com::sun::star::uno::RuntimeException if our our component factory does not support this interface */ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getLegacyServiceFactory() const; /** retrieves a value from our component context @param _rName the name of the value to retrieve @return the context value with the given name @seealso XComponentContext::getValueByName @seealso getContextValueByAsciiName */ ::com::sun::star::uno::Any getContextValueByName( const ::rtl::OUString& _rName ) const; /** retrieves a value from our component context, specified by 8-bit ASCII string @param _rName the name of the value to retrieve, as ASCII character string @return the context value with the given name @seealso XComponentContext::getValueByName @seealso getContextValueByName */ inline ::com::sun::star::uno::Any getContextValueByAsciiName( const sal_Char* _pAsciiName ) const { return getContextValueByName( ::rtl::OUString::createFromAscii( _pAsciiName ) ); } /** retrieve context to create interfaces by the ctors */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > getContext() const { return m_xContext;} }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_PCROMPONENTCONTEXT_HXX <commit_msg>INTEGRATION: CWS mba30patches01 (1.3.124); FILE MERGED 2008/04/23 10:49:51 mba 1.3.124.2: RESYNC: (1.3-1.4); FILE MERGED 2008/03/18 15:40:59 mba 1.3.124.1: #i86365#: remove unused code<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pcrcomponentcontext.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef EXTENSIONS_SOURCE_PROPCTRLR_PCROMPONENTCONTEXT_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_PCROMPONENTCONTEXT_HXX /** === begin UNO includes === **/ #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> /** === end UNO includes === **/ //........................................................................ namespace pcr { //........................................................................ //==================================================================== //= ComponentContext //==================================================================== /** a helper class for working with a component context */ class ComponentContext { private: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory > m_xORB; public: /** constructs an instance @param _rxContext the component context to manage @throws ::com::sun::star::lang::NullPointerException if the given context, or its component factory, are <NULL/> */ ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext ); /** returns the ->XComponentContext interface */ inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > getUNOContext() const { return m_xContext; } /** determines whether the context is not <NULL/> */ inline sal_Bool is() const { return m_xContext.is(); } /** creates a component using our component factory/context @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < class INTERFACE > bool createComponent( const ::rtl::OUString& _rServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { _out_rxComponent.clear(); _out_rxComponent = _out_rxComponent.query( m_xORB->createInstanceWithContext( _rServiceName, m_xContext ) ); return _out_rxComponent.is(); } /** creates a component using our component factory/context @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < class INTERFACE > bool createComponent( const sal_Char* _pAsciiServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _out_rxComponent ); } /** creates a component using our component factory/context @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const ::rtl::OUString& _rServiceName ) const; /** creates a component using our component factory/context @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const sal_Char* _pAsciiServiceName ) const { return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ) ); } /** returns the ->XMultiServiceFactory interface of ->m_xORB, for passing to older code which does not yet support ->XMultiComponentFactory @throws ::com::sun::star::uno::RuntimeException if our our component factory does not support this interface */ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getLegacyServiceFactory() const; /** retrieves a value from our component context @param _rName the name of the value to retrieve @return the context value with the given name @seealso XComponentContext::getValueByName @seealso getContextValueByAsciiName */ ::com::sun::star::uno::Any getContextValueByName( const ::rtl::OUString& _rName ) const; /** retrieves a value from our component context, specified by 8-bit ASCII string @param _rName the name of the value to retrieve, as ASCII character string @return the context value with the given name @seealso XComponentContext::getValueByName @seealso getContextValueByName */ inline ::com::sun::star::uno::Any getContextValueByAsciiName( const sal_Char* _pAsciiName ) const { return getContextValueByName( ::rtl::OUString::createFromAscii( _pAsciiName ) ); } /** retrieve context to create interfaces by the ctors */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > getContext() const { return m_xContext;} }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_PCROMPONENTCONTEXT_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xdictionary.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: kz $ $Date: 2005-11-01 14:52:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // xdictionary.cpp: implementation of the xdictionary class. // ////////////////////////////////////////////////////////////////////// #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #include <com/sun/star/i18n/WordType.hpp> #include <xdictionary.hxx> #include <i18nutil/unicode.hxx> #include <string.h> #include <breakiteratorImpl.hxx> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { xdictionary::xdictionary(const sal_Char *lang) { #ifdef SAL_DLLPREFIX OUStringBuffer aBuf( strlen(lang) + 7 + 6 ); // mostly "lib*.so" (with * == dict_zh) aBuf.appendAscii( SAL_DLLPREFIX ); #else OUStringBuffer aBuf( strlen(lang) + 7 + 4 ); // mostly "*.dll" (with * == dict_zh) #endif aBuf.appendAscii( "dict_" ).appendAscii( lang ).appendAscii( SAL_DLLEXTENSION ); hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT ); if( hModule ) { int (*func)(); func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getExistMark").pData ); existMark = (sal_uInt8*) (*func)(); func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex1").pData ); index1 = (sal_Int16*) (*func)(); func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getIndex2").pData ); index2 = (sal_Int32*) (*func)(); func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getLenArray").pData ); lenArray = (sal_Int32*) (*func)(); func = (int(*)()) osl_getSymbol( hModule, OUString::createFromAscii("getDataArea").pData ); dataArea = (sal_Unicode*) (*func)(); } else existMark = NULL; for (sal_Int32 i = 0; i < CACHE_MAX; i++) cache[i].size = 0; // for CTL breakiterator, which the word boundary should not inside cell. useCellBoundary = sal_False; japaneseWordBreak = sal_False; } xdictionary::~xdictionary() { osl_unloadModule(hModule); for (sal_Int32 i = 0; i < CACHE_MAX; i++) { if (cache[i].size > 0) { delete cache[i].contents; delete cache[i].wordboundary; } } } void SAL_CALL xdictionary::setJapaneseWordBreak() { japaneseWordBreak = sal_True; } sal_Bool xdictionary::exists(const sal_Unicode c) { sal_Bool exist = existMark ? ((existMark[c>>3] & (1<<(c&0x07))) != 0) : sal_False; if (!exist && japaneseWordBreak) return BreakIteratorImpl::getScriptClass(c) == ScriptType::ASIAN; else return exist; } sal_Int32 SAL_CALL xdictionary::getLongestMatch(const sal_Unicode* str, sal_Int32 sLen) { sal_Int16 idx = index1[str[0] >> 8]; if (idx == 0xFF) return 0; idx = (idx<<8) | (str[0]&0xff); sal_uInt32 begin = index2[idx], end = index2[idx+1]; if (begin == 0) return 0; str++; sLen--; // first character is not stored in the dictionary for (sal_uInt32 i = end; i > begin; i--) { sal_Int32 len = lenArray[i] - lenArray[i - 1]; if (sLen >= len) { const sal_Unicode *dstr = dataArea + lenArray[i-1]; sal_Int32 pos = 0; while (pos < len && dstr[pos] == str[pos]) { pos++; } if (pos == len) return len + 1; } } return 0; } /* * Compare two unicode string, */ sal_Bool SAL_CALL WordBreakCache::equals(const sal_Unicode* str, Boundary& boundary) { // Different length, different string. if (length != boundary.endPos - boundary.startPos) return sal_False; for (sal_Int32 i = 0; i < length; i++) if (contents[i] != str[i + boundary.startPos]) return sal_False; return sal_True; } /* * Retrieve the segment containing the character at pos. * @param pos : Position of the given character. * @return true if CJK. */ sal_Bool SAL_CALL xdictionary::seekSegment(const sal_Unicode *text, sal_Int32 pos, sal_Int32 len, Boundary& segBoundary) { for (segBoundary.startPos = pos - 1; segBoundary.startPos >= 0 && (unicode::isWhiteSpace(text[segBoundary.startPos]) || exists(text[segBoundary.startPos])); segBoundary.startPos--); segBoundary.startPos++; for (segBoundary.endPos = pos; segBoundary.endPos < len && (unicode::isWhiteSpace(text[segBoundary.endPos]) || exists(text[segBoundary.endPos])); segBoundary.endPos++); return segBoundary.endPos > segBoundary.startPos + 1; } #define KANJA 1 #define KATAKANA 2 #define HIRAKANA 3 static sal_Int16 SAL_CALL JapaneseCharType(sal_Unicode c) { if (0x3041 <= c && c <= 0x309e) return HIRAKANA; if (0x30a1 <= c && c <= 0x30fe || 0xff65 <= c && c <= 0xff9f) return KATAKANA; return KANJA; } WordBreakCache& SAL_CALL xdictionary::getCache(const sal_Unicode *text, Boundary& wordBoundary) { WordBreakCache& aCache = cache[text[0] & 0x1f]; if (aCache.size != 0 && aCache.equals(text, wordBoundary)) return aCache; sal_Int32 len = wordBoundary.endPos - wordBoundary.startPos; if (aCache.size == 0 || len > aCache.size) { if (aCache.size != 0) { delete aCache.contents; delete aCache.wordboundary; aCache.size = len; } else aCache.size = len > DEFAULT_SIZE ? len : DEFAULT_SIZE; aCache.contents = new sal_Unicode[aCache.size + 1]; aCache.wordboundary = new sal_Int32[aCache.size + 2]; } aCache.length = len; memcpy(aCache.contents, text + wordBoundary.startPos, len * sizeof(sal_Unicode)); *(aCache.contents + len) = 0x0000; // reset the wordboundary in cache memset(aCache.wordboundary, '\0', sizeof(sal_Int32)*(len + 2)); sal_Int32 i = 0; // loop variable while (aCache.wordboundary[i] < aCache.length) { len = 0; // look the continuous white space as one word and cashe it while (unicode::isWhiteSpace(text[wordBoundary.startPos + aCache.wordboundary[i] + len])) len ++; if (len == 0) { const sal_Unicode *str = text + wordBoundary.startPos + aCache.wordboundary[i]; sal_Int32 slen = aCache.length - aCache.wordboundary[i]; sal_Int16 type = 0, count = 0; for (;len == 0 && slen > 0; str++, slen--) { len = getLongestMatch(str, slen); if (len == 0) { if (!japaneseWordBreak) { len = 1; } else { if (count == 0) type = JapaneseCharType(*str); else if (type != JapaneseCharType(*str)) break; count++; } } } if (count) { aCache.wordboundary[i+1] = aCache.wordboundary[i] + count; i++; if (useCellBoundary) { sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + wordBoundary.startPos - 1]; if (cBoundary > 0) aCache.wordboundary[i] = cBoundary - wordBoundary.startPos; } } } if (len) { aCache.wordboundary[i+1] = aCache.wordboundary[i] + len; i++; if (useCellBoundary) { sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + wordBoundary.startPos - 1]; if (cBoundary > 0) aCache.wordboundary[i] = cBoundary - wordBoundary.startPos; } } } aCache.wordboundary[i + 1] = aCache.length + 1; return aCache; } Boundary SAL_CALL xdictionary::previousWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType) { // looking for the first non-whitespace character from anyPos while (unicode::isWhiteSpace(text[anyPos - 1])) anyPos --; return getWordBoundary(text, anyPos - 1, len, wordType, true); } Boundary SAL_CALL xdictionary::nextWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType) { boundary = getWordBoundary(text, anyPos, len, wordType, true); // looknig for the first non-whitespace character from anyPos anyPos = boundary.endPos; while (unicode::isWhiteSpace(text[anyPos])) anyPos ++; return getWordBoundary(text, anyPos, len, wordType, true); } Boundary SAL_CALL xdictionary::getWordBoundary(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType, sal_Bool bDirection) { if (anyPos >= len || anyPos < 0) { boundary.startPos = boundary.endPos = anyPos < 0 ? 0 : len; } else if (seekSegment(text, anyPos, len, boundary)) { // character in dict WordBreakCache& aCache = getCache(text, boundary); sal_Int32 i = 0; while (aCache.wordboundary[i] <= (sal_Int32)anyPos - boundary.startPos) i++; sal_Int32 startPos = aCache.wordboundary[i - 1]; // if bDirection is false if (!bDirection && startPos > 0 && startPos == (anyPos - boundary.startPos) && unicode::isWhiteSpace(text[anyPos - 1])) i--; boundary.endPos = aCache.wordboundary[i] + boundary.startPos; boundary.startPos += aCache.wordboundary[i - 1]; } else { boundary.startPos = anyPos++; boundary.endPos = anyPos < len ? anyPos : len; } if (wordType == WordType::WORD_COUNT) { // skip punctuation for word count. while (boundary.endPos < len && unicode::isPunctuation(text[boundary.endPos])) boundary.endPos++; } return boundary; } void SAL_CALL xdictionary::setCellBoundary(sal_Int32* cellArray) { useCellBoundary = sal_True; cellBoundary = cellArray; } } } } } <commit_msg>INTEGRATION: CWS warnings01 (1.11.2); FILE MERGED 2006/03/08 13:19:08 nn 1.11.2.2: #i53898# warning-free code 2005/11/10 10:14:59 pl 1.11.2.1: #i53898# removed warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xdictionary.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:42:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // xdictionary.cpp: implementation of the xdictionary class. // ////////////////////////////////////////////////////////////////////// #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #include <com/sun/star/i18n/WordType.hpp> #include <xdictionary.hxx> #include <i18nutil/unicode.hxx> #include <string.h> #include <breakiteratorImpl.hxx> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// using namespace rtl; namespace com { namespace sun { namespace star { namespace i18n { xdictionary::xdictionary(const sal_Char *lang) { #ifdef SAL_DLLPREFIX OUStringBuffer aBuf( strlen(lang) + 7 + 6 ); // mostly "lib*.so" (with * == dict_zh) aBuf.appendAscii( SAL_DLLPREFIX ); #else OUStringBuffer aBuf( strlen(lang) + 7 + 4 ); // mostly "*.dll" (with * == dict_zh) #endif aBuf.appendAscii( "dict_" ).appendAscii( lang ).appendAscii( SAL_DLLEXTENSION ); hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT ); if( hModule ) { int (*func)(); func = (int(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getExistMark").pData ); existMark = (sal_uInt8*) (*func)(); func = (int(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getIndex1").pData ); index1 = (sal_Int16*) (*func)(); func = (int(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getIndex2").pData ); index2 = (sal_Int32*) (*func)(); func = (int(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getLenArray").pData ); lenArray = (sal_Int32*) (*func)(); func = (int(*)()) osl_getFunctionSymbol( hModule, OUString::createFromAscii("getDataArea").pData ); dataArea = (sal_Unicode*) (*func)(); } else existMark = NULL; for (sal_Int32 i = 0; i < CACHE_MAX; i++) cache[i].size = 0; // for CTL breakiterator, which the word boundary should not inside cell. useCellBoundary = sal_False; japaneseWordBreak = sal_False; } xdictionary::~xdictionary() { osl_unloadModule(hModule); for (sal_Int32 i = 0; i < CACHE_MAX; i++) { if (cache[i].size > 0) { delete cache[i].contents; delete cache[i].wordboundary; } } } void SAL_CALL xdictionary::setJapaneseWordBreak() { japaneseWordBreak = sal_True; } sal_Bool xdictionary::exists(const sal_Unicode c) { sal_Bool exist = existMark ? sal::static_int_cast<sal_Bool>((existMark[c>>3] & (1<<(c&0x07))) != 0) : sal_False; if (!exist && japaneseWordBreak) return BreakIteratorImpl::getScriptClass(c) == ScriptType::ASIAN; else return exist; } sal_Int32 SAL_CALL xdictionary::getLongestMatch(const sal_Unicode* str, sal_Int32 sLen) { sal_Int16 idx = index1[str[0] >> 8]; if (idx == 0xFF) return 0; idx = (idx<<8) | (str[0]&0xff); sal_uInt32 begin = index2[idx], end = index2[idx+1]; if (begin == 0) return 0; str++; sLen--; // first character is not stored in the dictionary for (sal_uInt32 i = end; i > begin; i--) { sal_Int32 len = lenArray[i] - lenArray[i - 1]; if (sLen >= len) { const sal_Unicode *dstr = dataArea + lenArray[i-1]; sal_Int32 pos = 0; while (pos < len && dstr[pos] == str[pos]) { pos++; } if (pos == len) return len + 1; } } return 0; } /* * Compare two unicode string, */ sal_Bool SAL_CALL WordBreakCache::equals(const sal_Unicode* str, Boundary& boundary) { // Different length, different string. if (length != boundary.endPos - boundary.startPos) return sal_False; for (sal_Int32 i = 0; i < length; i++) if (contents[i] != str[i + boundary.startPos]) return sal_False; return sal_True; } /* * Retrieve the segment containing the character at pos. * @param pos : Position of the given character. * @return true if CJK. */ sal_Bool SAL_CALL xdictionary::seekSegment(const sal_Unicode *text, sal_Int32 pos, sal_Int32 len, Boundary& segBoundary) { for (segBoundary.startPos = pos - 1; segBoundary.startPos >= 0 && (unicode::isWhiteSpace(text[segBoundary.startPos]) || exists(text[segBoundary.startPos])); segBoundary.startPos--); segBoundary.startPos++; for (segBoundary.endPos = pos; segBoundary.endPos < len && (unicode::isWhiteSpace(text[segBoundary.endPos]) || exists(text[segBoundary.endPos])); segBoundary.endPos++); return segBoundary.endPos > segBoundary.startPos + 1; } #define KANJA 1 #define KATAKANA 2 #define HIRAKANA 3 static sal_Int16 SAL_CALL JapaneseCharType(sal_Unicode c) { if (0x3041 <= c && c <= 0x309e) return HIRAKANA; if (0x30a1 <= c && c <= 0x30fe || 0xff65 <= c && c <= 0xff9f) return KATAKANA; return KANJA; } WordBreakCache& SAL_CALL xdictionary::getCache(const sal_Unicode *text, Boundary& wordBoundary) { WordBreakCache& aCache = cache[text[0] & 0x1f]; if (aCache.size != 0 && aCache.equals(text, wordBoundary)) return aCache; sal_Int32 len = wordBoundary.endPos - wordBoundary.startPos; if (aCache.size == 0 || len > aCache.size) { if (aCache.size != 0) { delete aCache.contents; delete aCache.wordboundary; aCache.size = len; } else aCache.size = len > DEFAULT_SIZE ? len : DEFAULT_SIZE; aCache.contents = new sal_Unicode[aCache.size + 1]; aCache.wordboundary = new sal_Int32[aCache.size + 2]; } aCache.length = len; memcpy(aCache.contents, text + wordBoundary.startPos, len * sizeof(sal_Unicode)); *(aCache.contents + len) = 0x0000; // reset the wordboundary in cache memset(aCache.wordboundary, '\0', sizeof(sal_Int32)*(len + 2)); sal_Int32 i = 0; // loop variable while (aCache.wordboundary[i] < aCache.length) { len = 0; // look the continuous white space as one word and cashe it while (unicode::isWhiteSpace(text[wordBoundary.startPos + aCache.wordboundary[i] + len])) len ++; if (len == 0) { const sal_Unicode *str = text + wordBoundary.startPos + aCache.wordboundary[i]; sal_Int32 slen = aCache.length - aCache.wordboundary[i]; sal_Int16 type = 0, count = 0; for (;len == 0 && slen > 0; str++, slen--) { len = getLongestMatch(str, slen); if (len == 0) { if (!japaneseWordBreak) { len = 1; } else { if (count == 0) type = JapaneseCharType(*str); else if (type != JapaneseCharType(*str)) break; count++; } } } if (count) { aCache.wordboundary[i+1] = aCache.wordboundary[i] + count; i++; if (useCellBoundary) { sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + wordBoundary.startPos - 1]; if (cBoundary > 0) aCache.wordboundary[i] = cBoundary - wordBoundary.startPos; } } } if (len) { aCache.wordboundary[i+1] = aCache.wordboundary[i] + len; i++; if (useCellBoundary) { sal_Int32 cBoundary = cellBoundary[aCache.wordboundary[i] + wordBoundary.startPos - 1]; if (cBoundary > 0) aCache.wordboundary[i] = cBoundary - wordBoundary.startPos; } } } aCache.wordboundary[i + 1] = aCache.length + 1; return aCache; } Boundary SAL_CALL xdictionary::previousWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType) { // looking for the first non-whitespace character from anyPos while (unicode::isWhiteSpace(text[anyPos - 1])) anyPos --; return getWordBoundary(text, anyPos - 1, len, wordType, true); } Boundary SAL_CALL xdictionary::nextWord(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType) { boundary = getWordBoundary(text, anyPos, len, wordType, true); // looknig for the first non-whitespace character from anyPos anyPos = boundary.endPos; while (unicode::isWhiteSpace(text[anyPos])) anyPos ++; return getWordBoundary(text, anyPos, len, wordType, true); } Boundary SAL_CALL xdictionary::getWordBoundary(const sal_Unicode *text, sal_Int32 anyPos, sal_Int32 len, sal_Int16 wordType, sal_Bool bDirection) { if (anyPos >= len || anyPos < 0) { boundary.startPos = boundary.endPos = anyPos < 0 ? 0 : len; } else if (seekSegment(text, anyPos, len, boundary)) { // character in dict WordBreakCache& aCache = getCache(text, boundary); sal_Int32 i = 0; while (aCache.wordboundary[i] <= (sal_Int32)anyPos - boundary.startPos) i++; sal_Int32 startPos = aCache.wordboundary[i - 1]; // if bDirection is false if (!bDirection && startPos > 0 && startPos == (anyPos - boundary.startPos) && unicode::isWhiteSpace(text[anyPos - 1])) i--; boundary.endPos = aCache.wordboundary[i] + boundary.startPos; boundary.startPos += aCache.wordboundary[i - 1]; } else { boundary.startPos = anyPos++; boundary.endPos = anyPos < len ? anyPos : len; } if (wordType == WordType::WORD_COUNT) { // skip punctuation for word count. while (boundary.endPos < len && unicode::isPunctuation(text[boundary.endPos])) boundary.endPos++; } return boundary; } void SAL_CALL xdictionary::setCellBoundary(sal_Int32* cellArray) { useCellBoundary = sal_True; cellBoundary = cellArray; } } } } } <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <bh_util.hpp> #include <jitk/iterator.hpp> using namespace std; using namespace bohrium::jitk; namespace bohrium { namespace jitk { namespace iterator { BlockList::BlockList(const vector<Block> &block_list) { if (not block_list.empty()) { _bottom(block_list); } } BlockList::BlockList(const Block &block) { if (block.isInstr()) { _stack.push_back(make_pair(nullptr, &block)); } else { const vector<Block> &block_list = block.getLoop()._block_list; if (not block_list.empty()) { _bottom(block_list); } } } void BlockList::_bottom(const vector<Block> &block_list) { if (block_list.empty()) { throw runtime_error("BlockList::_bottom() - `block_list` is empty!"); } _stack.push_back(make_pair(&block_list, &block_list[0])); if (block_list[0].isInstr()) { _stack.push_back(make_pair(nullptr, &block_list[0])); } else { _bottom(block_list[0].getLoop()._block_list); } } void BlockList::increment() { if (_stack.empty()) { return; } auto &block_list = _stack.back().first; auto &block = _stack.back().second; if (block_list == nullptr) { _stack.resize(_stack.size() - 1); increment(); } else { // We use a while-loop here for the unlikely case where a child's block_list is empty while (true) { if (block == &block_list->back()) { _stack.resize(_stack.size() - 1); increment(); break; } else { ++block; if (block->isInstr()) { _stack.push_back(make_pair(nullptr, block)); break; } else { if (not block->getLoop()._block_list.empty()) { _bottom(block->getLoop()._block_list); break; } // If `block->getLoop()._block_list` is empty, we continue to next block item. } } } } } bool BlockList::equal(BlockList const &other) const { return this->_stack == other._stack; } InstrPtr const &BlockList::dereference() const { auto &block_list = _stack.back().first; auto &block = _stack.back().second; assert(block_list == nullptr); assert(block->isInstr()); return block->getInstr(); } BlockList::Range allInstr(const LoopB &loop) { BlockList end, begin(loop._block_list); return boost::make_iterator_range(begin, end); } BlockList::Range allInstr(const Block &block) { BlockList end, begin(block); return boost::make_iterator_range(begin, end); } BaseList::Range allBases(const bh_instruction &instr) { BaseList begin{instr.operand}, end{instr.operand.end()}; return boost::make_iterator_range(begin, end); } LocalInstrList::Range allLocalInstr(const std::vector<Block> &block_list) { LocalInstrList begin{block_list}, end{block_list.end()}; return boost::make_iterator_range(begin, end); } LocalInstrList::Range allLocalInstr(const LoopB &loop) { LocalInstrList begin{loop._block_list}, end{loop._block_list.end()}; return boost::make_iterator_range(begin, end); } } // iterator } // jitk } // bohrium <commit_msg>BlockList::equal(): fixed compile warning<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <bh_util.hpp> #include <jitk/iterator.hpp> using namespace std; using namespace bohrium::jitk; namespace bohrium { namespace jitk { namespace iterator { BlockList::BlockList(const vector<Block> &block_list) { if (not block_list.empty()) { _bottom(block_list); } } BlockList::BlockList(const Block &block) { if (block.isInstr()) { _stack.push_back(make_pair(nullptr, &block)); } else { const vector<Block> &block_list = block.getLoop()._block_list; if (not block_list.empty()) { _bottom(block_list); } } } void BlockList::_bottom(const vector<Block> &block_list) { if (block_list.empty()) { throw runtime_error("BlockList::_bottom() - `block_list` is empty!"); } _stack.push_back(make_pair(&block_list, &block_list[0])); if (block_list[0].isInstr()) { _stack.push_back(make_pair(nullptr, &block_list[0])); } else { _bottom(block_list[0].getLoop()._block_list); } } void BlockList::increment() { if (_stack.empty()) { return; } auto &block_list = _stack.back().first; auto &block = _stack.back().second; if (block_list == nullptr) { _stack.resize(_stack.size() - 1); increment(); } else { // We use a while-loop here for the unlikely case where a child's block_list is empty while (true) { if (block == &block_list->back()) { _stack.resize(_stack.size() - 1); increment(); break; } else { ++block; if (block->isInstr()) { _stack.push_back(make_pair(nullptr, block)); break; } else { if (not block->getLoop()._block_list.empty()) { _bottom(block->getLoop()._block_list); break; } // If `block->getLoop()._block_list` is empty, we continue to next block item. } } } } } bool BlockList::equal(BlockList const &other) const { return this->_stack == other._stack; } InstrPtr const &BlockList::dereference() const { auto &block = _stack.back().second; assert(_stack.back().first == nullptr); assert(block->isInstr()); return block->getInstr(); } BlockList::Range allInstr(const LoopB &loop) { BlockList end, begin(loop._block_list); return boost::make_iterator_range(begin, end); } BlockList::Range allInstr(const Block &block) { BlockList end, begin(block); return boost::make_iterator_range(begin, end); } BaseList::Range allBases(const bh_instruction &instr) { BaseList begin{instr.operand}, end{instr.operand.end()}; return boost::make_iterator_range(begin, end); } LocalInstrList::Range allLocalInstr(const std::vector<Block> &block_list) { LocalInstrList begin{block_list}, end{block_list.end()}; return boost::make_iterator_range(begin, end); } LocalInstrList::Range allLocalInstr(const LoopB &loop) { LocalInstrList begin{loop._block_list}, end{loop._block_list.end()}; return boost::make_iterator_range(begin, end); } } // iterator } // jitk } // bohrium <|endoftext|>
<commit_before>#include <string> #ifdef _WIN32 # include <windows.h> #else //POSIX # include <dlfcn.h> #endif #include "plugin_loader.h" //We don't *really* need this to be its own separate file, but i refuse to let //this code near the main product. bool load_plugin(std::string fname, const plugin_pipe &p) { #ifdef _WIN32 HMODULE obj=LoadLibrary(fname.c_str()); if (HMODULE==NULL) return false; FARPROC func=GetProcAddress(obj,"plugin_init"); if (func==NULL) return false; //FARPROC returns an int * by default, so cast it to void. This has //more parentheses than Lisp. (*(void __cdecl (*)(plugin_pipe))(func))(p); #else //POSIX //Open the object file whenever you get around to it, and with its own //local symbol table. void *obj=dlopen(fname.c_str(), RTLD_LAZY | RTLD_LOCAL); if (obj==NULL) return false; //The POSIX standard says void * must convert to a function pointer, //but the C standard does not, so add a cast to shut up the compiler. auto func=(void (*)(plugin_pipe))dlsym(obj, "plugin_init"); if (func==NULL) return false; //Finally initialize the plugin (*func)(p); #endif return true; } <commit_msg>Added important comments<commit_after>#include <string> #ifdef _WIN32 # include <windows.h> #else //POSIX # include <dlfcn.h> #endif #include "plugin_loader.h" //We don't *really* need this to be its own separate file, but i refuse to let //this code near the main product. bool load_plugin(std::string fname, const plugin_pipe &p) { #ifdef _WIN32 HMODULE obj=LoadLibrary(fname.c_str()); if (HMODULE==NULL) return false; FARPROC func=GetProcAddress(obj,"plugin_init"); if (func==NULL) return false; //FARPROC returns an int * by default, so cast it to void. This has //more parentheses than Lisp. (*(void __cdecl (*)(plugin_pipe))(func))(p); #else //POSIX //Open the object file whenever you get around to it, and with its own //local symbol table. void *obj=dlopen(fname.c_str(), RTLD_LAZY | RTLD_LOCAL); if (obj==NULL) return false; //The POSIX standard says void * must convert to a function pointer, //but the C standard does not, so add a cast to shut up the compiler. auto func=(void (*)(plugin_pipe))dlsym(obj, "plugin_init"); if (func==NULL) return false; //Finally initialize the plugin (*func)(p); //We should close the object here, but can't for technical reasons. //They're described in detail at: //https://github.com/m42a/Lirch/wiki/Stuff-That-Should-Be-Written-Down-Somewhere #endif return true; } <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation; either version 2.1 of the License, * * or (at your option) any later version. * * * * libcppa is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_SPAWN_OPTIONS_HPP #define CPPA_SPAWN_OPTIONS_HPP namespace cppa { /** * @ingroup ActorCreation * @{ */ /** * @brief Stores options passed to the @p spawn function family. */ #ifdef CPPA_DOCUMENTATION class spawn_options { }; #else enum class spawn_options : int { no_flags = 0x00, link_flag = 0x01, monitor_flag = 0x02, detach_flag = 0x04, hide_flag = 0x08, blocking_api_flag = 0x10, priority_aware_flag = 0x20 }; #endif #ifndef CPPA_DOCUMENTATION namespace { #endif /** * @brief Concatenates two {@link spawn_options}. * @relates spawn_options */ constexpr spawn_options operator+(const spawn_options& lhs, const spawn_options& rhs) { return static_cast<spawn_options>(static_cast<int>(lhs) | static_cast<int>(rhs)); } /** * @brief Denotes default settings. */ constexpr spawn_options no_spawn_options = spawn_options::no_flags; /** * @brief Causes @p spawn to call <tt>self->monitor(...)</tt> immediately * after the new actor was spawned. */ constexpr spawn_options monitored = spawn_options::monitor_flag; /** * @brief Causes @p spawn to call <tt>self->link_to(...)</tt> immediately * after the new actor was spawned. */ constexpr spawn_options linked = spawn_options::link_flag; /** * @brief Causes the new actor to opt out of the cooperative scheduling. */ constexpr spawn_options detached = spawn_options::detach_flag; /** * @brief Causes the runtime to ignore the new actor in * {@link await_all_others_done()}. */ constexpr spawn_options hidden = spawn_options::hide_flag; /** * @brief Causes the new actor to opt in to the blocking API of libcppa, * i.e., the actor uses a context-switching or thread-based backend * instead of the default event-based implementation. */ constexpr spawn_options blocking_api = spawn_options::blocking_api_flag; /** * @brief Causes the new actor to evaluate message priorities. * @note This implicitly causes the actor to run in its own thread. */ constexpr spawn_options priority_aware = spawn_options::priority_aware_flag + spawn_options::detach_flag; #ifndef CPPA_DOCUMENTATION } // namespace <anonymous> #endif /** * @brief Checks wheter @p haystack contains @p needle. * @relates spawn_options */ constexpr bool has_spawn_option(spawn_options haystack, spawn_options needle) { return (static_cast<int>(haystack) & static_cast<int>(needle)) != 0; } /** * @brief Checks wheter the {@link detached} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_detach_flag(spawn_options opts) { return has_spawn_option(opts, detached); } /** * @brief Checks wheter the {@link priority_aware} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_priority_aware_flag(spawn_options opts) { return has_spawn_option(opts, priority_aware); } /** * @brief Checks wheter the {@link hidden} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_hide_flag(spawn_options opts) { return has_spawn_option(opts, hidden); } /** * @brief Checks wheter the {@link linked} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_link_flag(spawn_options opts) { return has_spawn_option(opts, linked); } /** * @brief Checks wheter the {@link monitored} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_monitor_flag(spawn_options opts) { return has_spawn_option(opts, monitored); } /** * @brief Checks wheter the {@link blocking_api} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_blocking_api_flag(spawn_options opts) { return has_spawn_option(opts, blocking_api); } /** @} */ } // namespace cppa #endif // CPPA_SPAWN_OPTIONS_HPP <commit_msg>moved operator+(spawn_options) to cppa namespace<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation; either version 2.1 of the License, * * or (at your option) any later version. * * * * libcppa is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_SPAWN_OPTIONS_HPP #define CPPA_SPAWN_OPTIONS_HPP namespace cppa { /** * @ingroup ActorCreation * @{ */ /** * @brief Stores options passed to the @p spawn function family. */ #ifdef CPPA_DOCUMENTATION class spawn_options { }; #else enum class spawn_options : int { no_flags = 0x00, link_flag = 0x01, monitor_flag = 0x02, detach_flag = 0x04, hide_flag = 0x08, blocking_api_flag = 0x10, priority_aware_flag = 0x20 }; #endif /** * @brief Concatenates two {@link spawn_options}. * @relates spawn_options */ constexpr spawn_options operator+(const spawn_options& lhs, const spawn_options& rhs) { return static_cast<spawn_options>( static_cast<int>(lhs) | static_cast<int>(rhs)); } #ifndef CPPA_DOCUMENTATION namespace { #endif /** * @brief Denotes default settings. */ constexpr spawn_options no_spawn_options = spawn_options::no_flags; /** * @brief Causes @p spawn to call <tt>self->monitor(...)</tt> immediately * after the new actor was spawned. */ constexpr spawn_options monitored = spawn_options::monitor_flag; /** * @brief Causes @p spawn to call <tt>self->link_to(...)</tt> immediately * after the new actor was spawned. */ constexpr spawn_options linked = spawn_options::link_flag; /** * @brief Causes the new actor to opt out of the cooperative scheduling. */ constexpr spawn_options detached = spawn_options::detach_flag; /** * @brief Causes the runtime to ignore the new actor in * {@link await_all_others_done()}. */ constexpr spawn_options hidden = spawn_options::hide_flag; /** * @brief Causes the new actor to opt in to the blocking API of libcppa, * i.e., the actor uses a context-switching or thread-based backend * instead of the default event-based implementation. */ constexpr spawn_options blocking_api = spawn_options::blocking_api_flag; /** * @brief Causes the new actor to evaluate message priorities. * @note This implicitly causes the actor to run in its own thread. */ constexpr spawn_options priority_aware = spawn_options::priority_aware_flag + spawn_options::detach_flag; #ifndef CPPA_DOCUMENTATION } // namespace <anonymous> #endif /** * @brief Checks wheter @p haystack contains @p needle. * @relates spawn_options */ constexpr bool has_spawn_option(spawn_options haystack, spawn_options needle) { return (static_cast<int>(haystack) & static_cast<int>(needle)) != 0; } /** * @brief Checks wheter the {@link detached} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_detach_flag(spawn_options opts) { return has_spawn_option(opts, detached); } /** * @brief Checks wheter the {@link priority_aware} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_priority_aware_flag(spawn_options opts) { return has_spawn_option(opts, priority_aware); } /** * @brief Checks wheter the {@link hidden} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_hide_flag(spawn_options opts) { return has_spawn_option(opts, hidden); } /** * @brief Checks wheter the {@link linked} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_link_flag(spawn_options opts) { return has_spawn_option(opts, linked); } /** * @brief Checks wheter the {@link monitored} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_monitor_flag(spawn_options opts) { return has_spawn_option(opts, monitored); } /** * @brief Checks wheter the {@link blocking_api} flag is set in @p opts. * @relates spawn_options */ constexpr bool has_blocking_api_flag(spawn_options opts) { return has_spawn_option(opts, blocking_api); } /** @} */ } // namespace cppa #endif // CPPA_SPAWN_OPTIONS_HPP <|endoftext|>
<commit_before>#include "generator/road_access_generator.hpp" #include "generator/routing_helpers.hpp" #include "routing/road_access.hpp" #include "routing/road_access_serialization.hpp" #include "indexer/classificator.hpp" #include "indexer/feature.hpp" #include "indexer/feature_data.hpp" #include "indexer/features_vector.hpp" #include "coding/file_container.hpp" #include "coding/file_writer.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include "base/osm_id.hpp" #include <initializer_list> #include "defines.hpp" #include <algorithm> #include <utility> using namespace routing; using namespace std; namespace { char constexpr kDelim[] = " \t\r\n"; using TagMapping = routing::RoadAccessTagProcessor::TagMapping; TagMapping const kMotorCarTagMapping = { {OsmElement::Tag("motorcar", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("motorcar", "no"), RoadAccess::Type::No}, {OsmElement::Tag("motorcar", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("motorcar", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kMotorVehicleTagMapping = { {OsmElement::Tag("motor_vehicle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("motor_vehicle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("motor_vehicle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("motor_vehicle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kVehicleTagMapping = { {OsmElement::Tag("vehicle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("vehicle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("vehicle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("vehicle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kCarBarriersTagMapping = { {OsmElement::Tag("barrier", "block"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "bollard"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "chain"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "cycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "jersey_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "lift_gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "log"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "motorcycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "swing_gate"), RoadAccess::Type::Private}, }; TagMapping const kPedestrianTagMapping = { {OsmElement::Tag("foot", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("foot", "no"), RoadAccess::Type::No}, {OsmElement::Tag("foot", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("foot", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kBicycleTagMapping = { {OsmElement::Tag("bicycle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("bicycle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("bicycle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("bicycle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kBicycleBarriersTagMapping = { {OsmElement::Tag("barrier", "cycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "turnstile"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "kissing_gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "gate"), RoadAccess::Type::Private}, }; // Allow everything to keep transit section empty. We'll use pedestrian section for // transit + pedestrian combination. TagMapping const kTransitTagMapping = { {OsmElement::Tag("access", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "no"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "private"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "destination"), RoadAccess::Type::Yes}, }; TagMapping const kDefaultTagMapping = { {OsmElement::Tag("access", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "no"), RoadAccess::Type::No}, {OsmElement::Tag("access", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("access", "destination"), RoadAccess::Type::Destination}, }; bool ParseRoadAccess(string const & roadAccessPath, map<osm::Id, uint32_t> const & osmIdToFeatureId, FeaturesVector const & featuresVector, RoadAccessCollector::RoadAccessByVehicleType & roadAccessByVehicleType) { ifstream stream(roadAccessPath); if (!stream) { LOG(LWARNING, ("Could not open", roadAccessPath)); return false; } vector<uint32_t> privateRoads; map<uint32_t, RoadAccess::Type> featureType[static_cast<size_t>(VehicleType::Count)]; map<RoadPoint, RoadAccess::Type> pointType[static_cast<size_t>(VehicleType::Count)]; auto addFeature = [&](uint32_t featureId, VehicleType vehicleType, RoadAccess::Type roadAccessType, uint64_t osmId) { auto & m = featureType[static_cast<size_t>(vehicleType)]; auto const emplaceRes = m.emplace(featureId, roadAccessType); if (!emplaceRes.second && emplaceRes.first->second != roadAccessType) { LOG(LDEBUG, ("Duplicate road access info for OSM way", osmId, "vehicle:", vehicleType, "access is:", emplaceRes.first->second, "tried:", roadAccessType)); } }; auto addPoint = [&](RoadPoint const & point, VehicleType vehicleType, RoadAccess::Type roadAccessType) { auto & m = pointType[static_cast<size_t>(vehicleType)]; auto const emplaceRes = m.emplace(point, roadAccessType); if (!emplaceRes.second && emplaceRes.first->second != roadAccessType) { LOG(LDEBUG, ("Duplicate road access info for road point", point, "vehicle:", vehicleType, "access is:", emplaceRes.first->second, "tried:", roadAccessType)); } }; string line; for (uint32_t lineNo = 1;; ++lineNo) { if (!getline(stream, line)) break; strings::SimpleTokenizer iter(line, kDelim); if (!iter) { LOG(LERROR, ("Error when parsing road access: empty line", lineNo)); return false; } VehicleType vehicleType; FromString(*iter, vehicleType); ++iter; if (!iter) { LOG(LERROR, ("Error when parsing road access: no road access type at line", lineNo, "Line contents:", line)); return false; } RoadAccess::Type roadAccessType; FromString(*iter, roadAccessType); ++iter; uint64_t osmId; if (!iter || !strings::to_uint64(*iter, osmId)) { LOG(LERROR, ("Error when parsing road access: bad osm id at line", lineNo, "Line contents:", line)); return false; } ++iter; uint32_t pointIdx; if (!iter || !strings::to_uint(*iter, pointIdx)) { LOG(LERROR, ("Error when parsing road access: bad pointIdx at line", lineNo, "Line contents:", line)); return false; } ++iter; auto const it = osmIdToFeatureId.find(osm::Id::Way(osmId)); // Even though this osm element has a tag that is interesting for us, // we have not created a feature from it. Possible reasons: // no primary tag, unsupported type, etc. if (it == osmIdToFeatureId.cend()) continue; uint32_t const featureId = it->second; if (pointIdx == 0) addFeature(featureId, vehicleType, roadAccessType, osmId); else addPoint(RoadPoint(featureId, pointIdx - 1), vehicleType, roadAccessType); } for (size_t i = 0; i < static_cast<size_t>(VehicleType::Count); ++i) roadAccessByVehicleType[i].SetAccessTypes(move(featureType[i]), move(pointType[i])); return true; } // If |elem| has access tag from |mapping|, returns corresponding RoadAccess::Type. // Tags in |mapping| should be mutually exclusive. Caller is responsible for that. If there are // multiple access tags from |mapping| in |elem|, returns RoadAccess::Type for any of them. // Returns RoadAccess::Type::Count if |elem| has no access tags from |mapping|. RoadAccess::Type GetAccessTypeFromMapping(OsmElement const & elem, TagMapping const * mapping) { for (auto const & tag : elem.m_tags) { auto const it = mapping->find(tag); if (it != mapping->cend()) return it->second; } return RoadAccess::Type::Count; } } // namespace namespace routing { // RoadAccessTagProcessor -------------------------------------------------------------------------- RoadAccessTagProcessor::RoadAccessTagProcessor(VehicleType vehicleType) : m_vehicleType(vehicleType) { switch (vehicleType) { case VehicleType::Car: m_tagMappings.push_back(&kMotorCarTagMapping); m_tagMappings.push_back(&kMotorVehicleTagMapping); m_tagMappings.push_back(&kVehicleTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); // Apply barrier tags if we have no {vehicle = ...}, {access = ...} etc. m_tagMappings.push_back(&kCarBarriersTagMapping); break; case VehicleType::Pedestrian: m_tagMappings.push_back(&kPedestrianTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); break; case VehicleType::Bicycle: m_tagMappings.push_back(&kBicycleTagMapping); m_tagMappings.push_back(&kVehicleTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); // Apply barrier tags if we have no {bicycle = ...}, {access = ...} etc. m_tagMappings.push_back(&kBicycleBarriersTagMapping); break; case VehicleType::Transit: // Use kTransitTagMapping to keep transit section empty. We'll use pedestrian section for // transit + pedestrian combination. m_tagMappings.push_back(&kTransitTagMapping); break; case VehicleType::Count: CHECK(false, ("Bad vehicle type")); break; } } void RoadAccessTagProcessor::Process(OsmElement const & elem, ofstream & oss) { // We will proccess all nodes before ways because of o5m format: // all nodes are first, then all ways, then all relations. if (elem.type == OsmElement::EntityType::Node) { RoadAccess::Type accessType = GetAccessType(elem); if (accessType != RoadAccess::Type::Yes) m_barriers[elem.id] = accessType; return; } if (elem.type != OsmElement::EntityType::Way) return; // All feature tags. auto const accessType = GetAccessType(elem); if (accessType != RoadAccess::Type::Yes) oss << ToString(m_vehicleType) << " " << ToString(accessType) << " " << elem.id << 0 << endl; // Barrier tags. for (size_t pointIdx = 0; pointIdx < elem.m_nds.size(); ++pointIdx) { auto const it = m_barriers.find(elem.m_nds[pointIdx]); if (it == m_barriers.cend()) continue; // idx == 0 used as wildcard segment Idx, for nodes we store |pointIdx + 1| instead of |pointIdx|. oss << ToString(m_vehicleType) << " " << ToString(it->second) << " " << elem.id << " " << pointIdx + 1; } } RoadAccess::Type RoadAccessTagProcessor::GetAccessType(OsmElement const & elem) const { for (auto const tagMapping : m_tagMappings) { auto const accessType = GetAccessTypeFromMapping(elem, tagMapping); if (accessType != RoadAccess::Type::Count) return accessType; } return RoadAccess::Type::Yes; } // RoadAccessWriter ------------------------------------------------------------ RoadAccessWriter::RoadAccessWriter() { for (size_t i = 0; i < static_cast<size_t>(VehicleType::Count); ++i) m_tagProcessors.emplace_back(static_cast<VehicleType>(i)); } void RoadAccessWriter::Open(string const & filePath) { LOG(LINFO, ("Saving information about barriers and road access classes in osm id terms to", filePath)); m_stream.open(filePath, ofstream::out); if (!IsOpened()) LOG(LINFO, ("Cannot open file", filePath)); } void RoadAccessWriter::Process(OsmElement const & elem) { if (!IsOpened()) { LOG(LWARNING, ("Tried to write to a closed barriers writer")); return; } for (auto & p : m_tagProcessors) p.Process(elem, m_stream); } bool RoadAccessWriter::IsOpened() const { return m_stream && m_stream.is_open(); } // RoadAccessCollector ---------------------------------------------------------- RoadAccessCollector::RoadAccessCollector(string const & dataFilePath, string const & roadAccessPath, string const & osmIdsToFeatureIdsPath) { map<osm::Id, uint32_t> osmIdToFeatureId; if (!ParseOsmIdToFeatureIdMapping(osmIdsToFeatureIdsPath, osmIdToFeatureId)) { LOG(LWARNING, ("An error happened while parsing feature id to osm ids mapping from file:", osmIdsToFeatureIdsPath)); m_valid = false; return; } FeaturesVectorTest featuresVector(dataFilePath); RoadAccessCollector::RoadAccessByVehicleType roadAccessByVehicleType; if (!ParseRoadAccess(roadAccessPath, osmIdToFeatureId, featuresVector.GetVector(), roadAccessByVehicleType)) { LOG(LWARNING, ("An error happened while parsing road access from file:", roadAccessPath)); m_valid = false; return; } m_valid = true; m_roadAccessByVehicleType.swap(roadAccessByVehicleType); } // Functions ------------------------------------------------------------------ void BuildRoadAccessInfo(string const & dataFilePath, string const & roadAccessPath, string const & osmIdsToFeatureIdsPath) { LOG(LINFO, ("Generating road access info for", dataFilePath)); RoadAccessCollector collector(dataFilePath, roadAccessPath, osmIdsToFeatureIdsPath); if (!collector.IsValid()) { LOG(LWARNING, ("Unable to parse road access in osm terms")); return; } FilesContainerW cont(dataFilePath, FileWriter::OP_WRITE_EXISTING); FileWriter writer = cont.GetWriter(ROAD_ACCESS_FILE_TAG); RoadAccessSerializer::Serialize(writer, collector.GetRoadAccessAllTypes()); } } // namespace routing <commit_msg>Fix intermediate road access csv file format<commit_after>#include "generator/road_access_generator.hpp" #include "generator/routing_helpers.hpp" #include "routing/road_access.hpp" #include "routing/road_access_serialization.hpp" #include "indexer/classificator.hpp" #include "indexer/feature.hpp" #include "indexer/feature_data.hpp" #include "indexer/features_vector.hpp" #include "coding/file_container.hpp" #include "coding/file_writer.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include "base/osm_id.hpp" #include <initializer_list> #include "defines.hpp" #include <algorithm> #include <utility> using namespace routing; using namespace std; namespace { char constexpr kDelim[] = " \t\r\n"; using TagMapping = routing::RoadAccessTagProcessor::TagMapping; TagMapping const kMotorCarTagMapping = { {OsmElement::Tag("motorcar", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("motorcar", "no"), RoadAccess::Type::No}, {OsmElement::Tag("motorcar", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("motorcar", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kMotorVehicleTagMapping = { {OsmElement::Tag("motor_vehicle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("motor_vehicle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("motor_vehicle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("motor_vehicle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kVehicleTagMapping = { {OsmElement::Tag("vehicle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("vehicle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("vehicle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("vehicle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kCarBarriersTagMapping = { {OsmElement::Tag("barrier", "block"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "bollard"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "chain"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "cycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "jersey_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "lift_gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "log"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "motorcycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "swing_gate"), RoadAccess::Type::Private}, }; TagMapping const kPedestrianTagMapping = { {OsmElement::Tag("foot", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("foot", "no"), RoadAccess::Type::No}, {OsmElement::Tag("foot", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("foot", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kBicycleTagMapping = { {OsmElement::Tag("bicycle", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("bicycle", "no"), RoadAccess::Type::No}, {OsmElement::Tag("bicycle", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("bicycle", "destination"), RoadAccess::Type::Destination}, }; TagMapping const kBicycleBarriersTagMapping = { {OsmElement::Tag("barrier", "cycle_barrier"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "turnstile"), RoadAccess::Type::No}, {OsmElement::Tag("barrier", "kissing_gate"), RoadAccess::Type::Private}, {OsmElement::Tag("barrier", "gate"), RoadAccess::Type::Private}, }; // Allow everything to keep transit section empty. We'll use pedestrian section for // transit + pedestrian combination. TagMapping const kTransitTagMapping = { {OsmElement::Tag("access", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "no"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "private"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "destination"), RoadAccess::Type::Yes}, }; TagMapping const kDefaultTagMapping = { {OsmElement::Tag("access", "yes"), RoadAccess::Type::Yes}, {OsmElement::Tag("access", "no"), RoadAccess::Type::No}, {OsmElement::Tag("access", "private"), RoadAccess::Type::Private}, {OsmElement::Tag("access", "destination"), RoadAccess::Type::Destination}, }; bool ParseRoadAccess(string const & roadAccessPath, map<osm::Id, uint32_t> const & osmIdToFeatureId, FeaturesVector const & featuresVector, RoadAccessCollector::RoadAccessByVehicleType & roadAccessByVehicleType) { ifstream stream(roadAccessPath); if (!stream) { LOG(LWARNING, ("Could not open", roadAccessPath)); return false; } vector<uint32_t> privateRoads; map<uint32_t, RoadAccess::Type> featureType[static_cast<size_t>(VehicleType::Count)]; map<RoadPoint, RoadAccess::Type> pointType[static_cast<size_t>(VehicleType::Count)]; auto addFeature = [&](uint32_t featureId, VehicleType vehicleType, RoadAccess::Type roadAccessType, uint64_t osmId) { auto & m = featureType[static_cast<size_t>(vehicleType)]; auto const emplaceRes = m.emplace(featureId, roadAccessType); if (!emplaceRes.second && emplaceRes.first->second != roadAccessType) { LOG(LDEBUG, ("Duplicate road access info for OSM way", osmId, "vehicle:", vehicleType, "access is:", emplaceRes.first->second, "tried:", roadAccessType)); } }; auto addPoint = [&](RoadPoint const & point, VehicleType vehicleType, RoadAccess::Type roadAccessType) { auto & m = pointType[static_cast<size_t>(vehicleType)]; auto const emplaceRes = m.emplace(point, roadAccessType); if (!emplaceRes.second && emplaceRes.first->second != roadAccessType) { LOG(LDEBUG, ("Duplicate road access info for road point", point, "vehicle:", vehicleType, "access is:", emplaceRes.first->second, "tried:", roadAccessType)); } }; string line; for (uint32_t lineNo = 1;; ++lineNo) { if (!getline(stream, line)) break; strings::SimpleTokenizer iter(line, kDelim); if (!iter) { LOG(LERROR, ("Error when parsing road access: empty line", lineNo)); return false; } VehicleType vehicleType; FromString(*iter, vehicleType); ++iter; if (!iter) { LOG(LERROR, ("Error when parsing road access: no road access type at line", lineNo, "Line contents:", line)); return false; } RoadAccess::Type roadAccessType; FromString(*iter, roadAccessType); ++iter; uint64_t osmId; if (!iter || !strings::to_uint64(*iter, osmId)) { LOG(LERROR, ("Error when parsing road access: bad osm id at line", lineNo, "Line contents:", line)); return false; } ++iter; uint32_t pointIdx; if (!iter || !strings::to_uint(*iter, pointIdx)) { LOG(LERROR, ("Error when parsing road access: bad pointIdx at line", lineNo, "Line contents:", line)); return false; } ++iter; auto const it = osmIdToFeatureId.find(osm::Id::Way(osmId)); // Even though this osm element has a tag that is interesting for us, // we have not created a feature from it. Possible reasons: // no primary tag, unsupported type, etc. if (it == osmIdToFeatureId.cend()) continue; uint32_t const featureId = it->second; if (pointIdx == 0) addFeature(featureId, vehicleType, roadAccessType, osmId); else addPoint(RoadPoint(featureId, pointIdx - 1), vehicleType, roadAccessType); } for (size_t i = 0; i < static_cast<size_t>(VehicleType::Count); ++i) roadAccessByVehicleType[i].SetAccessTypes(move(featureType[i]), move(pointType[i])); return true; } // If |elem| has access tag from |mapping|, returns corresponding RoadAccess::Type. // Tags in |mapping| should be mutually exclusive. Caller is responsible for that. If there are // multiple access tags from |mapping| in |elem|, returns RoadAccess::Type for any of them. // Returns RoadAccess::Type::Count if |elem| has no access tags from |mapping|. RoadAccess::Type GetAccessTypeFromMapping(OsmElement const & elem, TagMapping const * mapping) { for (auto const & tag : elem.m_tags) { auto const it = mapping->find(tag); if (it != mapping->cend()) return it->second; } return RoadAccess::Type::Count; } } // namespace namespace routing { // RoadAccessTagProcessor -------------------------------------------------------------------------- RoadAccessTagProcessor::RoadAccessTagProcessor(VehicleType vehicleType) : m_vehicleType(vehicleType) { switch (vehicleType) { case VehicleType::Car: m_tagMappings.push_back(&kMotorCarTagMapping); m_tagMappings.push_back(&kMotorVehicleTagMapping); m_tagMappings.push_back(&kVehicleTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); // Apply barrier tags if we have no {vehicle = ...}, {access = ...} etc. m_tagMappings.push_back(&kCarBarriersTagMapping); break; case VehicleType::Pedestrian: m_tagMappings.push_back(&kPedestrianTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); break; case VehicleType::Bicycle: m_tagMappings.push_back(&kBicycleTagMapping); m_tagMappings.push_back(&kVehicleTagMapping); m_tagMappings.push_back(&kDefaultTagMapping); // Apply barrier tags if we have no {bicycle = ...}, {access = ...} etc. m_tagMappings.push_back(&kBicycleBarriersTagMapping); break; case VehicleType::Transit: // Use kTransitTagMapping to keep transit section empty. We'll use pedestrian section for // transit + pedestrian combination. m_tagMappings.push_back(&kTransitTagMapping); break; case VehicleType::Count: CHECK(false, ("Bad vehicle type")); break; } } void RoadAccessTagProcessor::Process(OsmElement const & elem, ofstream & oss) { // We will proccess all nodes before ways because of o5m format: // all nodes are first, then all ways, then all relations. if (elem.type == OsmElement::EntityType::Node) { RoadAccess::Type accessType = GetAccessType(elem); if (accessType != RoadAccess::Type::Yes) m_barriers[elem.id] = accessType; return; } if (elem.type != OsmElement::EntityType::Way) return; // All feature tags. auto const accessType = GetAccessType(elem); if (accessType != RoadAccess::Type::Yes) oss << ToString(m_vehicleType) << " " << ToString(accessType) << " " << elem.id << " " << 0 /* wildcard segment Idx */ << endl; // Barrier tags. for (size_t pointIdx = 0; pointIdx < elem.m_nds.size(); ++pointIdx) { auto const it = m_barriers.find(elem.m_nds[pointIdx]); if (it == m_barriers.cend()) continue; // idx == 0 used as wildcard segment Idx, for nodes we store |pointIdx + 1| instead of |pointIdx|. oss << ToString(m_vehicleType) << " " << ToString(it->second) << " " << elem.id << " " << pointIdx + 1 << endl; } } RoadAccess::Type RoadAccessTagProcessor::GetAccessType(OsmElement const & elem) const { for (auto const tagMapping : m_tagMappings) { auto const accessType = GetAccessTypeFromMapping(elem, tagMapping); if (accessType != RoadAccess::Type::Count) return accessType; } return RoadAccess::Type::Yes; } // RoadAccessWriter ------------------------------------------------------------ RoadAccessWriter::RoadAccessWriter() { for (size_t i = 0; i < static_cast<size_t>(VehicleType::Count); ++i) m_tagProcessors.emplace_back(static_cast<VehicleType>(i)); } void RoadAccessWriter::Open(string const & filePath) { LOG(LINFO, ("Saving information about barriers and road access classes in osm id terms to", filePath)); m_stream.open(filePath, ofstream::out); if (!IsOpened()) LOG(LINFO, ("Cannot open file", filePath)); } void RoadAccessWriter::Process(OsmElement const & elem) { if (!IsOpened()) { LOG(LWARNING, ("Tried to write to a closed barriers writer")); return; } for (auto & p : m_tagProcessors) p.Process(elem, m_stream); } bool RoadAccessWriter::IsOpened() const { return m_stream && m_stream.is_open(); } // RoadAccessCollector ---------------------------------------------------------- RoadAccessCollector::RoadAccessCollector(string const & dataFilePath, string const & roadAccessPath, string const & osmIdsToFeatureIdsPath) { map<osm::Id, uint32_t> osmIdToFeatureId; if (!ParseOsmIdToFeatureIdMapping(osmIdsToFeatureIdsPath, osmIdToFeatureId)) { LOG(LWARNING, ("An error happened while parsing feature id to osm ids mapping from file:", osmIdsToFeatureIdsPath)); m_valid = false; return; } FeaturesVectorTest featuresVector(dataFilePath); RoadAccessCollector::RoadAccessByVehicleType roadAccessByVehicleType; if (!ParseRoadAccess(roadAccessPath, osmIdToFeatureId, featuresVector.GetVector(), roadAccessByVehicleType)) { LOG(LWARNING, ("An error happened while parsing road access from file:", roadAccessPath)); m_valid = false; return; } m_valid = true; m_roadAccessByVehicleType.swap(roadAccessByVehicleType); } // Functions ------------------------------------------------------------------ void BuildRoadAccessInfo(string const & dataFilePath, string const & roadAccessPath, string const & osmIdsToFeatureIdsPath) { LOG(LINFO, ("Generating road access info for", dataFilePath)); RoadAccessCollector collector(dataFilePath, roadAccessPath, osmIdsToFeatureIdsPath); if (!collector.IsValid()) { LOG(LWARNING, ("Unable to parse road access in osm terms")); return; } FilesContainerW cont(dataFilePath, FileWriter::OP_WRITE_EXISTING); FileWriter writer = cont.GetWriter(ROAD_ACCESS_FILE_TAG); RoadAccessSerializer::Serialize(writer, collector.GetRoadAccessAllTypes()); } } // namespace routing <|endoftext|>
<commit_before> #include "geometry/cartesian_product.hpp" #include <algorithm> #include "quantities/named_quantities.hpp" #include "quantities/tuples.hpp" namespace principia { namespace geometry { namespace internal_cartesian_product { using quantities::Apply2; template<typename LTuple, typename RTuple, int... indices> struct CartesianProductAdditiveGroup<LTuple, RTuple, std::integer_sequence<int, indices...>> { // The types of the result of addition and subtraction, with suitable // specializations for the void case of Apply2. template<typename L, typename R> struct TypesGenerator { using Sum = quantities::Sum<L, R>; using Difference = quantities::Difference<L, R>; }; template<typename L> struct TypesGenerator<L, void> { using Sum = L; using Difference = L; }; template<typename R> struct TypesGenerator<void, R> { using Sum = R; using Difference = R; }; // Aliases for use as the transform in Apply2. template<typename L, typename R> using Sum = typename TypesGenerator<L, R>::Sum; template<typename L, typename R> using Difference = typename TypesGenerator<L, R>::Difference; static constexpr Apply2<Sum, LTuple, RTuple> Add( LTuple const& left, RTuple const& right); static constexpr Apply2<Difference, LTuple, RTuple> Subtract( LTuple const& left, RTuple const& right); }; template<typename LTuple, typename RTuple, int... indices> constexpr auto CartesianProductAdditiveGroup< LTuple, RTuple, std::integer_sequence<int, indices...>>::Add(LTuple const& left, RTuple const& right) -> Apply2<Sum, LTuple, RTuple> { return {( indices < std::min(std::tuple_size_v<LTuple>, std::tuple_size_v<RTuple>) ? std::get<indices>(left) + std::get<indices>(right) : indices < std::tuple_size_v<LTuple> ? std::get<indices>(left) : std::get<indices>(right))...}; } template<typename LTuple, typename RTuple, int... indices> constexpr auto CartesianProductAdditiveGroup< LTuple, RTuple, std::integer_sequence<int, indices...>>::Subtract(LTuple const& left, RTuple const& right) -> Apply2<Difference, LTuple, RTuple> { return { (indices < std::min(std::tuple_size_v<LTuple>, std::tuple_size_v<RTuple>) ? std::get<indices>(left) - std::get<indices>(right) : indices < std::tuple_size_v<LTuple> ? std::get<indices>(left) : -std::get<indices>(right))...}; } } // namespace internal_cartesian_product } // namespace geometry } // namespace principia <commit_msg>Use conditionals.<commit_after> #include "geometry/cartesian_product.hpp" #include <algorithm> #include <type_traits> #include "quantities/named_quantities.hpp" #include "quantities/tuples.hpp" namespace principia { namespace geometry { namespace internal_cartesian_product { using quantities::Apply2; template<typename LTuple, typename RTuple, int... indices> struct CartesianProductAdditiveGroup<LTuple, RTuple, std::integer_sequence<int, indices...>> { // The types of the result of addition and subtraction, with suitable // checks for the void case of Apply2. template<typename L, typename R> using Sum = std::conditional_t<std::is_void_v<L>, R, std::conditional_t<std::is_void_v<R>, L, quantities::Sum<L, R>>>; template<typename L, typename R> using Difference = std::conditional_t<std::is_void_v<L>, R, std::conditional_t<std::is_void_v<R>, L, quantities::Difference<L, R>>>; static constexpr Apply2<Sum, LTuple, RTuple> Add( LTuple const& left, RTuple const& right); static constexpr Apply2<Difference, LTuple, RTuple> Subtract( LTuple const& left, RTuple const& right); }; template<typename LTuple, typename RTuple, int... indices> constexpr auto CartesianProductAdditiveGroup< LTuple, RTuple, std::integer_sequence<int, indices...>>::Add(LTuple const& left, RTuple const& right) -> Apply2<Sum, LTuple, RTuple> { return {( indices < std::min(std::tuple_size_v<LTuple>, std::tuple_size_v<RTuple>) ? std::get<indices>(left) + std::get<indices>(right) : indices < std::tuple_size_v<LTuple> ? std::get<indices>(left) : std::get<indices>(right))...}; } template<typename LTuple, typename RTuple, int... indices> constexpr auto CartesianProductAdditiveGroup< LTuple, RTuple, std::integer_sequence<int, indices...>>::Subtract(LTuple const& left, RTuple const& right) -> Apply2<Difference, LTuple, RTuple> { return { (indices < std::min(std::tuple_size_v<LTuple>, std::tuple_size_v<RTuple>) ? std::get<indices>(left) - std::get<indices>(right) : indices < std::tuple_size_v<LTuple> ? std::get<indices>(left) : -std::get<indices>(right))...}; } } // namespace internal_cartesian_product } // namespace geometry } // namespace principia <|endoftext|>
<commit_before>// STL #include <iostream> #include <fstream> #include <algorithm> #include <iterator> // Boost #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/scoped_ptr.hpp> // Local #include "pyp-topics.hh" #include "corpus.hh" #include "contexts_corpus.hh" #include "gzstream.hh" #include "mt19937ar.h" static const char *REVISION = "$Revision: 0.1 $"; // Namespaces using namespace boost; using namespace boost::program_options; using namespace std; int main(int argc, char **argv) { std::cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n"; std::cout << REVISION << '\n' << std::endl; //////////////////////////////////////////////////////////////////////////////////////////// // Command line processing variables_map vm; // Command line processing { options_description cmdline_options("Allowed options"); cmdline_options.add_options() ("help,h", "print help message") ("data,d", value<string>(), "file containing the documents and context terms") ("topics,t", value<int>()->default_value(50), "number of topics") ("document-topics-out,o", value<string>(), "file to write the document topics to") ("topic-words-out,w", value<string>(), "file to write the topic word distribution to") ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data") ("backoff-type", value<string>(), "backoff type: none|simple") ; store(parse_command_line(argc, argv, cmdline_options), vm); notify(vm); if (vm.count("help")) { cout << cmdline_options << "\n"; return 1; } } //////////////////////////////////////////////////////////////////////////////////////////// if (!vm.count("data")) { cerr << "Please specify a file containing the data." << endl; return 1; } // seed the random number generator //mt_init_genrand(time(0)); PYPTopics model(vm["topics"].as<int>()); // read the data BackoffGenerator* backoff_gen=0; if (vm.count("backoff-type")) { if (vm["backoff-type"].as<std::string>() == "none") { backoff_gen = 0; } else if (vm["backoff-type"].as<std::string>() == "simple") { backoff_gen = new SimpleBackoffGenerator(); } else { std::cerr << "Backoff type (--backoff-type) must be one of none|simple." << std::endl; return(1); } } ContextsCorpus contexts_corpus; contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen); model.set_backoff(contexts_corpus.backoff_index()); if (backoff_gen) delete backoff_gen; // train the sampler model.sample(contexts_corpus, vm["samples"].as<int>()); if (vm.count("document-topics-out")) { ogzstream documents_out(vm["document-topics-out"].as<string>().c_str()); int document_id=0; for (Corpus::const_iterator corpusIt=contexts_corpus.begin(); corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) { std::vector<int> unique_terms; for (Document::const_iterator docIt=corpusIt->begin(); docIt != corpusIt->end(); ++docIt) { if (unique_terms.empty() || *docIt != unique_terms.back()) unique_terms.push_back(*docIt); } documents_out << contexts_corpus.key(document_id) << '\t'; for (std::vector<int>::const_iterator termIt=unique_terms.begin(); termIt != unique_terms.end(); ++termIt) { if (termIt != unique_terms.begin()) documents_out << " ||| "; std::vector<std::string> strings = contexts_corpus.context2string(*termIt); std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(documents_out, " ")); documents_out << "||| C=" << model.max(document_id, *termIt); } documents_out << std::endl; } documents_out.close(); } if (vm.count("topic-words-out")) { ogzstream topics_out(vm["topic-words-out"].as<string>().c_str()); model.print_topic_terms(topics_out); topics_out.close(); } std::cout << std::endl; return 0; } <commit_msg>rev string<commit_after>// STL #include <iostream> #include <fstream> #include <algorithm> #include <iterator> // Boost #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/scoped_ptr.hpp> // Local #include "pyp-topics.hh" #include "corpus.hh" #include "contexts_corpus.hh" #include "gzstream.hh" #include "mt19937ar.h" static const char *REVISION = "$Rev$"; // Namespaces using namespace boost; using namespace boost::program_options; using namespace std; int main(int argc, char **argv) { std::cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n"; std::cout << REVISION << '\n' << std::endl; //////////////////////////////////////////////////////////////////////////////////////////// // Command line processing variables_map vm; // Command line processing { options_description cmdline_options("Allowed options"); cmdline_options.add_options() ("help,h", "print help message") ("data,d", value<string>(), "file containing the documents and context terms") ("topics,t", value<int>()->default_value(50), "number of topics") ("document-topics-out,o", value<string>(), "file to write the document topics to") ("topic-words-out,w", value<string>(), "file to write the topic word distribution to") ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data") ("backoff-type", value<string>(), "backoff type: none|simple") ; store(parse_command_line(argc, argv, cmdline_options), vm); notify(vm); if (vm.count("help")) { cout << cmdline_options << "\n"; return 1; } } //////////////////////////////////////////////////////////////////////////////////////////// if (!vm.count("data")) { cerr << "Please specify a file containing the data." << endl; return 1; } // seed the random number generator //mt_init_genrand(time(0)); PYPTopics model(vm["topics"].as<int>()); // read the data BackoffGenerator* backoff_gen=0; if (vm.count("backoff-type")) { if (vm["backoff-type"].as<std::string>() == "none") { backoff_gen = 0; } else if (vm["backoff-type"].as<std::string>() == "simple") { backoff_gen = new SimpleBackoffGenerator(); } else { std::cerr << "Backoff type (--backoff-type) must be one of none|simple." << std::endl; return(1); } } ContextsCorpus contexts_corpus; contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen); model.set_backoff(contexts_corpus.backoff_index()); if (backoff_gen) delete backoff_gen; // train the sampler model.sample(contexts_corpus, vm["samples"].as<int>()); if (vm.count("document-topics-out")) { ogzstream documents_out(vm["document-topics-out"].as<string>().c_str()); int document_id=0; for (Corpus::const_iterator corpusIt=contexts_corpus.begin(); corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) { std::vector<int> unique_terms; for (Document::const_iterator docIt=corpusIt->begin(); docIt != corpusIt->end(); ++docIt) { if (unique_terms.empty() || *docIt != unique_terms.back()) unique_terms.push_back(*docIt); } documents_out << contexts_corpus.key(document_id) << '\t'; for (std::vector<int>::const_iterator termIt=unique_terms.begin(); termIt != unique_terms.end(); ++termIt) { if (termIt != unique_terms.begin()) documents_out << " ||| "; std::vector<std::string> strings = contexts_corpus.context2string(*termIt); std::copy(strings.begin(), strings.end(), std::ostream_iterator<std::string>(documents_out, " ")); documents_out << "||| C=" << model.max(document_id, *termIt); } documents_out << std::endl; } documents_out.close(); } if (vm.count("topic-words-out")) { ogzstream topics_out(vm["topic-words-out"].as<string>().c_str()); model.print_topic_terms(topics_out); topics_out.close(); } std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>// STL #include <iostream> #include <fstream> #include <algorithm> #include <iterator> // Boost #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/scoped_ptr.hpp> // Local #include "pyp-topics.hh" #include "corpus.hh" #include "contexts_corpus.hh" #include "gzstream.hh" #include "mt19937ar.h" static const char *REVISION = "$Rev$"; // Namespaces using namespace boost; using namespace boost::program_options; using namespace std; int main(int argc, char **argv) { cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n"; cout << REVISION << '\n' <<endl; //////////////////////////////////////////////////////////////////////////////////////////// // Command line processing variables_map vm; // Command line processing { options_description cmdline_options("Allowed options"); cmdline_options.add_options() ("help,h", "print help message") ("data,d", value<string>(), "file containing the documents and context terms") ("topics,t", value<int>()->default_value(50), "number of topics") ("document-topics-out,o", value<string>(), "file to write the document topics to") ("default-topics-out", value<string>(), "file to write default term topic assignments.") ("topic-words-out,w", value<string>(), "file to write the topic word distribution to") ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data") ("backoff-type", value<string>(), "backoff type: none|simple") ("filter-singleton-contexts", "filter singleton contexts") ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.") ; store(parse_command_line(argc, argv, cmdline_options), vm); notify(vm); if (vm.count("help")) { cout << cmdline_options << "\n"; return 1; } } //////////////////////////////////////////////////////////////////////////////////////////// if (!vm.count("data")) { cerr << "Please specify a file containing the data." << endl; return 1; } // seed the random number generator //mt_init_genrand(time(0)); PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics")); // read the data BackoffGenerator* backoff_gen=0; if (vm.count("backoff-type")) { if (vm["backoff-type"].as<std::string>() == "none") { backoff_gen = 0; } else if (vm["backoff-type"].as<std::string>() == "simple") { backoff_gen = new SimpleBackoffGenerator(); } else { cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl; return(1); } } ContextsCorpus contexts_corpus; contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts")); model.set_backoff(contexts_corpus.backoff_index()); if (backoff_gen) delete backoff_gen; // train the sampler model.sample(contexts_corpus, vm["samples"].as<int>()); if (vm.count("document-topics-out")) { ogzstream documents_out(vm["document-topics-out"].as<string>().c_str()); int document_id=0; map<int,int> all_terms; for (Corpus::const_iterator corpusIt=contexts_corpus.begin(); corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) { vector<int> unique_terms; for (Document::const_iterator docIt=corpusIt->begin(); docIt != corpusIt->end(); ++docIt) { if (unique_terms.empty() || *docIt != unique_terms.back()) unique_terms.push_back(*docIt); } documents_out << contexts_corpus.key(document_id) << '\t'; for (std::vector<int>::const_iterator termIt=unique_terms.begin(); termIt != unique_terms.end(); ++termIt) { if (termIt != unique_terms.begin()) documents_out << " ||| "; vector<std::string> strings = contexts_corpus.context2string(*termIt); copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " ")); documents_out << "||| C=" << model.max(document_id, *termIt); // increment this terms frequency pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*termIt,1)); if (!insert_result.second) insert_result.first++; } documents_out <<endl; } documents_out.close(); ofstream default_topics(vm["default-topics-out"].as<string>().c_str()); default_topics << model.max_topic() <<endl; for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) { vector<std::string> strings = contexts_corpus.context2string(termIt->first); default_topics << model.max(-1, termIt->first) << " ||| " << termIt->second << " ||| "; copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " ")); default_topics <<endl; } } if (vm.count("topic-words-out")) { ogzstream topics_out(vm["topic-words-out"].as<string>().c_str()); model.print_topic_terms(topics_out); topics_out.close(); } cout <<endl; return 0; } <commit_msg><commit_after>// STL #include <iostream> #include <fstream> #include <algorithm> #include <iterator> // Boost #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/scoped_ptr.hpp> // Local #include "pyp-topics.hh" #include "corpus.hh" #include "contexts_corpus.hh" #include "gzstream.hh" #include "mt19937ar.h" static const char *REVISION = "$Rev$"; // Namespaces using namespace boost; using namespace boost::program_options; using namespace std; int main(int argc, char **argv) { cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n"; cout << REVISION << '\n' <<endl; //////////////////////////////////////////////////////////////////////////////////////////// // Command line processing variables_map vm; // Command line processing { options_description cmdline_options("Allowed options"); cmdline_options.add_options() ("help,h", "print help message") ("data,d", value<string>(), "file containing the documents and context terms") ("topics,t", value<int>()->default_value(50), "number of topics") ("document-topics-out,o", value<string>(), "file to write the document topics to") ("default-topics-out", value<string>(), "file to write default term topic assignments.") ("topic-words-out,w", value<string>(), "file to write the topic word distribution to") ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data") ("backoff-type", value<string>(), "backoff type: none|simple") ("filter-singleton-contexts", "filter singleton contexts") ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.") ; store(parse_command_line(argc, argv, cmdline_options), vm); notify(vm); if (vm.count("help")) { cout << cmdline_options << "\n"; return 1; } } //////////////////////////////////////////////////////////////////////////////////////////// if (!vm.count("data")) { cerr << "Please specify a file containing the data." << endl; return 1; } // seed the random number generator //mt_init_genrand(time(0)); PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics")); // read the data BackoffGenerator* backoff_gen=0; if (vm.count("backoff-type")) { if (vm["backoff-type"].as<std::string>() == "none") { backoff_gen = 0; } else if (vm["backoff-type"].as<std::string>() == "simple") { backoff_gen = new SimpleBackoffGenerator(); } else { cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl; return(1); } } ContextsCorpus contexts_corpus; contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts")); model.set_backoff(contexts_corpus.backoff_index()); if (backoff_gen) delete backoff_gen; // train the sampler model.sample(contexts_corpus, vm["samples"].as<int>()); if (vm.count("document-topics-out")) { ogzstream documents_out(vm["document-topics-out"].as<string>().c_str()); int document_id=0; map<int,int> all_terms; for (Corpus::const_iterator corpusIt=contexts_corpus.begin(); corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) { vector<int> unique_terms; for (Document::const_iterator docIt=corpusIt->begin(); docIt != corpusIt->end(); ++docIt) { if (unique_terms.empty() || *docIt != unique_terms.back()) unique_terms.push_back(*docIt); } documents_out << contexts_corpus.key(document_id) << '\t'; for (std::vector<int>::const_iterator termIt=unique_terms.begin(); termIt != unique_terms.end(); ++termIt) { if (termIt != unique_terms.begin()) documents_out << " ||| "; vector<std::string> strings = contexts_corpus.context2string(*termIt); copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " ")); documents_out << "||| C=" << model.max(document_id, *termIt); // increment this terms frequency pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*termIt,1)); if (!insert_result.second) //insert_result.first++; all_terms[*termIt] += 1; } documents_out <<endl; } documents_out.close(); ofstream default_topics(vm["default-topics-out"].as<string>().c_str()); default_topics << model.max_topic() <<endl; for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) { vector<std::string> strings = contexts_corpus.context2string(termIt->first); default_topics << model.max(-1, termIt->first) << " ||| " << termIt->second << " ||| "; copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " ")); default_topics <<endl; } } if (vm.count("topic-words-out")) { ogzstream topics_out(vm["topic-words-out"].as<string>().c_str()); model.print_topic_terms(topics_out); topics_out.close(); } cout <<endl; return 0; } <|endoftext|>
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@webzone.net) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../../src/gnelib.h" class TimeClass : public TimerCallback { public: TimeClass(int x2, int y2, std::string ourName) : lasttime(clock()), callNum(0), x(x2), y(y2), name(ourName) {} virtual ~TimeClass() {} void timerCallback() { clock_t finish = clock(); float napTime = (float)(finish - lasttime) / CLOCKS_PER_SEC; lasttime = finish; Console::mlprintf(x, y, "(%i)Hello, I'm %s! change: %f", callNum, name.c_str(), napTime); callNum++; } private: clock_t lasttime; int callNum; int x, y; std::string name; }; int main() { GNE::init(NL_IP, atexit); Console::init(atexit); Time t(0, 1000000); Console::mprintf("%is, %ius\n", t.getSec(), t.getuSec()); t.setuSec(1000000); Console::mprintf("%is, %ius\n", t.getSec(), t.getuSec()); t.setSec(5); Console::mprintf("%is, %ius\n", t.getSec(), t.getuSec()); t = t + Time(3, 5500000); Console::mprintf("%is, %ius\n", t.getSec(), t.getuSec()); Timer t1(new TimeClass(3, 8, "Bob"), 1000); Timer t2(new TimeClass(5, 10, "Sally"), 1250); Timer t3(new TimeClass(1, 12, "Joe"), 200); t1.startTimer(); assert(t1.isRunning()); t2.startTimer(); assert(t2.isRunning()); t3.startTimer(); assert(t3.isRunning()); Thread::sleep(4000); t1.stopTimer(); t2.stopTimer(); t3.stopTimer(); return 0; }<commit_msg>User decides when to quit the timer program now.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@webzone.net) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "../../src/gnelib.h" class TimeClass : public TimerCallback { public: TimeClass(int x2, int y2, std::string ourName) : lastTime(Timer::getCurrentTime()), callNum(0), x(x2), y(y2), name(ourName) {} virtual ~TimeClass() {} void timerCallback() { Time currTime = Timer::getCurrentTime(); Time diffTime = currTime - lastTime; lastTime = currTime; Console::mlprintf(x, y, "(%i)Hello, I'm %s! change: %ius", callNum, name.c_str(), diffTime.getTotaluSec()); callNum++; } private: Time lastTime; int callNum; int x, y; std::string name; }; int main() { GNE::init(NL_IP, atexit); Console::init(atexit); //Doing some tests on Time class Console::mprintf("Time class tests:\n"); Time t(0, 1000000); Console::mprintf("%is, %ius\n", t.getSec(), t.getuSec()); t += 1000001; //add a little over one second Console::mprintf("%is, %ius\n", t.getSec(), t.getuSec()); t.setSec(5); Console::mprintf("%is, %ius\n", t.getSec(), t.getuSec()); t = t + Time(3, 5500000); Console::mprintf("%is, %ius\n", t.getSec(), t.getuSec()); Console::mprintf("Timer class tests, press a key to quit:\n"); //Create the timers Timer t1(new TimeClass(3, 8, "Bob"), 1000); Timer t2(new TimeClass(5, 10, "Sally"), 1250); Timer t3(new TimeClass(1, 12, "Joe"), 200); //Start the timers t1.startTimer(); assert(t1.isRunning()); t2.startTimer(); assert(t2.isRunning()); t3.startTimer(); assert(t3.isRunning()); while(!Console::kbhit()) { //Wait for keypress Thread::sleep(100); //sleep to give up the CPU for a bit. } Console::mlprintf(0, 14, "Shutting down timers, please wait..."); t1.stopTimer(); t2.stopTimer(); t3.stopTimer(); return 0; }<|endoftext|>
<commit_before>/********************************************************************* * * Copyright 2012 the original author or authors. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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<stdio.h> #include<time.h> #include<fstream> #include<sstream> #include<chrono> #include<boost/filesystem.hpp> #include<wordexp.h> #include<dirent.h> #include<sys/ioctl.h> #include<fcntl.h> #include<errno.h> #include<mutex> #include<ros/ros.h> #include<rospilot/CaptureImage.h> #include<rospilot/Resolutions.h> #include<rospilot/VisionTargets.h> #include<std_srvs/Empty.h> #include<sensor_msgs/CompressedImage.h> #include<background_image_sink.h> #include<ptp.h> #include<usb_camera.h> #include<people_detector.h> #include<video_recorder.h> #include<transcoders.h> #include<resizer.h> #include<h264_server.h> extern "C" { #include <linux/videodev2.h> } namespace rospilot { static int ffmpegLockManager(void **mtx, enum AVLockOp op) { switch(op) { case AV_LOCK_CREATE: *mtx = new std::mutex(); if(!*mtx) return 1; return 0; case AV_LOCK_OBTAIN: ((std::mutex *) *mtx)->lock(); return 0; case AV_LOCK_RELEASE: ((std::mutex *) *mtx)->unlock(); return 0; case AV_LOCK_DESTROY: delete (std::mutex *) *mtx; *mtx = nullptr; return 0; } return 1; } using namespace std::chrono; class CameraNode { private: ros::NodeHandle node; // NOTE: We don't need to guard this with a mutex, because callbacks // are called in spinOnce() in the main thread BaseCamera *camera = nullptr; JpegDecoder *jpegDecoder = nullptr; SoftwareVideoRecorder *videoRecorder = nullptr; BackgroundImageSink *liveStream = nullptr; BackgroundImageSink *recorder = nullptr; BackgroundImageSink *detector = nullptr; H264Server h264Server; PeopleDetector *peopleDetector = nullptr; ros::Publisher resolutionsTopic; ros::Publisher imagePub; ros::Publisher detectedPeopleTopic; ros::ServiceServer captureServiceServer; ros::ServiceServer startRecordServiceServer; ros::ServiceServer stopRecordServiceServer; std::string videoDevice; std::string mfcPath; std::string mediaPath; int cameraWidth; int cameraHeight; int framerate; bool detectorEnabled = false; sensor_msgs::CompressedImage image; private: bool sendPreview() { if(camera != nullptr && camera->getLiveImage(&image)) { bool keyFrame = false; bool transcodedSuccessfully = false; imagePub.publish(image); jpegDecoder->decodeInPlace(&image); liveStream->addFrame(&image); recorder->addFrame(&image); if (detector != nullptr) { detector->addFrame(&image); } return true; } return false; } void initCameraAndEncoders() { if (camera != nullptr) { delete camera; } camera = createCamera(); resolutionsTopic.publish(camera->getSupportedResolutions()); PixelFormat pixelFormat = PIX_FMT_YUV420P; H264Settings recordingH264Settings; recordingH264Settings.height = cameraHeight; recordingH264Settings.width = cameraWidth; recordingH264Settings.level = 40; recordingH264Settings.gop_size = 30; recordingH264Settings.zero_latency = false; recordingH264Settings.profile = HIGH; recordingH264Settings.height = cameraHeight; recordingH264Settings.width = cameraWidth; recordingH264Settings.bit_rate = 4 * cameraWidth * cameraHeight; double aspectRatio = cameraHeight / (double) cameraWidth; H264Settings liveH264Settings; liveH264Settings.height = (int) (aspectRatio * 640); liveH264Settings.width = 640; liveH264Settings.level = 41; liveH264Settings.gop_size = 12; liveH264Settings.bit_rate = 1000 * 1000; liveH264Settings.zero_latency = true; liveH264Settings.profile = CONSTRAINED_BASELINE; if (jpegDecoder != nullptr) { delete jpegDecoder; } jpegDecoder = new TurboJpegDecoder(cameraWidth, cameraHeight, pixelFormat); if (liveStream != nullptr) { delete liveStream; } Resizer *resizer = new Resizer( cameraWidth, cameraHeight, liveH264Settings.width, liveH264Settings.height, pixelFormat); liveStream = new BackgroundImageSink( &h264Server, createEncoder(liveH264Settings), resizer); if (videoRecorder != nullptr) { delete videoRecorder; } videoRecorder = new SoftwareVideoRecorder(pixelFormat, recordingH264Settings, mediaPath); if (recorder != nullptr) { delete recorder; } recorder = new BackgroundImageSink( videoRecorder, createEncoder(recordingH264Settings), nullptr ); node.param("detector_enabled", detectorEnabled, false); if (detector != nullptr) { delete detector; detector = nullptr; } if (peopleDetector != nullptr) { delete peopleDetector; peopleDetector = nullptr; } if (detectorEnabled) { peopleDetector = new PeopleDetector(&detectedPeopleTopic, cameraWidth, cameraHeight); detector = new BackgroundImageSink(peopleDetector, nullptr, nullptr); } } std::string findCameraDevice() { // Look for the MFC DIR *dir = opendir("/dev"); dirent *dirEntry = nullptr; while ((dirEntry = readdir(dir)) != nullptr) { int fd; v4l2_capability videoCap; std::string path = std::string("/dev/") + dirEntry->d_name; if (path.substr(0, std::string("/dev/video").size()) != "/dev/video") { continue; } ROS_INFO("Querying %s", path.c_str()); if((fd = open(path.c_str(), O_RDONLY)) == -1){ ROS_WARN("Can't open %s: %s", path.c_str(), strerror(errno)); continue; } if(ioctl(fd, VIDIOC_QUERYCAP, &videoCap) == -1) { ROS_WARN("Can't read from %s: %s", path.c_str(), strerror(errno)); continue; } else { if (videoCap.capabilities & V4L2_CAP_VIDEO_CAPTURE) { close(fd); closedir(dir); return path; } } close(fd); } closedir(dir); return ""; } BaseCamera *createCamera() { std::string cameraType; node.param("camera_type", cameraType, std::string("usb")); node.param("video_device", videoDevice, std::string("")); std::string resolution; node.getParam("resolution", resolution); cameraWidth = std::stoi(resolution.substr(0, resolution.find('x'))); cameraHeight = std::stoi(resolution.substr(resolution.find('x') + 1)); node.param("framerate", framerate, 30); node.param("media_path", mediaPath, std::string("~/.rospilot/media")); wordexp_t p; wordexp(mediaPath.c_str(), &p, 0); if (p.we_wordc != 1) { ROS_ERROR("Got too many words when expanding media path: %s", mediaPath.c_str()); } else { mediaPath = p.we_wordv[0]; } wordfree(&p); if (videoDevice.size() == 0) { videoDevice = findCameraDevice(); node.setParam("video_device", videoDevice); } if (cameraType == "ptp") { return new PtpCamera(); } else if (cameraType == "usb") { ROS_INFO("Requesting camera res %dx%d", cameraWidth, cameraHeight); UsbCamera *camera = new UsbCamera(videoDevice, cameraWidth, cameraHeight, framerate); // Read the width and height, since the camera may have altered it to // something it supports cameraWidth = camera->getWidth(); cameraHeight = camera->getHeight(); std::stringstream ss; ss << cameraWidth << "x" << cameraHeight; node.setParam("resolution", ss.str()); ROS_INFO("Camera selected res %dx%d", cameraWidth, cameraHeight); return camera; } else { ROS_FATAL("Unsupported camera type: %s", cameraType.c_str()); return nullptr; } } public: CameraNode() : node("~") { resolutionsTopic = node.advertise<rospilot::Resolutions>( "resolutions", 1, true); imagePub = node.advertise<sensor_msgs::CompressedImage>( "image_raw/compressed", 1); detectedPeopleTopic = node.advertise<rospilot::VisionTargets>( "vision_targets", 1); captureServiceServer = node.advertiseService( "capture_image", &CameraNode::captureImageCallback, this); startRecordServiceServer = node.advertiseService( "start_record", &CameraNode::startRecordHandler, this); stopRecordServiceServer = node.advertiseService( "stop_record", &CameraNode::stopRecordHandler, this); std::string mfc; node.param("mfc", mfc, std::string("")); if (mfc.size() > 0) { mfcPath = mfc; } else { mfcPath = findMfcDevice(); } // Install lock manager to make ffmpeg thread-safe if (av_lockmgr_register(ffmpegLockManager)) { ROS_FATAL("Failed to make ffmpeg thread-safe"); } initCameraAndEncoders(); } std::string findMfcDevice() { // Look for the MFC DIR *dir = opendir("/dev"); dirent *dirEntry = nullptr; while ((dirEntry = readdir(dir)) != nullptr) { int fd; v4l2_capability videoCap; std::string path = std::string("/dev/") + dirEntry->d_name; if (path.substr(0, std::string("/dev/video").size()) != "/dev/video" || path == videoDevice) { continue; } ROS_INFO("Querying %s", path.c_str()); if((fd = open(path.c_str(), O_RDONLY)) == -1){ ROS_WARN("Can't open %s: %s", path.c_str(), strerror(errno)); continue; } if(ioctl(fd, VIDIOC_QUERYCAP, &videoCap) == -1) { ROS_WARN("Can't read from %s: %s", path.c_str(), strerror(errno)); } else { v4l2_ext_controls ctrls; v4l2_ext_control ctrl; ctrl.id = V4L2_CID_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE; // These aren't used for integer controls ctrl.size = 0; memzero(ctrl.reserved2); ctrls.ctrl_class = V4L2_CTRL_CLASS_MPEG; ctrls.count = 1; ctrls.controls = &ctrl; if(ioctl(fd, VIDIOC_G_EXT_CTRLS, &ctrls) == 0) { close(fd); closedir(dir); return path; } } close(fd); } closedir(dir); return ""; } H264Encoder *createEncoder(H264Settings settings) { if (mfcPath.size() > 0 && !settings.zero_latency) { ROS_INFO("Using hardware encoder"); return new ExynosMultiFormatCodecH264Encoder(mfcPath, settings); } else { ROS_INFO("Using software encoder"); return new SoftwareH264Encoder(settings); } } ~CameraNode() { if (camera != nullptr) { delete camera; } delete jpegDecoder; delete recorder; delete liveStream; delete videoRecorder; if (detector != nullptr) { delete detector; } if (peopleDetector != nullptr) { delete peopleDetector; } av_lockmgr_register(nullptr); } bool spin() { ROS_INFO("camera node is running."); h264Server.start(); while (node.ok()) { // Process any pending service callbacks ros::spinOnce(); std::string newResolution; node.getParam("resolution", newResolution); int newWidth = std::stoi(newResolution.substr(0, newResolution.find('x'))); int newHeight = std::stoi(newResolution.substr(newResolution.find('x') + 1)); std::string newVideoDevice; node.getParam("video_device", newVideoDevice); bool newDetectorEnabled; node.getParam("detector_enabled", newDetectorEnabled); if (newVideoDevice != videoDevice || newDetectorEnabled != detectorEnabled || newWidth != cameraWidth || newHeight != cameraHeight) { initCameraAndEncoders(); } if(!sendPreview()) { // Sleep and hope the camera recovers usleep(1000*1000); } // Run at 1kHz usleep(1000); } h264Server.stop(); return true; } bool startRecordHandler(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { time_t t = time(nullptr); struct tm *tmp = localtime(&t); char str[100]; strftime(str, sizeof(str), "%Y-%m-%d_%H%M%S.mp4", tmp); std::string path = mediaPath + "/" + str; return videoRecorder->start(path.c_str()); } bool stopRecordHandler(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { return videoRecorder->stop(); } bool captureImageCallback(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { if (camera != nullptr) { time_t t = time(nullptr); struct tm *tmp = localtime(&t); char str[100]; strftime(str, sizeof(str), "%Y-%m-%d_%H%M%S", tmp); std::string basePath = mediaPath + "/" + str; std::string path = basePath + ".jpg"; for (int i = 1; boost::filesystem::exists(path); i++) { std::stringstream ss; ss << basePath << "_" << i << ".jpg"; path = ss.str(); } sensor_msgs::CompressedImage image; if (!camera->captureImage(&image)) { return false; } std::fstream fout(path, std::fstream::out); fout.write((char*) image.data.data(), image.data.size()); fout.close(); return true; } return false; } }; } int main(int argc, char **argv) { ros::init(argc, argv, "camera"); rospilot::CameraNode a; a.spin(); return 0; } <commit_msg>Add more logging to camera node<commit_after>/********************************************************************* * * Copyright 2012 the original author or authors. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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<stdio.h> #include<time.h> #include<fstream> #include<sstream> #include<chrono> #include<boost/filesystem.hpp> #include<wordexp.h> #include<dirent.h> #include<sys/ioctl.h> #include<fcntl.h> #include<errno.h> #include<mutex> #include<ros/ros.h> #include<rospilot/CaptureImage.h> #include<rospilot/Resolutions.h> #include<rospilot/VisionTargets.h> #include<std_srvs/Empty.h> #include<sensor_msgs/CompressedImage.h> #include<background_image_sink.h> #include<ptp.h> #include<usb_camera.h> #include<people_detector.h> #include<video_recorder.h> #include<transcoders.h> #include<resizer.h> #include<h264_server.h> extern "C" { #include <linux/videodev2.h> } namespace rospilot { static int ffmpegLockManager(void **mtx, enum AVLockOp op) { switch(op) { case AV_LOCK_CREATE: *mtx = new std::mutex(); if(!*mtx) return 1; return 0; case AV_LOCK_OBTAIN: ((std::mutex *) *mtx)->lock(); return 0; case AV_LOCK_RELEASE: ((std::mutex *) *mtx)->unlock(); return 0; case AV_LOCK_DESTROY: delete (std::mutex *) *mtx; *mtx = nullptr; return 0; } return 1; } using namespace std::chrono; class CameraNode { private: ros::NodeHandle node; // NOTE: We don't need to guard this with a mutex, because callbacks // are called in spinOnce() in the main thread BaseCamera *camera = nullptr; JpegDecoder *jpegDecoder = nullptr; SoftwareVideoRecorder *videoRecorder = nullptr; BackgroundImageSink *liveStream = nullptr; BackgroundImageSink *recorder = nullptr; BackgroundImageSink *detector = nullptr; H264Server h264Server; PeopleDetector *peopleDetector = nullptr; ros::Publisher resolutionsTopic; ros::Publisher imagePub; ros::Publisher detectedPeopleTopic; ros::ServiceServer captureServiceServer; ros::ServiceServer startRecordServiceServer; ros::ServiceServer stopRecordServiceServer; std::string videoDevice; std::string mfcPath; std::string mediaPath; int cameraWidth; int cameraHeight; int framerate; bool detectorEnabled = false; sensor_msgs::CompressedImage image; private: bool sendPreview() { if(camera != nullptr && camera->getLiveImage(&image)) { bool keyFrame = false; bool transcodedSuccessfully = false; imagePub.publish(image); jpegDecoder->decodeInPlace(&image); liveStream->addFrame(&image); recorder->addFrame(&image); if (detector != nullptr) { detector->addFrame(&image); } return true; } return false; } void initCameraAndEncoders() { if (camera != nullptr) { delete camera; } camera = createCamera(); resolutionsTopic.publish(camera->getSupportedResolutions()); PixelFormat pixelFormat = PIX_FMT_YUV420P; H264Settings recordingH264Settings; recordingH264Settings.height = cameraHeight; recordingH264Settings.width = cameraWidth; recordingH264Settings.level = 40; recordingH264Settings.gop_size = 30; recordingH264Settings.zero_latency = false; recordingH264Settings.profile = HIGH; recordingH264Settings.height = cameraHeight; recordingH264Settings.width = cameraWidth; recordingH264Settings.bit_rate = 4 * cameraWidth * cameraHeight; double aspectRatio = cameraHeight / (double) cameraWidth; H264Settings liveH264Settings; liveH264Settings.height = (int) (aspectRatio * 640); liveH264Settings.width = 640; liveH264Settings.level = 41; liveH264Settings.gop_size = 12; liveH264Settings.bit_rate = 1000 * 1000; liveH264Settings.zero_latency = true; liveH264Settings.profile = CONSTRAINED_BASELINE; if (jpegDecoder != nullptr) { delete jpegDecoder; } jpegDecoder = new TurboJpegDecoder(cameraWidth, cameraHeight, pixelFormat); if (liveStream != nullptr) { delete liveStream; } Resizer *resizer = new Resizer( cameraWidth, cameraHeight, liveH264Settings.width, liveH264Settings.height, pixelFormat); liveStream = new BackgroundImageSink( &h264Server, createEncoder(liveH264Settings), resizer); if (videoRecorder != nullptr) { delete videoRecorder; } videoRecorder = new SoftwareVideoRecorder(pixelFormat, recordingH264Settings, mediaPath); if (recorder != nullptr) { delete recorder; } recorder = new BackgroundImageSink( videoRecorder, createEncoder(recordingH264Settings), nullptr ); node.param("detector_enabled", detectorEnabled, false); if (detector != nullptr) { delete detector; detector = nullptr; } if (peopleDetector != nullptr) { delete peopleDetector; peopleDetector = nullptr; } if (detectorEnabled) { peopleDetector = new PeopleDetector(&detectedPeopleTopic, cameraWidth, cameraHeight); detector = new BackgroundImageSink(peopleDetector, nullptr, nullptr); } } std::string findCameraDevice() { // Look for the MFC DIR *dir = opendir("/dev"); dirent *dirEntry = nullptr; while ((dirEntry = readdir(dir)) != nullptr) { int fd; v4l2_capability videoCap; std::string path = std::string("/dev/") + dirEntry->d_name; if (path.substr(0, std::string("/dev/video").size()) != "/dev/video") { continue; } ROS_INFO("Querying %s", path.c_str()); if((fd = open(path.c_str(), O_RDONLY)) == -1){ ROS_WARN("Can't open %s: %s", path.c_str(), strerror(errno)); continue; } if(ioctl(fd, VIDIOC_QUERYCAP, &videoCap) == -1) { ROS_WARN("Can't read from %s: %s", path.c_str(), strerror(errno)); continue; } else { if (videoCap.capabilities & V4L2_CAP_VIDEO_CAPTURE) { close(fd); closedir(dir); return path; } } close(fd); } closedir(dir); return ""; } BaseCamera *createCamera() { std::string cameraType; node.param("camera_type", cameraType, std::string("usb")); node.param("video_device", videoDevice, std::string("")); std::string resolution; node.getParam("resolution", resolution); cameraWidth = std::stoi(resolution.substr(0, resolution.find('x'))); cameraHeight = std::stoi(resolution.substr(resolution.find('x') + 1)); node.param("framerate", framerate, 30); node.param("media_path", mediaPath, std::string("~/.rospilot/media")); wordexp_t p; wordexp(mediaPath.c_str(), &p, 0); if (p.we_wordc != 1) { ROS_ERROR("Got too many words when expanding media path: %s", mediaPath.c_str()); } else { mediaPath = p.we_wordv[0]; } wordfree(&p); if (videoDevice.size() == 0) { videoDevice = findCameraDevice(); node.setParam("video_device", videoDevice); } if (cameraType == "ptp") { return new PtpCamera(); } else if (cameraType == "usb") { ROS_INFO("Requesting camera res %dx%d", cameraWidth, cameraHeight); UsbCamera *camera = new UsbCamera(videoDevice, cameraWidth, cameraHeight, framerate); // Read the width and height, since the camera may have altered it to // something it supports cameraWidth = camera->getWidth(); cameraHeight = camera->getHeight(); std::stringstream ss; ss << cameraWidth << "x" << cameraHeight; node.setParam("resolution", ss.str()); ROS_INFO("Camera selected res %dx%d", cameraWidth, cameraHeight); return camera; } else { ROS_FATAL("Unsupported camera type: %s", cameraType.c_str()); return nullptr; } } public: CameraNode() : node("~") { resolutionsTopic = node.advertise<rospilot::Resolutions>( "resolutions", 1, true); imagePub = node.advertise<sensor_msgs::CompressedImage>( "image_raw/compressed", 1); detectedPeopleTopic = node.advertise<rospilot::VisionTargets>( "vision_targets", 1); captureServiceServer = node.advertiseService( "capture_image", &CameraNode::captureImageCallback, this); startRecordServiceServer = node.advertiseService( "start_record", &CameraNode::startRecordHandler, this); stopRecordServiceServer = node.advertiseService( "stop_record", &CameraNode::stopRecordHandler, this); std::string mfc; node.param("mfc", mfc, std::string("")); if (mfc.size() > 0) { mfcPath = mfc; } else { mfcPath = findMfcDevice(); } // Install lock manager to make ffmpeg thread-safe if (av_lockmgr_register(ffmpegLockManager)) { ROS_FATAL("Failed to make ffmpeg thread-safe"); } initCameraAndEncoders(); } std::string findMfcDevice() { // Look for the MFC DIR *dir = opendir("/dev"); dirent *dirEntry = nullptr; while ((dirEntry = readdir(dir)) != nullptr) { int fd; v4l2_capability videoCap; std::string path = std::string("/dev/") + dirEntry->d_name; if (path.substr(0, std::string("/dev/video").size()) != "/dev/video" || path == videoDevice) { continue; } ROS_INFO("Querying %s", path.c_str()); if((fd = open(path.c_str(), O_RDONLY)) == -1){ ROS_WARN("Can't open %s: %s", path.c_str(), strerror(errno)); continue; } if(ioctl(fd, VIDIOC_QUERYCAP, &videoCap) == -1) { ROS_WARN("Can't read from %s: %s", path.c_str(), strerror(errno)); } else { v4l2_ext_controls ctrls; v4l2_ext_control ctrl; ctrl.id = V4L2_CID_MPEG_MFC51_VIDEO_FRAME_SKIP_MODE; // These aren't used for integer controls ctrl.size = 0; memzero(ctrl.reserved2); ctrls.ctrl_class = V4L2_CTRL_CLASS_MPEG; ctrls.count = 1; ctrls.controls = &ctrl; if(ioctl(fd, VIDIOC_G_EXT_CTRLS, &ctrls) == 0) { close(fd); closedir(dir); return path; } } close(fd); } closedir(dir); return ""; } H264Encoder *createEncoder(H264Settings settings) { if (mfcPath.size() > 0 && !settings.zero_latency) { ROS_INFO("Using hardware encoder: %s", mfcPath.c_str()); return new ExynosMultiFormatCodecH264Encoder(mfcPath, settings); } else { ROS_INFO("Using software encoder"); return new SoftwareH264Encoder(settings); } } ~CameraNode() { if (camera != nullptr) { delete camera; } delete jpegDecoder; delete recorder; delete liveStream; delete videoRecorder; if (detector != nullptr) { delete detector; } if (peopleDetector != nullptr) { delete peopleDetector; } av_lockmgr_register(nullptr); } bool spin() { ROS_INFO("camera node is running."); h264Server.start(); while (node.ok()) { // Process any pending service callbacks ros::spinOnce(); std::string newResolution; node.getParam("resolution", newResolution); int newWidth = std::stoi(newResolution.substr(0, newResolution.find('x'))); int newHeight = std::stoi(newResolution.substr(newResolution.find('x') + 1)); std::string newVideoDevice; node.getParam("video_device", newVideoDevice); bool newDetectorEnabled; node.getParam("detector_enabled", newDetectorEnabled); if (newVideoDevice != videoDevice || newDetectorEnabled != detectorEnabled || newWidth != cameraWidth || newHeight != cameraHeight) { initCameraAndEncoders(); } if(!sendPreview()) { // Sleep and hope the camera recovers usleep(1000*1000); } // Run at 1kHz usleep(1000); } h264Server.stop(); return true; } bool startRecordHandler(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { time_t t = time(nullptr); struct tm *tmp = localtime(&t); char str[100]; strftime(str, sizeof(str), "%Y-%m-%d_%H%M%S.mp4", tmp); std::string path = mediaPath + "/" + str; return videoRecorder->start(path.c_str()); } bool stopRecordHandler(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { return videoRecorder->stop(); } bool captureImageCallback(std_srvs::Empty::Request& request, std_srvs::Empty::Response &response) { if (camera != nullptr) { time_t t = time(nullptr); struct tm *tmp = localtime(&t); char str[100]; strftime(str, sizeof(str), "%Y-%m-%d_%H%M%S", tmp); std::string basePath = mediaPath + "/" + str; std::string path = basePath + ".jpg"; for (int i = 1; boost::filesystem::exists(path); i++) { std::stringstream ss; ss << basePath << "_" << i << ".jpg"; path = ss.str(); } sensor_msgs::CompressedImage image; if (!camera->captureImage(&image)) { return false; } std::fstream fout(path, std::fstream::out); fout.write((char*) image.data.data(), image.data.size()); fout.close(); return true; } return false; } }; } int main(int argc, char **argv) { ros::init(argc, argv, "camera"); rospilot::CameraNode a; a.spin(); return 0; } <|endoftext|>
<commit_before>#include <termbox.h> #include <cstdint> #include <nanojson.hpp> #include <algorithm> #include <iostream> #include <string> #include <vector> #include <regex> class TermBox { public: TermBox() = default; ~TermBox() noexcept { try { tb_shutdown(); } catch (...) { } } void init() { int error = tb_init(); if (error) { std::cerr << "tb_init() failed with error code " << error << std::endl; std::exit(error); } } }; class CocoClient { TermBox termbox; std::vector<std::string> inputs, render_items, filtered; std::string query, selected_str; long cursor, selected; size_t offset; std::string const query_header = "QUERY> "; static constexpr unsigned y_offset = 1; public: CocoClient() { for (std::string line; std::getline(std::cin, line);) { inputs.push_back(line); } termbox.init(); apply_filter(); } std::string select_line() { while (true) { update_items(); if (handle_event()) break; } return selected_str; } bool handle_event() { tb_event ev; tb_poll_event(&ev); if (ev.key == TB_KEY_ENTER) { selected_str = render_items[offset + selected]; return true; } else if (ev.key == TB_KEY_ESC) { return true; } else if (ev.key == TB_KEY_BACKSPACE || ev.key == TB_KEY_BACKSPACE2) { if (!query.empty()) { query.pop_back(); apply_filter(); } } else if (ev.key == TB_KEY_ARROW_UP) { if (selected > -1) { selected -= 1; } if (cursor > 0) { cursor -= 1; } if (selected == -1) { selected += 1; if (offset > 0) { offset -= 1; render_items.resize(filtered.size() - offset); std::copy(filtered.begin() + offset, filtered.end(), render_items.begin()); } } } else if (ev.key == TB_KEY_ARROW_DOWN) { if (cursor < render_items.size() - 1) { cursor += 1; } if ((render_items.size() < tb_height() - 1) && (selected < render_items.size() - 1)) { selected += 1; } else if ((render_items.size() > tb_height() - 1) && (selected < tb_height() - 1)) { selected += 1; } if (selected == tb_height() - 1) { selected -= 1; if (offset < filtered.size() - 1) { offset += 1; render_items.resize(filtered.size() - offset); std::copy(filtered.begin() + offset, filtered.end(), render_items.begin()); } } } else if ((ev.ch != 0) || (ev.key == 32 && ev.ch == 0)) { query.push_back(ev.ch); apply_filter(); } return false; } private: void apply_filter() { filtered = filter(); render_items = filtered; selected = 0; cursor = 0; offset = 0; } std::vector<std::string> filter() const { std::regex re(query); if (query.empty()) { return inputs; } else { std::vector<std::string> ret; for (auto&& elem : inputs) { if (std::regex_search(elem, re)) { ret.push_back(elem); } } return ret; } } void update_items() const { tb_clear(); print_query(); for (int y = 0; y < (int)render_items.size(); ++y) { print_line(render_items[y], y, y == selected); } tb_present(); } void print_query() const { std::string query_str = query_header + query; for (int x = 0; x < tb_width(); ++x) { auto const c = static_cast<uint32_t>(x < query_str.length() ? query_str[x] : ' '); if (x == query_str.length()) { tb_change_cell(x, 0, c, TB_WHITE, TB_WHITE); } else { tb_change_cell(x, 0, c, TB_WHITE, TB_BLACK); } } } void print_line(std::string line, unsigned y, bool selected) const { for (int x = 0; x < tb_width(); ++x) { auto const c = static_cast<uint32_t>(x < line.length() ? line[x] : ' '); if (selected) { tb_change_cell(x, y + y_offset, c, TB_RED, TB_WHITE); } else { tb_change_cell(x, y + y_offset, c, TB_WHITE, TB_BLACK); } } } }; int main() { std::string selected; { CocoClient cli{}; selected = cli.select_line(); } if (!selected.empty()) { std::cout << selected << std::endl; } return 0; } <commit_msg>revise<commit_after>#include <termbox.h> #include <cstdint> #include <nanojson.hpp> #include <algorithm> #include <iostream> #include <string> #include <vector> #include <regex> class TermBox { public: TermBox() { init(); } ~TermBox() noexcept { try { tb_shutdown(); } catch (...) { } } void init() { int error = tb_init(); if (error) { std::cerr << "tb_init() failed with error code " << error << std::endl; std::exit(error); } } }; class CocoClient { TermBox termbox; std::vector<std::string> inputs, render_items, filtered; std::string query, selected_str; long cursor, selected; size_t offset; std::string const query_header = "QUERY> "; static constexpr unsigned y_offset = 1; public: CocoClient(std::vector<std::string> inputs) : inputs{std::move(inputs)} {} std::string select_line() { apply_filter(); while (true) { update_items(); tb_event ev; tb_poll_event(&ev); if (handle_event(ev)) break; } return selected_str; } bool handle_event(tb_event& ev) { if (ev.key == TB_KEY_ENTER) { if (!filtered.empty()) { selected_str = render_items[offset + selected]; } return true; } else if (ev.key == TB_KEY_ESC) { return true; } else if (ev.key == TB_KEY_BACKSPACE || ev.key == TB_KEY_BACKSPACE2) { if (!query.empty()) { query.pop_back(); apply_filter(); } } else if (ev.key == TB_KEY_ARROW_UP) { if (selected > -1) { selected -= 1; } if (cursor > 0) { cursor -= 1; } if (selected == -1) { selected += 1; if (offset > 0) { offset -= 1; render_items.resize(filtered.size() - offset); std::copy(filtered.begin() + offset, filtered.end(), render_items.begin()); } } } else if (ev.key == TB_KEY_ARROW_DOWN) { if (cursor < render_items.size() - 1) { cursor += 1; } if ((render_items.size() < tb_height() - 1) && (selected < render_items.size() - 1)) { selected += 1; } else if ((render_items.size() > tb_height() - 1) && (selected < tb_height() - 1)) { selected += 1; } if (selected == tb_height() - 1) { selected -= 1; if (offset < filtered.size() - 1) { offset += 1; render_items.resize(filtered.size() - offset); std::copy(filtered.begin() + offset, filtered.end(), render_items.begin()); } } } else if ((ev.ch != 0) || (ev.key == 32 && ev.ch == 0)) { query.push_back(ev.ch); apply_filter(); } return false; } private: void apply_filter() { filtered = filter(); render_items = filtered; selected = 0; cursor = 0; offset = 0; } std::vector<std::string> filter() const { std::regex re(query); if (query.empty()) { return inputs; } else { std::vector<std::string> ret; for (auto&& elem : inputs) { if (std::regex_search(elem, re)) { ret.push_back(elem); } } return ret; } } void update_items() const { tb_clear(); print_query(); for (int y = 0; y < (int)render_items.size(); ++y) { print_line(render_items[y], y, y == selected); } tb_present(); } void print_query() const { std::string query_str = query_header + query; for (int x = 0; x < tb_width(); ++x) { auto const c = static_cast<uint32_t>(x < query_str.length() ? query_str[x] : ' '); if (x == query_str.length()) { tb_change_cell(x, 0, c, TB_WHITE, TB_WHITE); } else { tb_change_cell(x, 0, c, TB_WHITE, TB_BLACK); } } } void print_line(std::string line, unsigned y, bool selected) const { for (int x = 0; x < tb_width(); ++x) { auto const c = static_cast<uint32_t>(x < line.length() ? line[x] : ' '); if (selected) { tb_change_cell(x, y + y_offset, c, TB_RED, TB_WHITE); } else { tb_change_cell(x, y + y_offset, c, TB_WHITE, TB_BLACK); } } } }; int main() { std::regex ansi(R"(\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K])"); std::vector<std::string> inputs; for (std::string line; std::getline(std::cin, line);) { inputs.push_back(std::regex_replace(line, ansi, "")); } std::string selected; { auto cli = CocoClient{std::move(inputs)}; selected = cli.select_line(); } if (!selected.empty()) { std::cout << selected << std::endl; } return 0; } <|endoftext|>
<commit_before>/************************************************************************* > File Name: Combat.cpp > Project Name: Hearthstonepp > Author: Young-Joong Kim > Purpose: Implement CombatTask > Created Time: 2018/07/21 > Copyright (c) 2018, Young-Joong Kim *************************************************************************/ #include <Tasks/BasicTasks/CombatTask.h> #include <Tasks/BasicTasks/ModifyHealthTask.h> namespace Hearthstonepp::BasicTasks { CombatTask::CombatTask(TaskAgent& agent) : m_requirement(TaskID::SELECT_TARGET, agent) { // Do Nothing } TaskID CombatTask::GetTaskID() const { return TaskID::COMBAT; } MetaData CombatTask::Impl(Player& player1, Player& player2) { TaskMeta serialized; // Get Targeting Response from GameInterface m_requirement.Interact(player1.id, serialized); using RequireTaskMeta = FlatData::ResponseTarget; const auto& buffer = serialized.GetConstBuffer(); auto req = flatbuffers::GetRoot<RequireTaskMeta>(buffer.get()); if (req == nullptr) { return MetaData::COMBAT_FLATBUFFER_NULLPTR; } BYTE src = req->src(); BYTE dst = req->dst(); source = (src > 0) ? dynamic_cast<Character*>(player1.field[src - 1]) : dynamic_cast<Character*>(player1.hero); target = (dst > 0) ? dynamic_cast<Character*>(player2.field[dst - 1]) : dynamic_cast<Character*>(player2.hero); // Source Minion Index Verification if (src > player1.field.size()) { return MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE; } // Source Minion Verification for Attacked Vector std::vector<Character*>& attacked = player1.attacked; if (std::find(attacked.begin(), attacked.end(), source) != attacked.end()) { return MetaData::COMBAT_ALREADY_ATTACKED; } attacked.emplace_back(source); // Destination Verification // dst == 0 : hero // 1 < dst <= field.size : minion if (dst > player2.field.size()) { return MetaData::COMBAT_DST_IDX_OUT_OF_RANGE; } BYTE sourceAttack = static_cast<BYTE>(source->attack); BYTE targetAttack = (dst > 0) ? static_cast<BYTE>(target->attack) : 0; // Attack : Dst -> Src MetaData hurtedSrc = ModifyHealthTask(source, targetAttack).Run(player1, player2); if (hurtedSrc != MetaData::MODIFY_HEALTH_SUCCESS) { return hurtedSrc; } // Attack : Src -> Dst MetaData hurtedDst = ModifyHealthTask(target, sourceAttack).Run(player1, player2); if (hurtedDst != MetaData::MODIFY_HEALTH_SUCCESS) { return hurtedDst; } return MetaData::COMBAT_SUCCESS; } } // namespace Hearthstonepp::BasicTasks<commit_msg>Update CombatTask - Add minion erasing routine<commit_after>/************************************************************************* > File Name: Combat.cpp > Project Name: Hearthstonepp > Author: Young-Joong Kim > Purpose: Implement CombatTask > Created Time: 2018/07/21 > Copyright (c) 2018, Young-Joong Kim *************************************************************************/ #include <Tasks/BasicTasks/CombatTask.h> #include <Tasks/BasicTasks/ModifyHealthTask.h> namespace Hearthstonepp::BasicTasks { CombatTask::CombatTask(TaskAgent& agent) : m_requirement(TaskID::SELECT_TARGET, agent) { // Do Nothing } TaskID CombatTask::GetTaskID() const { return TaskID::COMBAT; } MetaData CombatTask::Impl(Player& player1, Player& player2) { TaskMeta serialized; // Get Targeting Response from GameInterface m_requirement.Interact(player1.id, serialized); auto req = TaskMeta::ConvertTo<FlatData::ResponseTarget>(serialized); if (req == nullptr) { return MetaData::COMBAT_FLATBUFFER_NULLPTR; } BYTE src = req->src(); BYTE dst = req->dst(); source = (src > 0) ? dynamic_cast<Character*>(player1.field[src - 1]) : dynamic_cast<Character*>(player1.hero); target = (dst > 0) ? dynamic_cast<Character*>(player2.field[dst - 1]) : dynamic_cast<Character*>(player2.hero); // Source Minion Index Verification if (src > player1.field.size()) { return MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE; } // Source Minion Verification for Attacked Vector std::vector<Character*>& attacked = player1.attacked; if (std::find(attacked.begin(), attacked.end(), source) != attacked.end()) { return MetaData::COMBAT_ALREADY_ATTACKED; } // Destination Verification // dst == 0 : hero // 1 < dst <= field.size : minion if (dst > player2.field.size()) { return MetaData::COMBAT_DST_IDX_OUT_OF_RANGE; } BYTE sourceAttack = (src > 0) ? static_cast<BYTE>(source->attack) : 0; BYTE targetAttack = (dst > 0) ? static_cast<BYTE>(target->attack) : 0; // Attack : Dst -> Src MetaData hurtedSrc = ModifyHealthTask(source, targetAttack).Run(player1, player2); if (hurtedSrc != MetaData::MODIFY_HEALTH_SUCCESS) { return hurtedSrc; } if (source->health <= 0) { // find minion and remove it from field auto& field = player1.field; if (auto ptr = std::find(field.begin(), field.end(), source); ptr != field.end()) { field.erase(ptr); } player1.usedMinion.emplace_back(source); } attacked.emplace_back(source); // Attack : Src -> Dst MetaData hurtedDst = ModifyHealthTask(target, sourceAttack).Run(player1, player2); if (hurtedDst != MetaData::MODIFY_HEALTH_SUCCESS) { return hurtedDst; } if (target->health <= 0) { auto& field = player2.field; if (auto ptr = std::find(field.begin(), field.end(), target); ptr != field.end()) { field.erase(ptr); } player2.usedMinion.emplace_back(source); } return MetaData::COMBAT_SUCCESS; } } // namespace Hearthstonepp::BasicTasks<|endoftext|>
<commit_before><commit_msg>Removed unused file QuadTree.cpp<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** Author: Milian Wolff, KDAB (milian.wolff@kdab.com) ** ** This file is part of Qt Creator. ** ** 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. ** ****************************************************************************/ #include "memcheckrunner.h" #include "../xmlprotocol/error.h" #include "../xmlprotocol/status.h" #include "../xmlprotocol/threadedparser.h" #include <utils/qtcassert.h> #include <QNetworkInterface> #include <QTcpServer> #include <QTcpSocket> #include <QEventLoop> #include <QApplication> #include <QDialog> #include <QDialogButtonBox> #include <QLabel> #include <QListWidget> #include <QVBoxLayout> namespace Valgrind { namespace Memcheck { class MemcheckRunner::Private { public: explicit Private() : parser(0), logSocket(0) { } QTcpServer xmlServer; XmlProtocol::ThreadedParser *parser; QTcpServer logServer; QTcpSocket *logSocket; }; MemcheckRunner::MemcheckRunner(QObject *parent) : ValgrindRunner(parent), d(new Private) { } MemcheckRunner::~MemcheckRunner() { if (d->parser->isRunning()) { // make sure we don't delete the thread while it's still running waitForFinished(); } delete d; d = 0; } QString MemcheckRunner::tool() const { return QLatin1String("memcheck"); } void MemcheckRunner::setParser(XmlProtocol::ThreadedParser *parser) { QTC_ASSERT(!d->parser, qt_noop()); d->parser = parser; } bool MemcheckRunner::start() { QTC_ASSERT(d->parser, return false); QString ip; QHostAddress hostAddr; if (startMode() == Analyzer::StartLocal) { ip = QLatin1String("127.0.0.1"); hostAddr = QHostAddress(QHostAddress::LocalHost); } if (startMode() == Analyzer::StartRemote) { QList<QHostAddress> possibleHostAddresses; //NOTE: ::allAddresses does not seem to work for usb interfaces... foreach (const QNetworkInterface &iface, QNetworkInterface::allInterfaces()) { foreach (const QNetworkAddressEntry &entry, iface.addressEntries()) { const QHostAddress addr = entry.ip(); if (addr.toString() != QLatin1String("127.0.0.1") && addr.toString() != QLatin1String("0:0:0:0:0:0:0:1")) { possibleHostAddresses << addr; break; } } } if (possibleHostAddresses.isEmpty()) { emit processErrorReceived(tr("No network interface found for remote analysis."), QProcess::FailedToStart); return false; } else if (possibleHostAddresses.size() > 1) { QDialog dlg; dlg.setWindowTitle(tr("Select Network Interface")); QVBoxLayout *layout = new QVBoxLayout; QLabel *description = new QLabel; description->setWordWrap(true); description->setText(tr("More than one network interface was found on your machine. Please select which one you want to use for remote analysis.")); layout->addWidget(description); QListWidget *list = new QListWidget; foreach (const QHostAddress &address, possibleHostAddresses) list->addItem(address.toString()); list->setSelectionMode(QAbstractItemView::SingleSelection); list->setCurrentRow(0); layout->addWidget(list); QDialogButtonBox *buttons = new QDialogButtonBox; buttons->addButton(QDialogButtonBox::Ok); buttons->addButton(QDialogButtonBox::Cancel); connect(buttons, SIGNAL(accepted()), &dlg, SLOT(accept())); connect(buttons, SIGNAL(rejected()), &dlg, SLOT(reject())); layout->addWidget(buttons); dlg.setLayout(layout); if (dlg.exec() != QDialog::Accepted) { emit processErrorReceived(tr("No Network Interface was chosen for remote analysis"), QProcess::FailedToStart); return false; } QTC_ASSERT(list->currentRow() >= 0, return false); QTC_ASSERT(list->currentRow() < possibleHostAddresses.size(), return false); hostAddr = possibleHostAddresses.at(list->currentRow()); } else { hostAddr = possibleHostAddresses.first(); } ip = hostAddr.toString(); QTC_ASSERT(!ip.isEmpty(), return false); hostAddr = QHostAddress(ip); } bool check = d->xmlServer.listen(hostAddr); if (!check) emit processErrorReceived( tr("XmlServer on %1: ").arg(ip) + d->xmlServer.errorString(), QProcess::FailedToStart ); QTC_ASSERT(check, return false); d->xmlServer.setMaxPendingConnections(1); const quint16 xmlPortNumber = d->xmlServer.serverPort(); connect(&d->xmlServer, SIGNAL(newConnection()), SLOT(xmlSocketConnected())); check = d->logServer.listen(hostAddr); if (!check) emit processErrorReceived( tr("LogServer on %1: ").arg(ip) + d->logServer.errorString(), QProcess::FailedToStart ); QTC_ASSERT(check, return false); d->logServer.setMaxPendingConnections(1); const quint16 logPortNumber = d->logServer.serverPort(); connect(&d->logServer, SIGNAL(newConnection()), SLOT(logSocketConnected())); QStringList memcheckArguments; memcheckArguments << QLatin1String("--xml=yes") << QString::fromLatin1("--xml-socket=%1:%2").arg(ip).arg(xmlPortNumber) << QLatin1String("--child-silent-after-fork=yes") << QString::fromLatin1("--log-socket=%1:%2").arg(ip).arg(logPortNumber); setValgrindArguments(memcheckArguments); return ValgrindRunner::start(); } void MemcheckRunner::xmlSocketConnected() { QTcpSocket *socket = d->xmlServer.nextPendingConnection(); QTC_ASSERT(socket, return); d->xmlServer.close(); d->parser->parse(socket); } void MemcheckRunner::logSocketConnected() { d->logSocket = d->logServer.nextPendingConnection(); QTC_ASSERT(d->logSocket, return); connect(d->logSocket, SIGNAL(readyRead()), this, SLOT(readLogSocket())); d->logServer.close(); } void MemcheckRunner::readLogSocket() { QTC_ASSERT(d->logSocket, return); emit logMessageReceived(d->logSocket->readAll()); } } // namespace Memcheck } // namespace Valgrind <commit_msg>Valgrind: Do not ignore/overwrite tool options<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** Author: Milian Wolff, KDAB (milian.wolff@kdab.com) ** ** This file is part of Qt Creator. ** ** 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. ** ****************************************************************************/ #include "memcheckrunner.h" #include "../xmlprotocol/error.h" #include "../xmlprotocol/status.h" #include "../xmlprotocol/threadedparser.h" #include <utils/qtcassert.h> #include <QNetworkInterface> #include <QTcpServer> #include <QTcpSocket> #include <QEventLoop> #include <QApplication> #include <QDialog> #include <QDialogButtonBox> #include <QLabel> #include <QListWidget> #include <QVBoxLayout> namespace Valgrind { namespace Memcheck { class MemcheckRunner::Private { public: explicit Private() : parser(0), logSocket(0) { } QTcpServer xmlServer; XmlProtocol::ThreadedParser *parser; QTcpServer logServer; QTcpSocket *logSocket; }; MemcheckRunner::MemcheckRunner(QObject *parent) : ValgrindRunner(parent), d(new Private) { } MemcheckRunner::~MemcheckRunner() { if (d->parser->isRunning()) { // make sure we don't delete the thread while it's still running waitForFinished(); } delete d; d = 0; } QString MemcheckRunner::tool() const { return QLatin1String("memcheck"); } void MemcheckRunner::setParser(XmlProtocol::ThreadedParser *parser) { QTC_ASSERT(!d->parser, qt_noop()); d->parser = parser; } bool MemcheckRunner::start() { QTC_ASSERT(d->parser, return false); QString ip; QHostAddress hostAddr; if (startMode() == Analyzer::StartLocal) { ip = QLatin1String("127.0.0.1"); hostAddr = QHostAddress(QHostAddress::LocalHost); } if (startMode() == Analyzer::StartRemote) { QList<QHostAddress> possibleHostAddresses; //NOTE: ::allAddresses does not seem to work for usb interfaces... foreach (const QNetworkInterface &iface, QNetworkInterface::allInterfaces()) { foreach (const QNetworkAddressEntry &entry, iface.addressEntries()) { const QHostAddress addr = entry.ip(); if (addr.toString() != QLatin1String("127.0.0.1") && addr.toString() != QLatin1String("0:0:0:0:0:0:0:1")) { possibleHostAddresses << addr; break; } } } if (possibleHostAddresses.isEmpty()) { emit processErrorReceived(tr("No network interface found for remote analysis."), QProcess::FailedToStart); return false; } else if (possibleHostAddresses.size() > 1) { QDialog dlg; dlg.setWindowTitle(tr("Select Network Interface")); QVBoxLayout *layout = new QVBoxLayout; QLabel *description = new QLabel; description->setWordWrap(true); description->setText(tr("More than one network interface was found on your machine. Please select which one you want to use for remote analysis.")); layout->addWidget(description); QListWidget *list = new QListWidget; foreach (const QHostAddress &address, possibleHostAddresses) list->addItem(address.toString()); list->setSelectionMode(QAbstractItemView::SingleSelection); list->setCurrentRow(0); layout->addWidget(list); QDialogButtonBox *buttons = new QDialogButtonBox; buttons->addButton(QDialogButtonBox::Ok); buttons->addButton(QDialogButtonBox::Cancel); connect(buttons, SIGNAL(accepted()), &dlg, SLOT(accept())); connect(buttons, SIGNAL(rejected()), &dlg, SLOT(reject())); layout->addWidget(buttons); dlg.setLayout(layout); if (dlg.exec() != QDialog::Accepted) { emit processErrorReceived(tr("No Network Interface was chosen for remote analysis"), QProcess::FailedToStart); return false; } QTC_ASSERT(list->currentRow() >= 0, return false); QTC_ASSERT(list->currentRow() < possibleHostAddresses.size(), return false); hostAddr = possibleHostAddresses.at(list->currentRow()); } else { hostAddr = possibleHostAddresses.first(); } ip = hostAddr.toString(); QTC_ASSERT(!ip.isEmpty(), return false); hostAddr = QHostAddress(ip); } bool check = d->xmlServer.listen(hostAddr); if (!check) emit processErrorReceived( tr("XmlServer on %1: ").arg(ip) + d->xmlServer.errorString(), QProcess::FailedToStart ); QTC_ASSERT(check, return false); d->xmlServer.setMaxPendingConnections(1); const quint16 xmlPortNumber = d->xmlServer.serverPort(); connect(&d->xmlServer, SIGNAL(newConnection()), SLOT(xmlSocketConnected())); check = d->logServer.listen(hostAddr); if (!check) emit processErrorReceived( tr("LogServer on %1: ").arg(ip) + d->logServer.errorString(), QProcess::FailedToStart ); QTC_ASSERT(check, return false); d->logServer.setMaxPendingConnections(1); const quint16 logPortNumber = d->logServer.serverPort(); connect(&d->logServer, SIGNAL(newConnection()), SLOT(logSocketConnected())); QStringList memcheckLogArguments; memcheckLogArguments << QLatin1String("--xml=yes") << QString::fromLatin1("--xml-socket=%1:%2").arg(ip).arg(xmlPortNumber) << QLatin1String("--child-silent-after-fork=yes") << QString::fromLatin1("--log-socket=%1:%2").arg(ip).arg(logPortNumber); setValgrindArguments(memcheckLogArguments + valgrindArguments()); return ValgrindRunner::start(); } void MemcheckRunner::xmlSocketConnected() { QTcpSocket *socket = d->xmlServer.nextPendingConnection(); QTC_ASSERT(socket, return); d->xmlServer.close(); d->parser->parse(socket); } void MemcheckRunner::logSocketConnected() { d->logSocket = d->logServer.nextPendingConnection(); QTC_ASSERT(d->logSocket, return); connect(d->logSocket, SIGNAL(readyRead()), this, SLOT(readLogSocket())); d->logServer.close(); } void MemcheckRunner::readLogSocket() { QTC_ASSERT(d->logSocket, return); emit logMessageReceived(d->logSocket->readAll()); } } // namespace Memcheck } // namespace Valgrind <|endoftext|>
<commit_before>#ifndef ALEPH_MATH_PIECEWISE_LINEAR_FUNCTION_HH__ #define ALEPH_MATH_PIECEWISE_LINEAR_FUNCTION_HH__ #include <aleph/math/KahanSummation.hh> #include <functional> #include <iterator> #include <limits> #include <map> #include <set> #include <stdexcept> #include <vector> #include <cassert> #include <cmath> namespace aleph { namespace math { namespace detail { /** Performs linear interpolation between two points */ template <class D, class I> I lerp( D x, D x0, I y0, D x1, I y1 ) { return y0 + (y1-y0) * (x-x0) / (x1-x0); } } // namespace detail /** @class PiecewiseLinearFunction @brief Models a piecewise linear function A piecewise linear function is fully defined by a set of pairs of coordinates, specifying values in the *domain* and the *image* of the function. This class permits various arithmetical operations, such as addition and subtraction, with piecewise linear functions and provides a number of other common operations. @tparam D Type of the *domain* of the function @tparam I Type of the *image* of the function */ template <class D, class I = D> class PiecewiseLinearFunction { public: using Domain = D; using Image = I; /** Creates an empty piecewise linear function */ PiecewiseLinearFunction() = default; /** Creates a new piecewise linear function from a range of values. The values must consist of pairs that are convertible to double. Duplicates are not permitted and will result in an exception being thrown. @param begin Input iterator to begin of range @param end Input iterator to end of range */ template <class InputIterator> PiecewiseLinearFunction( InputIterator begin, InputIterator end ) { for( InputIterator it = begin; it != end; ++it ) { auto x = it->first; auto y = it->second; bool success = false; std::tie( std::ignore, success ) = _data.insert( std::make_pair(x,y) ); if( !success ) throw std::runtime_error( "Duplicate value pairs not permitted for piecewise linear functions" ); } // Inserts new points whenever the function intersects the x-axis in // order to ensure that the integration procedure works. if( !_data.empty() ) this->insertIntersectionPoints(); } // Evaluation -------------------------------------------------------- /** Evaluates the piecewise linear function at a certain position. The function must not be evaluated beyond its domain. This will result in zeroes. For every other evaluation point, the function performs interpolation between the nearest values. @param x Coordinate at which to evaluate the function @returns Interpolated y value */ Image operator()( Domain x ) const noexcept { auto range = _data.equal_range( x ); auto begin = range.first; auto end = range.second; // Beyond the domain if( begin == _data.end() || end == _data.begin() ) return Image(); // One of the stored values else if( begin->first == x ) return begin->second; // Interpolation required auto right = begin; auto left = std::prev( begin ); return detail::lerp( x, left->first, left->second, right->first, right->second ); } // Operations -------------------------------------------------------- /** Calculates the sum of two piecewise linear functions */ PiecewiseLinearFunction& operator+=( const PiecewiseLinearFunction& rhs ) noexcept { return this->apply( rhs, std::plus<Image>() ); } /** Calculates the sum of two piecewise linear functions */ PiecewiseLinearFunction operator+( const PiecewiseLinearFunction& rhs ) const noexcept { auto lhs = *this; lhs += rhs; return lhs; } /** Calculates the difference of two piecewise linear functions */ PiecewiseLinearFunction& operator-=( const PiecewiseLinearFunction& rhs ) noexcept { return this->apply( rhs, std::minus<Image>() ); } /** Calculates the difference of two piecewise linear functions */ PiecewiseLinearFunction operator-( const PiecewiseLinearFunction& rhs ) const noexcept { auto lhs = *this; lhs -= rhs; return lhs; } /** Unary minus: negates all values in the image of the piecewise linear function */ PiecewiseLinearFunction operator-() const noexcept { PiecewiseLinearFunction f; for( auto&& pair : _data ) f._data.insert( std::make_pair( pair.first, -pair.second ) ); return f; } /** Multiplies the given piecewise linear function with a scalar value */ PiecewiseLinearFunction& operator*=( Image lambda ) noexcept { for( auto&& pair : _data ) pair.second *= lambda; return *this; } /** Multiplies the given piecewise linear function with a scalar value */ PiecewiseLinearFunction operator*( Image lambda ) const noexcept { auto f = *this; f *= lambda; return f; } /** Divides the given step function by a scalar value */ PiecewiseLinearFunction& operator/=( I lambda ) { if( lambda == I() ) throw std::runtime_error( "Attempted division by zero" ); return this->operator*=( 1/lambda ); } /** Divides the given step function by a scalar value */ PiecewiseLinearFunction& operator/( I lambda ) const noexcept { auto f = *this; f /= lambda; return f; } // Queries ----------------------------------------------------------- /** Copies the domain values to an output iterator */ template <class OutputIterator> void domain( OutputIterator result ) const noexcept { for( auto&& pair : _data ) *result++ = pair.first; } /** Copies the image values to an output iterator */ template <class OutputIterator> void image( OutputIterator result ) const noexcept { for( auto&& pair : _data ) *result++ = pair.second; } /** Compares two piecewise linear functions. The functions are considered to be *equal* when the take the same values for the same interval. This method will evaluate the functions over *all* points of the domain. @param rhs Other function to compare against @returns true if both functions are equal, regardless of whether one of the functions has a subdivided range of values. */ bool operator==( const PiecewiseLinearFunction& rhs ) const noexcept { std::set<Domain> domain; this->domain( std::inserter( domain, domain.begin() ) ); rhs.domain( std::inserter( domain, domain.begin() ) ); bool result = true; for( auto&& x : domain ) { auto y0 = this->operator()( x ); auto y1 = rhs( x ); if( y0 != y1 ) return false; } return result; } /** Negates the comparison between two functions */ bool operator!=( const PiecewiseLinearFunction& rhs ) const noexcept { return !this->operator==( rhs ); } // Transformations --------------------------------------------------- /** Calculates the absolute value of the function */ PiecewiseLinearFunction& abs() noexcept { for( auto&& pair : _data ) pair.second = std::abs( pair.second ); return *this; } /** Calculates the maximum (supremum) of the function */ Image max() const noexcept { if( _data.empty() ) return Image(); auto max = std::numeric_limits<Image>::lowest(); for( auto&& pair : _data ) max = std::max( max, pair.second ); return max; } /** Calculates the supremum (maximum) of the function */ Image sup() const noexcept { return this->max(); } /** Calculates the integral over the (absolute value of the) function, raised to the \f$p\f$-th power. */ Image integral( Image p = Image(1) ) const noexcept { if( _data.empty() ) return Image(); // The Kahan summation ensures that small parts of the integral do // not disappear amidst the remaining values. KahanSummation<Image> norm = Image(); auto previous = _data.begin(); auto current = std::next( _data.begin() ); while( current != _data.end() ) { // Coefficients of the line that connect the previous point and the current // point. auto x1 = previous->first; auto y1 = previous->second; auto x2 = current->first; auto y2 = current->second; auto m = (y2 - y1) / (x2 - x1); auto c = y1 - m * x1; // Evaluator for the integral. This is an application of Cavalieri's // quadrature formula. auto evaluator = [&]( Image x ) { // Horizontal segments if( m == Image() ) return std::pow( c, p ) * x; // Regular lines else return std::pow( m*x + c, p+1 ) / ( m * (p+1) ); }; auto integral = std::abs( evaluator( x2 ) - evaluator( x1 ) ); norm += integral; previous = current; ++current; } return std::pow( norm, 1/p ); } private: /** Applies a binary operation to the current piecewise linear function and another function. To this, the domains of *both* functions will be merged, and the operation will be applied to their values, with a suitable interpolation scheme in place. @param other Second piecewise linear function @param operation Operation to apply to both functions @returns Reference to modified piecewise linear function. The original piecewise linear function ceases to exist. */ template <class BinaryOperation> PiecewiseLinearFunction& apply( const PiecewiseLinearFunction& other, BinaryOperation operation ) { std::set<Domain> xValues; for( auto&& pair : _data ) xValues.insert( pair.first ); for( auto&& pair : other._data ) xValues.insert( pair.first ); // Oherwise, the loop below will turn in an infinite loop since or // the validity of the `current` iterator would have to be checked // before-hand. if( xValues.empty() ) return *this; // Intersection handling. This is required to ensure that the combination of // the two functions contains shared segments. { // This closure checks whether two line segments intersect. If this is the // case, the intersection point needs to be stored as an additional point // in the set of values. auto intersection = []( Domain x0, Image y0, Domain x1, Image y1, Domain x2, Image y2, Domain x3, Image y3 ) { auto s1x = x1 - x0; auto s1y = y1 - y0; auto s2x = x3 - x2; auto s2y = y3 - y2; auto s = ( -s1y * (x0-x2) + s1x * (y0-y2) ) / ( -s2x * s1y + s1x * s2y ); auto t = ( s2x * (y0-y2) - s2y * (x0-x2) ) / ( -s2x * s1y + s1x * s2y ); if( s >= 0 && s <= 1 && t >= 0 && t <= 1 ) return x0 + t * s1x; return x0; }; std::set<Domain> intersections; auto current = xValues.begin(); auto next = std::next( current ); for( ; next != xValues.end(); ) { auto x0 = *current; auto x1 = *next; auto y0 = this->operator()( x0 ); auto y1 = this->operator()( x1 ); auto y2 = other( x0 ); auto y3 = other( x1 ); auto x = intersection( x0, y0, x1, y1, x0, y2, x1, y3 ); if( x != x0 ) intersections.insert( x ); current = next; next = std::next( current ); } xValues.insert( intersections.begin(), intersections.end() ); } // Apply the operation to all points ------------------------------- std::map<Domain, Image> data; for( auto&& x : xValues ) { auto y1 = this->operator()( x ); auto y2 = other( x ); data.insert( std::make_pair( x, operation( y1, y2 ) ) ); } _data.swap( data ); return *this; } /** Checks the segments of the piecewise linear function for intersections with the x-axis. In these cases, a new point needs to be inserted into the list of function values. Else, the integration procedure will not work because a segment might be considered to have an area of zero. The following example illustrates this problem: \verbatim /\ / \ --------- \ / \/ \endverbatim If the intersection in the middle is not being counted as a point on the PL function, the area of the corresponding segment will be zero. This is not the desired and expected behaviour. */ void insertIntersectionPoints() { auto current = _data.begin(); auto next = std::next( current ); std::set<Domain> intersections; for( ; next != _data.end(); ) { auto x0 = current->first; auto y0 = current->second; auto x1 = next->first; auto y1 = next->second; // We do not need to check the other cases. If either one of the values is // zero, we already have an intersection. if( y0 * y1 < Image() ) { auto m = ( y1 - y0 ) / ( x1 - x0 ); auto c = y0 - m * x0; auto x = - c / m; intersections.insert( x ); } current = next; next = std::next( current ); } for( auto&& x : intersections ) _data.insert( std::make_pair( x, Image() ) ); } /** Maps values in the domain to values in the image */ std::map<Domain, Image> _data; }; } // namespace math } // namespace aleph /** Multiplies a given piecewise linear function by a scalar value */ template <class D, class I, class T> aleph::math::PiecewiseLinearFunction<D, I> operator*( T lambda, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { return f * lambda; } /** Divides a given piecewise linear function by a scalar value */ template <class D, class I, class T> aleph::math::PiecewiseLinearFunction<D, I> operator/( T lambda, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { return f / lambda; } /** Output operator of a piecewise linear function. Permits printing the function values to an *output stream* in order to permit their usage by other functions and/or programs. */ template <class D, class I> std::ostream& operator<<( std::ostream& o, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { std::vector<D> X; std::vector<I> Y; f.domain( std::back_inserter(X) ); f.image ( std::back_inserter(Y) ); assert( X.size() == Y.size() ); for( std::size_t i = 0; i < X.size() && i < Y.size(); i++ ) o << X[i] << "\t" << Y[i] << "\n"; return o; } #endif <commit_msg>Fixed division operator for piecewise linear functions<commit_after>#ifndef ALEPH_MATH_PIECEWISE_LINEAR_FUNCTION_HH__ #define ALEPH_MATH_PIECEWISE_LINEAR_FUNCTION_HH__ #include <aleph/math/KahanSummation.hh> #include <functional> #include <iterator> #include <limits> #include <map> #include <set> #include <stdexcept> #include <vector> #include <cassert> #include <cmath> namespace aleph { namespace math { namespace detail { /** Performs linear interpolation between two points */ template <class D, class I> I lerp( D x, D x0, I y0, D x1, I y1 ) { return y0 + (y1-y0) * (x-x0) / (x1-x0); } } // namespace detail /** @class PiecewiseLinearFunction @brief Models a piecewise linear function A piecewise linear function is fully defined by a set of pairs of coordinates, specifying values in the *domain* and the *image* of the function. This class permits various arithmetical operations, such as addition and subtraction, with piecewise linear functions and provides a number of other common operations. @tparam D Type of the *domain* of the function @tparam I Type of the *image* of the function */ template <class D, class I = D> class PiecewiseLinearFunction { public: using Domain = D; using Image = I; /** Creates an empty piecewise linear function */ PiecewiseLinearFunction() = default; /** Creates a new piecewise linear function from a range of values. The values must consist of pairs that are convertible to double. Duplicates are not permitted and will result in an exception being thrown. @param begin Input iterator to begin of range @param end Input iterator to end of range */ template <class InputIterator> PiecewiseLinearFunction( InputIterator begin, InputIterator end ) { for( InputIterator it = begin; it != end; ++it ) { auto x = it->first; auto y = it->second; bool success = false; std::tie( std::ignore, success ) = _data.insert( std::make_pair(x,y) ); if( !success ) throw std::runtime_error( "Duplicate value pairs not permitted for piecewise linear functions" ); } // Inserts new points whenever the function intersects the x-axis in // order to ensure that the integration procedure works. if( !_data.empty() ) this->insertIntersectionPoints(); } // Evaluation -------------------------------------------------------- /** Evaluates the piecewise linear function at a certain position. The function must not be evaluated beyond its domain. This will result in zeroes. For every other evaluation point, the function performs interpolation between the nearest values. @param x Coordinate at which to evaluate the function @returns Interpolated y value */ Image operator()( Domain x ) const noexcept { auto range = _data.equal_range( x ); auto begin = range.first; auto end = range.second; // Beyond the domain if( begin == _data.end() || end == _data.begin() ) return Image(); // One of the stored values else if( begin->first == x ) return begin->second; // Interpolation required auto right = begin; auto left = std::prev( begin ); return detail::lerp( x, left->first, left->second, right->first, right->second ); } // Operations -------------------------------------------------------- /** Calculates the sum of two piecewise linear functions */ PiecewiseLinearFunction& operator+=( const PiecewiseLinearFunction& rhs ) noexcept { return this->apply( rhs, std::plus<Image>() ); } /** Calculates the sum of two piecewise linear functions */ PiecewiseLinearFunction operator+( const PiecewiseLinearFunction& rhs ) const noexcept { auto lhs = *this; lhs += rhs; return lhs; } /** Calculates the difference of two piecewise linear functions */ PiecewiseLinearFunction& operator-=( const PiecewiseLinearFunction& rhs ) noexcept { return this->apply( rhs, std::minus<Image>() ); } /** Calculates the difference of two piecewise linear functions */ PiecewiseLinearFunction operator-( const PiecewiseLinearFunction& rhs ) const noexcept { auto lhs = *this; lhs -= rhs; return lhs; } /** Unary minus: negates all values in the image of the piecewise linear function */ PiecewiseLinearFunction operator-() const noexcept { PiecewiseLinearFunction f; for( auto&& pair : _data ) f._data.insert( std::make_pair( pair.first, -pair.second ) ); return f; } /** Multiplies the given piecewise linear function with a scalar value */ PiecewiseLinearFunction& operator*=( Image lambda ) noexcept { for( auto&& pair : _data ) pair.second *= lambda; return *this; } /** Multiplies the given piecewise linear function with a scalar value */ PiecewiseLinearFunction operator*( Image lambda ) const noexcept { auto f = *this; f *= lambda; return f; } /** Divides the given step function by a scalar value */ PiecewiseLinearFunction& operator/=( I lambda ) { if( lambda == I() ) throw std::runtime_error( "Attempted division by zero" ); return this->operator*=( 1/lambda ); } /** Divides the given step function by a scalar value */ PiecewiseLinearFunction operator/( I lambda ) const noexcept { auto f = *this; f /= lambda; return f; } // Queries ----------------------------------------------------------- /** Copies the domain values to an output iterator */ template <class OutputIterator> void domain( OutputIterator result ) const noexcept { for( auto&& pair : _data ) *result++ = pair.first; } /** Copies the image values to an output iterator */ template <class OutputIterator> void image( OutputIterator result ) const noexcept { for( auto&& pair : _data ) *result++ = pair.second; } /** Compares two piecewise linear functions. The functions are considered to be *equal* when the take the same values for the same interval. This method will evaluate the functions over *all* points of the domain. @param rhs Other function to compare against @returns true if both functions are equal, regardless of whether one of the functions has a subdivided range of values. */ bool operator==( const PiecewiseLinearFunction& rhs ) const noexcept { std::set<Domain> domain; this->domain( std::inserter( domain, domain.begin() ) ); rhs.domain( std::inserter( domain, domain.begin() ) ); bool result = true; for( auto&& x : domain ) { auto y0 = this->operator()( x ); auto y1 = rhs( x ); if( y0 != y1 ) return false; } return result; } /** Negates the comparison between two functions */ bool operator!=( const PiecewiseLinearFunction& rhs ) const noexcept { return !this->operator==( rhs ); } // Transformations --------------------------------------------------- /** Calculates the absolute value of the function */ PiecewiseLinearFunction& abs() noexcept { for( auto&& pair : _data ) pair.second = std::abs( pair.second ); return *this; } /** Calculates the maximum (supremum) of the function */ Image max() const noexcept { if( _data.empty() ) return Image(); auto max = std::numeric_limits<Image>::lowest(); for( auto&& pair : _data ) max = std::max( max, pair.second ); return max; } /** Calculates the supremum (maximum) of the function */ Image sup() const noexcept { return this->max(); } /** Calculates the integral over the (absolute value of the) function, raised to the \f$p\f$-th power. */ Image integral( Image p = Image(1) ) const noexcept { if( _data.empty() ) return Image(); // The Kahan summation ensures that small parts of the integral do // not disappear amidst the remaining values. KahanSummation<Image> norm = Image(); auto previous = _data.begin(); auto current = std::next( _data.begin() ); while( current != _data.end() ) { // Coefficients of the line that connect the previous point and the current // point. auto x1 = previous->first; auto y1 = previous->second; auto x2 = current->first; auto y2 = current->second; auto m = (y2 - y1) / (x2 - x1); auto c = y1 - m * x1; // Evaluator for the integral. This is an application of Cavalieri's // quadrature formula. auto evaluator = [&]( Image x ) { // Horizontal segments if( m == Image() ) return std::pow( c, p ) * x; // Regular lines else return std::pow( m*x + c, p+1 ) / ( m * (p+1) ); }; auto integral = std::abs( evaluator( x2 ) - evaluator( x1 ) ); norm += integral; previous = current; ++current; } return std::pow( norm, 1/p ); } private: /** Applies a binary operation to the current piecewise linear function and another function. To this, the domains of *both* functions will be merged, and the operation will be applied to their values, with a suitable interpolation scheme in place. @param other Second piecewise linear function @param operation Operation to apply to both functions @returns Reference to modified piecewise linear function. The original piecewise linear function ceases to exist. */ template <class BinaryOperation> PiecewiseLinearFunction& apply( const PiecewiseLinearFunction& other, BinaryOperation operation ) { std::set<Domain> xValues; for( auto&& pair : _data ) xValues.insert( pair.first ); for( auto&& pair : other._data ) xValues.insert( pair.first ); // Oherwise, the loop below will turn in an infinite loop since or // the validity of the `current` iterator would have to be checked // before-hand. if( xValues.empty() ) return *this; // Intersection handling. This is required to ensure that the combination of // the two functions contains shared segments. { // This closure checks whether two line segments intersect. If this is the // case, the intersection point needs to be stored as an additional point // in the set of values. auto intersection = []( Domain x0, Image y0, Domain x1, Image y1, Domain x2, Image y2, Domain x3, Image y3 ) { auto s1x = x1 - x0; auto s1y = y1 - y0; auto s2x = x3 - x2; auto s2y = y3 - y2; auto s = ( -s1y * (x0-x2) + s1x * (y0-y2) ) / ( -s2x * s1y + s1x * s2y ); auto t = ( s2x * (y0-y2) - s2y * (x0-x2) ) / ( -s2x * s1y + s1x * s2y ); if( s >= 0 && s <= 1 && t >= 0 && t <= 1 ) return x0 + t * s1x; return x0; }; std::set<Domain> intersections; auto current = xValues.begin(); auto next = std::next( current ); for( ; next != xValues.end(); ) { auto x0 = *current; auto x1 = *next; auto y0 = this->operator()( x0 ); auto y1 = this->operator()( x1 ); auto y2 = other( x0 ); auto y3 = other( x1 ); auto x = intersection( x0, y0, x1, y1, x0, y2, x1, y3 ); if( x != x0 ) intersections.insert( x ); current = next; next = std::next( current ); } xValues.insert( intersections.begin(), intersections.end() ); } // Apply the operation to all points ------------------------------- std::map<Domain, Image> data; for( auto&& x : xValues ) { auto y1 = this->operator()( x ); auto y2 = other( x ); data.insert( std::make_pair( x, operation( y1, y2 ) ) ); } _data.swap( data ); return *this; } /** Checks the segments of the piecewise linear function for intersections with the x-axis. In these cases, a new point needs to be inserted into the list of function values. Else, the integration procedure will not work because a segment might be considered to have an area of zero. The following example illustrates this problem: \verbatim /\ / \ --------- \ / \/ \endverbatim If the intersection in the middle is not being counted as a point on the PL function, the area of the corresponding segment will be zero. This is not the desired and expected behaviour. */ void insertIntersectionPoints() { auto current = _data.begin(); auto next = std::next( current ); std::set<Domain> intersections; for( ; next != _data.end(); ) { auto x0 = current->first; auto y0 = current->second; auto x1 = next->first; auto y1 = next->second; // We do not need to check the other cases. If either one of the values is // zero, we already have an intersection. if( y0 * y1 < Image() ) { auto m = ( y1 - y0 ) / ( x1 - x0 ); auto c = y0 - m * x0; auto x = - c / m; intersections.insert( x ); } current = next; next = std::next( current ); } for( auto&& x : intersections ) _data.insert( std::make_pair( x, Image() ) ); } /** Maps values in the domain to values in the image */ std::map<Domain, Image> _data; }; } // namespace math } // namespace aleph /** Multiplies a given piecewise linear function by a scalar value */ template <class D, class I, class T> aleph::math::PiecewiseLinearFunction<D, I> operator*( T lambda, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { return f * lambda; } /** Divides a given piecewise linear function by a scalar value */ template <class D, class I, class T> aleph::math::PiecewiseLinearFunction<D, I> operator/( T lambda, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { return f / lambda; } /** Output operator of a piecewise linear function. Permits printing the function values to an *output stream* in order to permit their usage by other functions and/or programs. */ template <class D, class I> std::ostream& operator<<( std::ostream& o, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { std::vector<D> X; std::vector<I> Y; f.domain( std::back_inserter(X) ); f.image ( std::back_inserter(Y) ); assert( X.size() == Y.size() ); for( std::size_t i = 0; i < X.size() && i < Y.size(); i++ ) o << X[i] << "\t" << Y[i] << "\n"; return o; } #endif <|endoftext|>
<commit_before>/* * Test Driver for Botan */ #include <vector> #include <string> #include <iostream> #include <cstdlib> #include <cstring> #include <exception> #include <limits> #include <botan/botan.h> #include <botan/mp_types.h> using namespace Botan_types; #include "getopt.h" const std::string VALIDATION_FILE = "checks/validate.dat"; const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat"; const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat"; const std::string EXPECTED_FAIL_FILE = "checks/fail.dat"; void benchmark(const std::string&, bool html, double seconds); void bench_pk(const std::string&, bool html, double seconds); u32bit bench_algo(const std::string&, double); int validate(); int main(int argc, char* argv[]) { try { OptionParser opts("help|html|init=|validate|" "benchmark|bench-type=|bench-algo=|seconds="); opts.parse(argv); Botan::InitializerOptions init_options(opts.value_if_set("init")); Botan::LibraryInitializer init(init_options); if(opts.is_set("help") || argc <= 1) { std::cerr << "Test driver for " << Botan::version_string() << "\n" << "Options:\n" << " --validate: Check test vectors\n" << " --benchmark: Benchmark everything\n" << " --bench-type={block,mode,stream,hash,mac,rng,pk}:\n" << " Benchmark only algorithms of a particular type\n" << " --html: Produce HTML output for benchmarks\n" << " --seconds=n: Benchmark for n seconds\n" << " --init=<str>: Pass <str> to the library\n" << " --help: Print this message\n"; return 1; } if(opts.is_set("validate")) return validate(); double seconds = 1.5; if(opts.is_set("seconds")) { seconds = std::atof(opts.value("seconds").c_str()); if((seconds < 0.1 || seconds > 30) && seconds != 0) { std::cout << "Invalid argument to --seconds\n"; return 2; } } const bool html = opts.is_set("html"); if(opts.is_set("bench-algo")) { std::vector<std::string> algs = Botan::split_on(opts.value("bench-algo"), ','); for(u32bit j = 0; j != algs.size(); j++) { const std::string alg = algs[j]; u32bit found = bench_algo(alg, seconds); if(!found) // maybe it's a PK algorithm bench_pk(alg, html, seconds); } } if(opts.is_set("benchmark")) benchmark("All", html, seconds); else if(opts.is_set("bench-type")) { const std::string type = opts.value("bench-type"); if(type == "all") benchmark("All", html, seconds); else if(type == "block") benchmark("Block Cipher", html, seconds); else if(type == "stream") benchmark("Stream Cipher", html, seconds); else if(type == "hash") benchmark("Hash", html, seconds); else if(type == "mac") benchmark("MAC", html, seconds); else if(type == "rng") benchmark("RNG", html, seconds); else if(type == "pk") bench_pk("All", html, seconds); } } catch(Botan::Exception& e) { std::cout << "Exception caught:\n " << e.what() << std::endl; return 1; } catch(std::exception& e) { std::cout << "Standard library exception caught:\n " << e.what() << std::endl; return 1; } catch(...) { std::cout << "Unknown exception caught." << std::endl; return 1; } return 0; } int validate() { void test_types(); u32bit do_validation_tests(const std::string&, bool = true); u32bit do_bigint_tests(const std::string&); u32bit do_pk_validation_tests(const std::string&); std::cout << "Beginning validation tests..." << std::endl; test_types(); u32bit errors = 0; try { errors += do_validation_tests(VALIDATION_FILE); errors += do_validation_tests(EXPECTED_FAIL_FILE, false); errors += do_bigint_tests(BIGINT_VALIDATION_FILE); errors += do_pk_validation_tests(PK_VALIDATION_FILE); } catch(Botan::Exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; return 1; } catch(std::exception& e) { std::cout << "Standard library exception caught: " << e.what() << std::endl; return 1; } catch(...) { std::cout << "Unknown exception caught." << std::endl; return 1; } if(errors) { std::cout << errors << " test" << ((errors == 1) ? "" : "s") << " failed." << std::endl; return 1; } std::cout << "All tests passed!" << std::endl; return 0; } template<typename T> bool test(const char* type, int digits, bool is_signed) { bool passed = true; if(std::numeric_limits<T>::is_specialized == false) { std::cout << "WARNING: Could not check parameters of " << type << " in std::numeric_limits" << std::endl; return true; } if(std::numeric_limits<T>::digits != digits && digits != 0) { std::cout << "ERROR: numeric_limits<" << type << ">::digits != " << digits << std::endl; passed = false; } if(std::numeric_limits<T>::is_signed != is_signed) { std::cout << "ERROR: numeric_limits<" << type << ">::is_signed != " << std::boolalpha << is_signed << std::endl; passed = false; } if(std::numeric_limits<T>::is_integer == false) { std::cout << "ERROR: numeric_limits<" << type << ">::is_integer == false " << std::endl; passed = false; } return passed; } void test_types() { bool passed = true; passed = passed && test<Botan::byte >("byte", 8, false); passed = passed && test<Botan::u16bit>("u16bit", 16, false); passed = passed && test<Botan::u32bit>("u32bit", 32, false); passed = passed && test<Botan::u64bit>("u64bit", 64, false); passed = passed && test<Botan::s32bit>("s32bit", 31, true); passed = passed && test<Botan::word>("word", 0, false); if(!passed) { std::cout << "Important settings in types.h are wrong. Please fix " "and recompile." << std::endl; std::exit(1); } } <commit_msg>Increase the (arbitrary) upper bound on how long the benchmarks can run to 5 minutes (300 seconds).<commit_after>/* * Test Driver for Botan */ #include <vector> #include <string> #include <iostream> #include <cstdlib> #include <cstring> #include <exception> #include <limits> #include <botan/botan.h> #include <botan/mp_types.h> using namespace Botan_types; #include "getopt.h" const std::string VALIDATION_FILE = "checks/validate.dat"; const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat"; const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat"; const std::string EXPECTED_FAIL_FILE = "checks/fail.dat"; void benchmark(const std::string&, bool html, double seconds); void bench_pk(const std::string&, bool html, double seconds); u32bit bench_algo(const std::string&, double); int validate(); int main(int argc, char* argv[]) { try { OptionParser opts("help|html|init=|validate|" "benchmark|bench-type=|bench-algo=|seconds="); opts.parse(argv); Botan::InitializerOptions init_options(opts.value_if_set("init")); Botan::LibraryInitializer init(init_options); if(opts.is_set("help") || argc <= 1) { std::cerr << "Test driver for " << Botan::version_string() << "\n" << "Options:\n" << " --validate: Check test vectors\n" << " --benchmark: Benchmark everything\n" << " --bench-type={block,mode,stream,hash,mac,rng,pk}:\n" << " Benchmark only algorithms of a particular type\n" << " --html: Produce HTML output for benchmarks\n" << " --seconds=n: Benchmark for n seconds\n" << " --init=<str>: Pass <str> to the library\n" << " --help: Print this message\n"; return 1; } if(opts.is_set("validate")) return validate(); double seconds = 1.5; if(opts.is_set("seconds")) { seconds = std::atof(opts.value("seconds").c_str()); if(seconds && (seconds < 0.1 || seconds > (5 * 60))) { std::cout << "Invalid argument to --seconds\n"; return 2; } } const bool html = opts.is_set("html"); if(opts.is_set("bench-algo")) { std::vector<std::string> algs = Botan::split_on(opts.value("bench-algo"), ','); for(u32bit j = 0; j != algs.size(); j++) { const std::string alg = algs[j]; u32bit found = bench_algo(alg, seconds); if(!found) // maybe it's a PK algorithm bench_pk(alg, html, seconds); } } if(opts.is_set("benchmark")) benchmark("All", html, seconds); else if(opts.is_set("bench-type")) { const std::string type = opts.value("bench-type"); if(type == "all") benchmark("All", html, seconds); else if(type == "block") benchmark("Block Cipher", html, seconds); else if(type == "stream") benchmark("Stream Cipher", html, seconds); else if(type == "hash") benchmark("Hash", html, seconds); else if(type == "mac") benchmark("MAC", html, seconds); else if(type == "rng") benchmark("RNG", html, seconds); else if(type == "pk") bench_pk("All", html, seconds); } } catch(Botan::Exception& e) { std::cout << "Exception caught:\n " << e.what() << std::endl; return 1; } catch(std::exception& e) { std::cout << "Standard library exception caught:\n " << e.what() << std::endl; return 1; } catch(...) { std::cout << "Unknown exception caught." << std::endl; return 1; } return 0; } int validate() { void test_types(); u32bit do_validation_tests(const std::string&, bool = true); u32bit do_bigint_tests(const std::string&); u32bit do_pk_validation_tests(const std::string&); std::cout << "Beginning validation tests..." << std::endl; test_types(); u32bit errors = 0; try { errors += do_validation_tests(VALIDATION_FILE); errors += do_validation_tests(EXPECTED_FAIL_FILE, false); errors += do_bigint_tests(BIGINT_VALIDATION_FILE); errors += do_pk_validation_tests(PK_VALIDATION_FILE); } catch(Botan::Exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; return 1; } catch(std::exception& e) { std::cout << "Standard library exception caught: " << e.what() << std::endl; return 1; } catch(...) { std::cout << "Unknown exception caught." << std::endl; return 1; } if(errors) { std::cout << errors << " test" << ((errors == 1) ? "" : "s") << " failed." << std::endl; return 1; } std::cout << "All tests passed!" << std::endl; return 0; } template<typename T> bool test(const char* type, int digits, bool is_signed) { bool passed = true; if(std::numeric_limits<T>::is_specialized == false) { std::cout << "WARNING: Could not check parameters of " << type << " in std::numeric_limits" << std::endl; return true; } if(std::numeric_limits<T>::digits != digits && digits != 0) { std::cout << "ERROR: numeric_limits<" << type << ">::digits != " << digits << std::endl; passed = false; } if(std::numeric_limits<T>::is_signed != is_signed) { std::cout << "ERROR: numeric_limits<" << type << ">::is_signed != " << std::boolalpha << is_signed << std::endl; passed = false; } if(std::numeric_limits<T>::is_integer == false) { std::cout << "ERROR: numeric_limits<" << type << ">::is_integer == false " << std::endl; passed = false; } return passed; } void test_types() { bool passed = true; passed = passed && test<Botan::byte >("byte", 8, false); passed = passed && test<Botan::u16bit>("u16bit", 16, false); passed = passed && test<Botan::u32bit>("u32bit", 32, false); passed = passed && test<Botan::u64bit>("u64bit", 64, false); passed = passed && test<Botan::s32bit>("s32bit", 31, true); passed = passed && test<Botan::word>("word", 0, false); if(!passed) { std::cout << "Important settings in types.h are wrong. Please fix " "and recompile." << std::endl; std::exit(1); } } <|endoftext|>