lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
C++
src/devices/bin/driver_host/driver_host_context.cc
casey/fuchsia
2b965e9a1e8f2ea346db540f3611a5be16bb4d6b
#include "driver_host_context.h" #include <stdio.h> #include <fbl/auto_lock.h> #include <fs/vfs.h> #include "log.h" void DriverHostContext::PushWorkItem(const fbl::RefPtr<zx_device_t>& dev, Callback callback) { auto work_item = std::make_unique<WorkItem>(dev, std::move(callback)); fbl::AutoLock al(&lock_); work_items_.push_back(std::move(work_item)); if (!event_waiter_->signaled()) { event_waiter_->signal(); } } void DriverHostContext::InternalRunWorkItems(size_t how_many_to_run) { { fbl::AutoLock al(&lock_); if (event_waiter_->signaled()) { event_waiter_->designal(); } } size_t work_items_run = 0; auto keep_running = [&]() { return work_items_run < how_many_to_run || how_many_to_run == 0; }; do { fbl::DoublyLinkedList<std::unique_ptr<WorkItem>> work_items; { fbl::AutoLock al(&lock_); work_items = std::move(work_items_); } if (work_items.is_empty()) { return; } std::unique_ptr<WorkItem> work_item; while (keep_running() && (work_item = work_items.pop_front())) { work_item->callback(); work_items_run++; } if (!work_items.is_empty()) { fbl::AutoLock al(&lock_); work_items_.splice(work_items_.begin(), work_items); } } while (keep_running()); fbl::AutoLock al(&lock_); if (!work_items_.is_empty() && !event_waiter_->signaled()) { event_waiter_->signal(); } } void DriverHostContext::RunWorkItems(size_t how_many_to_run) { std::unique_ptr<EventWaiter> event_waiter; { fbl::AutoLock al(&lock_); ZX_DEBUG_ASSERT(event_waiter_ != nullptr); if (work_items_.is_empty()) { return; } event_waiter = event_waiter_->Cancel(); } InternalRunWorkItems(how_many_to_run); EventWaiter::BeginWait(std::move(event_waiter), loop_.dispatcher()); } zx_status_t DriverHostContext::SetupEventWaiter() { zx::event event; if (zx_status_t status = zx::event::create(0, &event); status != ZX_OK) { return status; } constexpr uint32_t kBatchSize = 5; auto event_waiter = std::make_unique<EventWaiter>(std::move(event), [this]() { InternalRunWorkItems(kBatchSize); }); { fbl::AutoLock al(&lock_); event_waiter_ = event_waiter.get(); } return EventWaiter::BeginWait(std::move(event_waiter), loop_.dispatcher()); } void DriverHostContext::EventWaiter::HandleEvent(std::unique_ptr<EventWaiter> event_waiter, async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, const zx_packet_signal_t* signal) { if (status != ZX_OK) { log(ERROR, "driver_host: event waiter error: %d\n", status); return; } if (signal->observed & ZX_USER_SIGNAL_0) { event_waiter->InvokeCallback(); BeginWait(std::move(event_waiter), dispatcher); } else { printf("%s: invalid signals %x\n", __func__, signal->observed); abort(); } } zx_status_t DriverHostContext::DeviceConnect(const fbl::RefPtr<zx_device_t>& dev, uint32_t flags, zx::channel c) { auto options = fs::VnodeConnectionOptions::FromIoV1Flags(flags); fbl::RefPtr<fs::Vnode> target; zx_status_t status = dev->vnode->OpenValidating(options, &target); if (status != ZX_OK) { return status; } if (target == nullptr) { target = dev->vnode; } return vfs_.Serve(std::move(target), std::move(c), options); }
#include "driver_host_context.h" #include <stdio.h> #include <fbl/auto_lock.h> #include <fs/vfs.h>
nst zx_packet_signal_t* signal) { if (status != ZX_OK) { log(ERROR, "driver_host: event waiter error: %d\n", status); return; } if (signal->observed & ZX_USER_SIGNAL_0) { event_waiter->InvokeCallback(); BeginWait(std::move(event_waiter), dispatcher); } else { printf("%s: invalid signals %x\n", __func__, signal->observed); abort(); } } zx_status_t DriverHostContext::DeviceConnect(const fbl::RefPtr<zx_device_t>& dev, uint32_t flags, zx::channel c) { auto options = fs::VnodeConnectionOptions::FromIoV1Flags(flags); fbl::RefPtr<fs::Vnode> target; zx_status_t status = dev->vnode->OpenValidating(options, &target); if (status != ZX_OK) { return status; } if (target == nullptr) { target = dev->vnode; } return vfs_.Serve(std::move(target), std::move(c), options); }
#include "log.h" void DriverHostContext::PushWorkItem(const fbl::RefPtr<zx_device_t>& dev, Callback callback) { auto work_item = std::make_unique<WorkItem>(dev, std::move(callback)); fbl::AutoLock al(&lock_); work_items_.push_back(std::move(work_item)); if (!event_waiter_->signaled()) { event_waiter_->signal(); } } void DriverHostContext::InternalRunWorkItems(size_t how_many_to_run) { { fbl::AutoLock al(&lock_); if (event_waiter_->signaled()) { event_waiter_->designal(); } } size_t work_items_run = 0; auto keep_running = [&]() { return work_items_run < how_many_to_run || how_many_to_run == 0; }; do { fbl::DoublyLinkedList<std::unique_ptr<WorkItem>> work_items; { fbl::AutoLock al(&lock_); work_items = std::move(work_items_); } if (work_items.is_empty()) { return; } std::unique_ptr<WorkItem> work_item; while (keep_running() && (work_item = work_items.pop_front())) { work_item->callback(); work_items_run++; } if (!work_items.is_empty()) { fbl::AutoLock al(&lock_); work_items_.splice(work_items_.begin(), work_items); } } while (keep_running()); fbl::AutoLock al(&lock_); if (!work_items_.is_empty() && !event_waiter_->signaled()) { event_waiter_->signal(); } } void DriverHostContext::RunWorkItems(size_t how_many_to_run) { std::unique_ptr<EventWaiter> event_waiter; { fbl::AutoLock al(&lock_); ZX_DEBUG_ASSERT(event_waiter_ != nullptr); if (work_items_.is_empty()) { return; } event_waiter = event_waiter_->Cancel(); } InternalRunWorkItems(how_many_to_run); EventWaiter::BeginWait(std::move(event_waiter), loop_.dispatcher()); } zx_status_t DriverHostContext::SetupEventWaiter() { zx::event event; if (zx_status_t status = zx::event::create(0, &event); status != ZX_OK) { return status; } constexpr uint32_t kBatchSize = 5; auto event_waiter = std::make_unique<EventWaiter>(std::move(event), [this]() { InternalRunWorkItems(kBatchSize); }); { fbl::AutoLock al(&lock_); event_waiter_ = event_waiter.get(); } return EventWaiter::BeginWait(std::move(event_waiter), loop_.dispatcher()); } void DriverHostContext::EventWaiter::HandleEvent(std::unique_ptr<EventWaiter> event_waiter, async_dispatcher_t* dispatcher, async::WaitBase* wait, zx_status_t status, co
random
[]
C++
src/render/MCPT_EL.cc
ppwwyyxx/Ray-Tracing-Engine
af3ec164d6b5e5b592a54a75282432d610423ffb
#include "render/MCPT_EL.hh" using namespace std; Color MCPT_EL::do_trace(const Ray& ray, int depth, int use_emission) const { if (depth > max_depth) return Color::BLACK; m_assert(fabs(ray.dir.sqr() - 1) < EPS); auto first_trace = find_first(ray, true); if (!first_trace) return Color::BLACK; Vec norm = first_trace->normal(), inter_point = first_trace->intersection_point(); auto surf = first_trace->get_property(); Color diffu = surf->diffuse; real_t forward_density = first_trace->get_forward_density(); m_assert((fabs(norm.sqr() - 1) < EPS)); m_assert(norm.dot(ray.dir) <= 0); if (ray.debug) { print_debug("debug ray: arrive point (%lf, %lf, %lf) \n", inter_point.x, inter_point.y, inter_point.z); } real_t max_color_comp = diffu.get_max(); if (depth > 5 or fabs(max_color_comp) < EPS) { if (drand48() < max_color_comp) diffu = diffu * (1.0 / max_color_comp); else return surf->emission * use_emission; } real_t r1 = 2 * M_PI * drand48(), r2 = drand48(), r2s = sqrt(r2); Vec u = ((fabs(norm.x) > 0.1 ? Vec(0, 1, 0) : Vec(1, 0, 0)).cross(norm)).get_normalized(), v = norm.cross(u); Vec d = ((u * cos(r1)) * r2s + v * sin(r1) * r2s + norm * (sqrt(1 - r2))).get_normalized(); real_t diffuse_weight = min(1 - surf->specular, 1 - surf->transparency); Color now_diffuse = do_trace(Ray(inter_point - ray.dir * EPS, d), depth + 1) * diffuse_weight; real_t lighting = 0; for (auto & light : lights) { Vec l_src = light->get_src(); real_t l_size = light->get_size(); Vec sw = l_src - inter_point, su = (fabs(sw.x) > 0.1 ? Vec(0, 1, 0) : Vec(1, 0, 0)).get_normalized(), sv = sw.cross(su); real_t cos_a_max = sqrt(1 - ::sqr(l_size) / sw.sqr()); if (!isnormal(cos_a_max)) cos_a_max = 0; real_t eps1 = drand48(), eps2 = drand48(); real_t cos_a = 1 - eps1 + eps1 * cos_a_max, sin_a = sqrt(1 - ::sqr(cos_a)), phi = 2 * M_PI * eps2; Vec dir = su * cos(phi) * sin_a + sv * sin(phi) * sin_a + sw * cos_a; if (dir.dot(norm) < 0) continue; dir.normalize(); if (check_shadow_ray(Ray(inter_point + dir * EPS, dir), light)) { real_t omega = 2 * M_PI * (1 - cos_a_max); lighting += light->intensity * dir.dot(norm) * omega * M_1_PI; } } lighting *= diffuse_weight / 6; m_assert(diffuse_weight >= 0); m_assert(lighting >= 0); Color now_refl = Color::BLACK; if (surf->specular > 0 && !(first_trace->contain())) { Ray new_ray(inter_point - ray.dir * EPS, -norm.reflection(ray.dir), ray.density); m_assert(fabs((-norm.reflection(ray.dir)).sqr() - 1) < EPS); new_ray.debug = ray.debug; Color refl = do_trace(new_ray, depth + 1, 0); now_refl = refl * surf->specular; } Color now_transm = Color::BLACK; if (surf->transparency > EPS) { Ray refl_ray(inter_point - ray.dir * EPS, -norm.reflection(ray.dir), ray.density); refl_ray.debug = ray.debug; Vec tr_dir = norm.transmission(ray.dir, ray.density / forward_density); if (isfinite(tr_dir.x)) { Ray new_ray(inter_point + ray.dir * EPS, tr_dir, forward_density); new_ray.debug = ray.debug; real_t F0 = sqr(0.5) / sqr(ray.density + forward_density); real_t theta = first_trace->contain() ? tr_dir.dot(norm) : ray.dir.dot(norm); real_t Fr = F0 + (1 - F0) * pow(1 + theta, 5); real_t P = 0.25 + Fr * 0.5; if (drand48() < P) { Color refl = do_trace(refl_ray, depth + 1, 0) * surf->specular; now_transm = refl * Fr / P; } else { Color transm = do_trace(new_ray, depth + 1, 0); now_transm = transm * ((1 - Fr) / (1 - P)) * surf->transparency; } } else { Color refl = do_trace(refl_ray, depth + 1) * surf->specular; now_transm = refl; } } return surf->emission * use_emission + diffu * (now_diffuse + now_refl + now_transm) + diffu * lighting; } bool MCPT_EL::check_shadow_ray(const Ray& ray, const shared_ptr<Light>& light) const { real_t min = numeric_limits<real_t>::max(); for (auto & obj : objs) { auto tmp = obj->get_trace(ray, min == numeric_limits<real_t>::max() ? -1 : min); if (tmp) { real_t d = tmp->intersection_dist(); update_min(min, d); } } bool found = false; for (auto &l : lights) { auto tmp = l->get_trace(ray, min == numeric_limits<real_t>::max() ? -1 : min); if (tmp) { real_t d = tmp->intersection_dist(); if (update_min(min, d)) { if (found) return false; } else { if (l == light) return false; } if (l == light) found = true; } } return true; }
#include "render/MCPT_EL.hh" using namespace std; Color MCPT_EL::do_trace(const Ray& ray, int depth, int use_emission) const { if (depth > max_depth) return Color::BLACK; m_assert(fabs(ray.dir.sqr() - 1) < EPS); auto first_trace = find_first(ray, true); if (!first_trace) return Color::BLACK; Vec norm = first_trace->normal(), inter_point = first_trace->intersection_point(); auto surf = first_trace->get_property(); Color diffu = surf->diffuse; real_t forward_density = first_trace->get_forward_density(); m_assert((fabs(norm.sqr() - 1) < EPS)); m_assert(norm.dot(ray.dir) <= 0); if (ray.debug) { print_debug("debug ray: arrive point (%lf, %lf, %lf) \n", inter_point.x, inter_point.y, inter_point.z); } real_t max_color_comp = diffu.get_max(); if (depth > 5 or fabs(max_color_comp) < EPS) {
} real_t r1 = 2 * M_PI * drand48(), r2 = drand48(), r2s = sqrt(r2); Vec u = ((fabs(norm.x) > 0.1 ? Vec(0, 1, 0) : Vec(1, 0, 0)).cross(norm)).get_normalized(), v = norm.cross(u); Vec d = ((u * cos(r1)) * r2s + v * sin(r1) * r2s + norm * (sqrt(1 - r2))).get_normalized(); real_t diffuse_weight = min(1 - surf->specular, 1 - surf->transparency); Color now_diffuse = do_trace(Ray(inter_point - ray.dir * EPS, d), depth + 1) * diffuse_weight; real_t lighting = 0; for (auto & light : lights) { Vec l_src = light->get_src(); real_t l_size = light->get_size(); Vec sw = l_src - inter_point, su = (fabs(sw.x) > 0.1 ? Vec(0, 1, 0) : Vec(1, 0, 0)).get_normalized(), sv = sw.cross(su); real_t cos_a_max = sqrt(1 - ::sqr(l_size) / sw.sqr()); if (!isnormal(cos_a_max)) cos_a_max = 0; real_t eps1 = drand48(), eps2 = drand48(); real_t cos_a = 1 - eps1 + eps1 * cos_a_max, sin_a = sqrt(1 - ::sqr(cos_a)), phi = 2 * M_PI * eps2; Vec dir = su * cos(phi) * sin_a + sv * sin(phi) * sin_a + sw * cos_a; if (dir.dot(norm) < 0) continue; dir.normalize(); if (check_shadow_ray(Ray(inter_point + dir * EPS, dir), light)) { real_t omega = 2 * M_PI * (1 - cos_a_max); lighting += light->intensity * dir.dot(norm) * omega * M_1_PI; } } lighting *= diffuse_weight / 6; m_assert(diffuse_weight >= 0); m_assert(lighting >= 0); Color now_refl = Color::BLACK; if (surf->specular > 0 && !(first_trace->contain())) { Ray new_ray(inter_point - ray.dir * EPS, -norm.reflection(ray.dir), ray.density); m_assert(fabs((-norm.reflection(ray.dir)).sqr() - 1) < EPS); new_ray.debug = ray.debug; Color refl = do_trace(new_ray, depth + 1, 0); now_refl = refl * surf->specular; } Color now_transm = Color::BLACK; if (surf->transparency > EPS) { Ray refl_ray(inter_point - ray.dir * EPS, -norm.reflection(ray.dir), ray.density); refl_ray.debug = ray.debug; Vec tr_dir = norm.transmission(ray.dir, ray.density / forward_density); if (isfinite(tr_dir.x)) { Ray new_ray(inter_point + ray.dir * EPS, tr_dir, forward_density); new_ray.debug = ray.debug; real_t F0 = sqr(0.5) / sqr(ray.density + forward_density); real_t theta = first_trace->contain() ? tr_dir.dot(norm) : ray.dir.dot(norm); real_t Fr = F0 + (1 - F0) * pow(1 + theta, 5); real_t P = 0.25 + Fr * 0.5; if (drand48() < P) { Color refl = do_trace(refl_ray, depth + 1, 0) * surf->specular; now_transm = refl * Fr / P; } else { Color transm = do_trace(new_ray, depth + 1, 0); now_transm = transm * ((1 - Fr) / (1 - P)) * surf->transparency; } } else { Color refl = do_trace(refl_ray, depth + 1) * surf->specular; now_transm = refl; } } return surf->emission * use_emission + diffu * (now_diffuse + now_refl + now_transm) + diffu * lighting; } bool MCPT_EL::check_shadow_ray(const Ray& ray, const shared_ptr<Light>& light) const { real_t min = numeric_limits<real_t>::max(); for (auto & obj : objs) { auto tmp = obj->get_trace(ray, min == numeric_limits<real_t>::max() ? -1 : min); if (tmp) { real_t d = tmp->intersection_dist(); update_min(min, d); } } bool found = false; for (auto &l : lights) { auto tmp = l->get_trace(ray, min == numeric_limits<real_t>::max() ? -1 : min); if (tmp) { real_t d = tmp->intersection_dist(); if (update_min(min, d)) { if (found) return false; } else { if (l == light) return false; } if (l == light) found = true; } } return true; }
if (drand48() < max_color_comp) diffu = diffu * (1.0 / max_color_comp); else return surf->emission * use_emission;
if_condition
[ { "content": "class Color {\n\n\tpublic:\n\n\t\treal_t r = 0, g = 0, b = 0;\n\n\n\n\t\tColor():\n\n\t\t\tColor(EPS, EPS, EPS) { }\n\n\n\n\t\texplicit Color(real_t _r, real_t _g, real_t _b):\n\n\t\t\tr(_r), g(_g), b(_b) {}\n\n\n\n\t\texplicit Color(const Vec& v):\n\n\t\t\tr(v.x), g(v.y), b(v.z) {}\n\n\n\n\t\tsta...
C++
src/xcorr_engine.cpp
dev0x13/ust_x
d030ee40462933b645cee417856306f62cf37a28
#include <xcorr_engine.h> #include <XCorr.h> #include <HilbertTransformer.h> #include <algorithm> static const size_t defects = 14; UST::XCorrEngine::XCorrEngine(size_t window_size_axial_, size_t window_size_lateral_, size_t size1_, size_t size2_) : window_size_axial(window_size_axial_), window_size_lateral(window_size_lateral_), window_size_by_2_axial(window_size_axial_ / 2), window_size_by_2_lateral(window_size_lateral_ / 2), size1(size1_), size2(size2_) { windows = new Complex**[2 * numTasks]; for (size_t i = 0; i < 2 * numTasks; ++i) { windows[i] = new Complex*[window_size_lateral_]; for (size_t j = 0; j < window_size_lateral_; ++j) { windows[i][j] = new Complex[window_size_axial_]; } } hField1 = new Complex*[size1]; hField2 = new Complex*[size1]; for (size_t i = 0; i < size1; ++i) { hField1[i] = new Complex[size2]; hField2[i] = new Complex[size2]; } } UST::XCorrEngine::~XCorrEngine() { for (size_t i = 0; i < 2 * numTasks; ++i) { for (size_t j = 0; j < window_size_lateral; ++j) { delete[] windows[i][j]; } delete[] windows[i]; } delete[] windows; for (size_t i = 0; i < size1; ++i) { delete[] hField1[i]; delete[] hField2[i]; } delete[] hField1; delete[] hField2; } void UST::XCorrEngine::hilbertTask( short **sig1, short **sig2, const size_t begin, const size_t end) { thread_local static dsperado::HilbertTransformer<double> ht(size2); thread_local static UST::Complex *hIn = new Complex[size2]; size_t i, j; double mean1 = 0, mean2 = 0; for (i = begin; i < end; ++i) { for (j = defects; j < size2; ++j) { mean1 += sig1[i][j]; mean2 += sig2[i][j]; } mean1 /= size2 - defects; mean2 /= size2 - defects; for (j = defects; j < size2; ++j) { hIn[j].r = sig1[i][j] - mean1; hIn[j].i = 0; } ht.transform(hIn, hField1[i]); for (j = defects; j < size2; ++j) { hIn[j].r = sig2[i][j] - mean2; hIn[j].i = 0; } ht.transform(hIn, hField2[i]); } } void UST::XCorrEngine::xCorrTask(const size_t begin, const size_t end, size_t taskId) { auto window1 = this->windows[taskId * 2]; auto window2 = this->windows[taskId * 2 + 1]; double tmp1, tmp2; Complex xCorrRes; for (size_t n = begin; n < end; ++n) { for (size_t m = defects; m < size2; ++m) { size_t wj = 0, wk = 0; for (long j = (long)n - window_size_by_2_lateral; j < (long)n + window_size_by_2_lateral; ++j) { for (long k = (long)m - window_size_by_2_axial; k < (long)m + window_size_by_2_axial; ++k) { auto realJ = std::min((long)size1 - 1, std::max(j, (long)0)); auto realK = std::min((long)size2 - 1, std::max(k, (long)0)); window1[wj][wk] = hField1[realJ][realK]; window2[wj][wk] = hField2[realJ][realK]; wk++; } wj++; wk = 0; } xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, 0); tmp1 = std::atan2(xCorrRes.i, xCorrRes.r); xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, 1); tmp2 = std::atan2(xCorrRes.i, xCorrRes.r); xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, -1); tmp2 -= std::atan2(xCorrRes.i, xCorrRes.r); out[n][m] = tmp1 / tmp2; } } } void UST::XCorrEngine::calcShift( short **sig1, short **sig2, double **out) { this->out = out; this->tp.startTaskBlock(numThreads); for (size_t i = 0; i < numThreads; ++i) { auto begin = i * pieceSize, end = begin + pieceSize; this->tp.runTask(&UST::XCorrEngine::hilbertTask, this, sig1, sig2, begin, end); } if (div != 0) { this->hilbertTask(sig1, sig2, size1 - div, size1); } this->tp.wait(); this->tp.startTaskBlock(numThreads); for (size_t i = 0; i < numThreads; ++i) { auto begin = i * pieceSize, end = begin + pieceSize; this->tp.runTask(&UST::XCorrEngine::xCorrTask, this, begin, end, i); } if (div != 0) { this->xCorrTask(size1 - div, size1, numThreads); } this->tp.wait(); }
#include <xcorr_engine.h> #include <XCorr.h> #include <HilbertTransformer.h> #include <algorithm> static const size_t defects = 14; UST::XCorrEngine::XCorrEngine(size_t window_size_axial_, size_t window_size_lateral_, size_t size1_, size_t size2_) : window_size_axial(window_size_axial_), window_size_lateral(window_size_lateral_), window_size_by_2_axial(window_size_axial_ / 2), window_size_by_2_lateral(window_size_lateral_ / 2), size1(size1_), size2(size2_) { windows = new Complex**[2 * numTasks]; for (size_t i = 0; i < 2 * numTasks; ++i) { windows[i] = new Complex*[window_size_lateral_]; for (size_t j = 0; j < window_size_lateral_; ++j) { windows[i][j] = new Complex[window_size_axial_]; } } hField1 = new Complex*[size1]; hField2 = new Complex*[size1]; for (size_t i = 0; i < size1; ++i) { hField1[i] = new Complex[size2]; hField2[i] = new Complex[size2]; } } UST::XCorrEngine::~XCorrEngine() { for (size_t i = 0; i < 2 * numTasks; ++i) { for (size_t j = 0; j < window_size_lateral; ++j) { delete[] windows[i][j]; } delete[] windows[i]; } delete[] windows; for (size_t i = 0; i < size1; ++i) { delete[] hField1[i]; delete[] hField2[i]; } delete[] hField1; delete[] hField2; } void UST::XCorrEngine::hilbertTask( short **sig1, short **sig2, const size_t begin, const size_t end) { thread_local static dsperado::HilbertTransformer<double> ht(size2); thread_local static UST::Complex *hIn = new Complex[size2]; size_t i, j; double mean1 = 0, mean2 = 0; for (i = begin; i < end; ++i) { for (j = defects; j < size2; ++j) { mean1 += sig1[i][j]; mean2 += sig2[i][j]; } mean1 /= size2 - defects; mean2 /= size2 - defects; for (j = defects; j < size2; ++j) { hIn[j].r = sig1[i][j] - mean1; hIn[j].i = 0; } ht.transform(hIn, hField1[i]); for (j = defects; j < size2; ++j) { hIn[j].r = sig2[i][j] - mean2; hIn[j].i = 0; } ht.transform(hIn, hField2[i]); } } void UST::XCorrEngine::xCorrTask(const size_t begin, const size_t end, size_t taskId) { auto window1 = this->windows[taskId * 2]; auto window2 = this->windows[taskId * 2 + 1]; double tmp1, tmp2; Complex xCorrRes; for (size_t n = begin; n < end; ++n) { for (size_t m = defects; m < size2; ++m) { size_t wj = 0, wk = 0;
void UST::XCorrEngine::calcShift( short **sig1, short **sig2, double **out) { this->out = out; this->tp.startTaskBlock(numThreads); for (size_t i = 0; i < numThreads; ++i) { auto begin = i * pieceSize, end = begin + pieceSize; this->tp.runTask(&UST::XCorrEngine::hilbertTask, this, sig1, sig2, begin, end); } if (div != 0) { this->hilbertTask(sig1, sig2, size1 - div, size1); } this->tp.wait(); this->tp.startTaskBlock(numThreads); for (size_t i = 0; i < numThreads; ++i) { auto begin = i * pieceSize, end = begin + pieceSize; this->tp.runTask(&UST::XCorrEngine::xCorrTask, this, begin, end, i); } if (div != 0) { this->xCorrTask(size1 - div, size1, numThreads); } this->tp.wait(); }
for (long j = (long)n - window_size_by_2_lateral; j < (long)n + window_size_by_2_lateral; ++j) { for (long k = (long)m - window_size_by_2_axial; k < (long)m + window_size_by_2_axial; ++k) { auto realJ = std::min((long)size1 - 1, std::max(j, (long)0)); auto realK = std::min((long)size2 - 1, std::max(k, (long)0)); window1[wj][wk] = hField1[realJ][realK]; window2[wj][wk] = hField2[realJ][realK]; wk++; } wj++; wk = 0; } xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, 0); tmp1 = std::atan2(xCorrRes.i, xCorrRes.r); xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, 1); tmp2 = std::atan2(xCorrRes.i, xCorrRes.r); xCorrRes = dsperado::XCorr::XCorr2DComplex<double>( window1, window2, window_size_lateral, window_size_axial, window_size_by_2_lateral, window_size_by_2_axial, -1); tmp2 -= std::atan2(xCorrRes.i, xCorrRes.r); out[n][m] = tmp1 / tmp2; } } }
function_block-function_prefix_line
[ { "content": "struct static_const\n\n{\n\n static constexpr T value{};\n\n};\n\n\n\ntemplate<typename T>\n\nconstexpr T static_const<T>::value;\n\n} // namespace detail\n\n} // namespace nlohmann\n\n\n\n// #include <nlohmann/detail/meta/type_traits.hpp>\n\n\n\n\n\n#include <limits> // numeric_limits\n\n#in...
C++
centreon-engine/test/commands/raw_run_async.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
#include <cstdlib> #include <cstring> #include <exception> #include "com/centreon/engine/commands/raw.hh" #include "com/centreon/engine/commands/set.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/process.hh" #include "test/commands/wait_process.hh" #include "test/unittest.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::commands; static bool run_without_timeout() { std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --timeout=off")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != cmd->get_command_line()))); } static bool run_with_timeout() { std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --timeout=on")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; uint64_t id(cmd->run(cmd->get_command_line(), mac, 1)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_UNKNOWN) || (res.exit_status != process::timeout) || (res.output != "(Process Timeout)"))); } static bool run_with_environment_macros() { config->enable_environment_macros(true); nagios_macros mac; char const* argv = "default_arg"; mac.argv[0] = new char[strlen(argv) + 1]; strcpy(mac.argv[0], argv); std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --check_macros")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); delete[] mac.argv[0]; result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != cmd->get_command_line()))); } static bool run_with_single_quotes() { std::shared_ptr<raw> cmd( new raw(__func__, "'./bin_test_run' '--timeout'='off'")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; uint64_t id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return !((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != "./bin_test_run --timeout=off")); } static bool run_with_double_quotes() { std::shared_ptr<raw> cmd( new raw(__func__, "\"./bin_test_run\" \"--timeout\"=\"off\"")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != "./bin_test_run --timeout=off"))); } int main_test(int argc, char** argv) { (void)argc; (void)argv; if (!run_without_timeout()) throw(engine_error() << "raw::run without timeout failed"); if (!run_with_timeout()) throw(engine_error() << "raw::run with timeout failed"); if (!run_with_environment_macros()) throw(engine_error() << "raw::run with macros failed"); if (!run_with_single_quotes()) throw(engine_error() << "raw::run with single quotes failed"); if (!run_with_double_quotes()) throw(engine_error() << "raw::run with double quotes failed"); return (EXIT_SUCCESS); } int main(int argc, char* argv[]) { unittest utest(argc, argv, &main_test); return (utest.run()); }
#include <cstdlib> #include <cstring> #include <exception> #include "com/centreon/engine/commands/raw.hh" #include "com/centreon/engine/commands/set.hh" #include "com/centreon/engine/exceptions/error.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/process.hh" #include "test/commands/wait_process.hh" #include "test/unittest.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::commands; static bool run_without_timeout() { std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --timeout=off")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != cmd->get_command_line()))); } static bool run_with_timeout() { std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --timeout=on")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; uint64_t id(cmd->run(cmd->get_command_line(), mac, 1)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_UNKNOWN) || (res.exit_status != process::timeout) || (res.output != "(Process Timeout)"))); } static bool run_with_environment_macros() { config->ena
d::shared_ptr<raw> cmd( new raw(__func__, "\"./bin_test_run\" \"--timeout\"=\"off\"")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != "./bin_test_run --timeout=off"))); } int main_test(int argc, char** argv) { (void)argc; (void)argv; if (!run_without_timeout()) throw(engine_error() << "raw::run without timeout failed"); if (!run_with_timeout()) throw(engine_error() << "raw::run with timeout failed"); if (!run_with_environment_macros()) throw(engine_error() << "raw::run with macros failed"); if (!run_with_single_quotes()) throw(engine_error() << "raw::run with single quotes failed"); if (!run_with_double_quotes()) throw(engine_error() << "raw::run with double quotes failed"); return (EXIT_SUCCESS); } int main(int argc, char* argv[]) { unittest utest(argc, argv, &main_test); return (utest.run()); }
ble_environment_macros(true); nagios_macros mac; char const* argv = "default_arg"; mac.argv[0] = new char[strlen(argv) + 1]; strcpy(mac.argv[0], argv); std::shared_ptr<raw> cmd(new raw(__func__, "./bin_test_run --check_macros")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); unsigned long id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); delete[] mac.argv[0]; result const& res = wait_proc.get_result(); return (!((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != cmd->get_command_line()))); } static bool run_with_single_quotes() { std::shared_ptr<raw> cmd( new raw(__func__, "'./bin_test_run' '--timeout'='off'")); wait_process wait_proc(cmd.get()); set::instance().add_command(cmd); nagios_macros mac; uint64_t id(cmd->run(cmd->get_command_line(), mac, 0)); wait_proc.wait(); result const& res = wait_proc.get_result(); return !((res.command_id != id) || (res.exit_code != STATE_OK) || (res.exit_status != process::normal) || (res.output != "./bin_test_run --timeout=off")); } static bool run_with_double_quotes() { st
random
[ { "content": "class timeout : public std::exception {\n\n public:\n\n timeout() noexcept : std::exception() {}\n\n timeout& operator=(const timeout&) = delete;\n\n};\n\n} // namespace exceptions\n\n\n\nCCB_END()\n\n\n\n#endif // !CCB_EXCEPTIONS_TIMEOUT_HH\n", "file_path": "centreon-broker/core/inc/com/c...
C++
core/indigo-core/molecule/src/molecule_inchi_utils.cpp
khyurri/Indigo
82f9ef9f43ca605f7265709e7a9256f1ff468d6c
#include "molecule/molecule_inchi_utils.h" #include "base_cpp/os_sync_wrapper.h" #include "molecule/elements.h" #include "molecule/molecule.h" #include "molecule/molecule_cis_trans.h" using namespace indigo; Array<int> MoleculeInChIUtils::_atom_lables_sorted; Array<int> MoleculeInChIUtils::_atom_lables_ranks; IMPL_ERROR(MoleculeInChIUtils, "InChI utility"); const Array<int>& MoleculeInChIUtils::getLexSortedAtomLables() { _ensureLabelsInitialized(); return _atom_lables_sorted; } const Array<int>& MoleculeInChIUtils::getLexSortedAtomLablesRanks() { _ensureLabelsInitialized(); return _atom_lables_ranks; } void MoleculeInChIUtils::_ensureLabelsInitialized() { if (_atom_lables_sorted.size() == 0) { static ThreadSafeStaticObj<OsLock> lock; OsLocker locker(lock.ref()); if (_atom_lables_sorted.size() == 0) _initializeAtomLabels(); } } void MoleculeInChIUtils::_initializeAtomLabels() { _atom_lables_sorted.reserve(ELEM_MAX); for (int i = ELEM_MIN; i < ELEM_MAX; i++) _atom_lables_sorted.push(i); _atom_lables_sorted.qsort(_compareAtomLabels, NULL); _atom_lables_ranks.resize(ELEM_MAX); _atom_lables_ranks.fffill(); for (int i = 0; i < _atom_lables_sorted.size(); i++) { int label = _atom_lables_sorted[i]; _atom_lables_ranks[label] = i; } } int MoleculeInChIUtils::_compareAtomLabels(int& label1, int& label2, void* context) { if (label1 == ELEM_C && label2 != ELEM_C) return -1; if (label1 != ELEM_C && label2 == ELEM_C) return 1; return strcmp(Element::toString(label1), Element::toString(label2)); } void MoleculeInChIUtils::stableSmallSort(Array<int>& indices, const Array<int>* ranks) { for (int i = 1; i < indices.size(); i++) { int i_value = indices[i]; int i_value_rank = i_value; if (ranks != NULL) i_value_rank = ranks->at(i_value); int j = i - 1; while (j >= 0) { int j_value_rank = indices[j]; if (ranks != NULL) j_value_rank = ranks->at(j_value_rank); if (i_value_rank >= j_value_rank) break; indices[j + 1] = indices[j]; j--; } indices[j + 1] = i_value; } } int MoleculeInChIUtils::compareHydrogens(int hyd1, int hyd2) { if (hyd1 == 0) hyd1 = 256; if (hyd2 == 0) hyd2 = 256; return hyd2 - hyd1; } int MoleculeInChIUtils::getParityInChI(Molecule& mol, int bond) { if (mol.cis_trans.getParity(bond) == 0) throw Error("Specified bond ins't stereogenic"); const Edge& edge = mol.getEdge(bond); const int* subst = mol.cis_trans.getSubstituents(bond); int max_first = std::max(subst[0], subst[1]); int max_second = std::max(subst[2], subst[3]); int value = MoleculeCisTrans::sameside(mol.getAtomXyz(edge.beg), mol.getAtomXyz(edge.end), mol.getAtomXyz(max_first), mol.getAtomXyz(max_second)); if (value > 0) return -1; return 1; }
#include "molecule/molecule_inchi_utils.h" #include "base_cpp/os_sync_wrapper.h" #include "molecule/elements.h" #include "molecule/molecule.h" #include "molecule/molecule_cis_trans.h" using namespace indigo; Array<int> MoleculeInChIUtils::_atom_lables_sorted; Array<int> MoleculeInChIUtils::_atom_lables_ranks; IMPL_ERROR(MoleculeInChIUtils, "InChI utility"); const Array<int>& MoleculeInChIUtils::getLexSortedAtomLables() { _ensureLabelsInitialized(); return _atom_lables_sorted; } const Array<int>& MoleculeInChIUtils::getLexSortedAtomLablesRanks() { _ensureLabelsInitialized(); return _atom_lables_ranks; } void MoleculeInChIUtils::_ensur
_initializeAtomLabels(); } } void MoleculeInChIUtils::_initializeAtomLabels() { _atom_lables_sorted.reserve(ELEM_MAX); for (int i = ELEM_MIN; i < ELEM_MAX; i++) _atom_lables_sorted.push(i); _atom_lables_sorted.qsort(_compareAtomLabels, NULL); _atom_lables_ranks.resize(ELEM_MAX); _atom_lables_ranks.fffill(); for (int i = 0; i < _atom_lables_sorted.size(); i++) { int label = _atom_lables_sorted[i]; _atom_lables_ranks[label] = i; } } int MoleculeInChIUtils::_compareAtomLabels(int& label1, int& label2, void* context) { if (label1 == ELEM_C && label2 != ELEM_C) return -1; if (label1 != ELEM_C && label2 == ELEM_C) return 1; return strcmp(Element::toString(label1), Element::toString(label2)); } void MoleculeInChIUtils::stableSmallSort(Array<int>& indices, const Array<int>* ranks) { for (int i = 1; i < indices.size(); i++) { int i_value = indices[i]; int i_value_rank = i_value; if (ranks != NULL) i_value_rank = ranks->at(i_value); int j = i - 1; while (j >= 0) { int j_value_rank = indices[j]; if (ranks != NULL) j_value_rank = ranks->at(j_value_rank); if (i_value_rank >= j_value_rank) break; indices[j + 1] = indices[j]; j--; } indices[j + 1] = i_value; } } int MoleculeInChIUtils::compareHydrogens(int hyd1, int hyd2) { if (hyd1 == 0) hyd1 = 256; if (hyd2 == 0) hyd2 = 256; return hyd2 - hyd1; } int MoleculeInChIUtils::getParityInChI(Molecule& mol, int bond) { if (mol.cis_trans.getParity(bond) == 0) throw Error("Specified bond ins't stereogenic"); const Edge& edge = mol.getEdge(bond); const int* subst = mol.cis_trans.getSubstituents(bond); int max_first = std::max(subst[0], subst[1]); int max_second = std::max(subst[2], subst[3]); int value = MoleculeCisTrans::sameside(mol.getAtomXyz(edge.beg), mol.getAtomXyz(edge.end), mol.getAtomXyz(max_first), mol.getAtomXyz(max_second)); if (value > 0) return -1; return 1; }
eLabelsInitialized() { if (_atom_lables_sorted.size() == 0) { static ThreadSafeStaticObj<OsLock> lock; OsLocker locker(lock.ref()); if (_atom_lables_sorted.size() == 0)
function_block-random_span
[ { "content": " final Indigo indigo;\n", "file_path": "api/java/indigo-inchi/src/main/java/com/epam/indigo/IndigoInchi.java", "rank": 0, "score": 207685.95766331634 }, { "content": "char *inchi__strnset( char *s, int val, size_t length )\n\n{\n\n char *ps = s;\n\n while (length-- && ...
C++
libcore/include/sirikata/core/trace/Trace.hpp
sirikata/sirikata
3a0d54a8c4778ad6e25ef031d461b2bc3e264860
#ifndef _SIRIKATA_CORE_TRACE_HPP_ #define _SIRIKATA_CORE_TRACE_HPP_ #include <sirikata/core/util/Platform.hpp> #include <sirikata/core/util/Thread.hpp> #include <sirikata/core/util/AtomicTypes.hpp> #include <sirikata/core/network/ObjectMessage.hpp> #include <sirikata/core/trace/BatchedBuffer.hpp> namespace Sirikata { namespace Trace { #define TRACE_DROP(nam) ((mContext->trace()->drops.n[::Sirikata::Trace::Drops::nam]=#nam )&&++(mContext->trace()->drops.d[::Sirikata::Trace::Drops::nam])); SILOG(drop,insane,#nam) struct Drops { enum { OH_DROPPED_AT_SEND, OH_DROPPED_AT_RECEIVE_QUEUE, SPACE_DROPPED_AT_MAIN_STRAND_CROSSING, DROPPED_AT_FORWARDED_LOCALLY, DROPPED_DURING_FORWARDING, DROPPED_DURING_FORWARDING_ROUTING, DROPPED_AT_SPACE_ENQUEUED, DROPPED_CSFQ_OVERFLOW, DROPPED_CSFQ_PROBABILISTIC, NUM_DROPS }; uint64 d[NUM_DROPS]; const char*n[NUM_DROPS]; Drops() { memset(d,0,NUM_DROPS*sizeof(uint64)); memset(n,0,NUM_DROPS*sizeof(const char*)); } void output(); }; #define ProximityTag 0 #define ObjectLocationTag 1 #define ServerDatagramQueuedTag 4 #define ServerDatagramSentTag 5 #define ServerDatagramReceivedTag 6 #define SegmentationChangeTag 10 #define MigrationBeginTag 11 #define MigrationAckTag 12 #define MigrationRoundTripTag 18 #define ServerLocationTag 13 #define ServerObjectEventTag 14 #define ObjectSegmentationCraqLookupRequestAnalysisTag 15 #define ObjectSegmentationProcessedRequestAnalysisTag 16 #define ObjectPingTag 17 #define ObjectPingCreatedTag 32 #define ObjectHitPointTag 34 #define OSegTrackedSetResultAnalysisTag 19 #define OSegShutdownEventTag 20 #define ObjectGeneratedLocationTag 22 #define OSegCacheResponseTag 23 #define OSegLookupNotOnServerAnalysisTag 24 #define OSegCumulativeTraceAnalysisTag 25 #define MessageTimestampTag 30 #define MessageCreationTimestampTag 31 #define ObjectConnectedTag 33 enum MessagePath { NONE, CREATED, DESTROYED, OH_HIT_NETWORK, OH_DROPPED_AT_SEND, OH_NET_RECEIVED, OH_DROPPED_AT_RECEIVE_QUEUE, OH_RECEIVED, SPACE_DROPPED_AT_MAIN_STRAND_CROSSING, HANDLE_OBJECT_HOST_MESSAGE, HANDLE_SPACE_MESSAGE, FORWARDED_LOCALLY, DROPPED_AT_FORWARDED_LOCALLY, FORWARDING_STARTED, FORWARDED_LOCALLY_SLOW_PATH, DROPPED_DURING_FORWARDING, OSEG_CACHE_CHECK_STARTED, OSEG_CACHE_CHECK_FINISHED, OSEG_LOOKUP_STARTED, OSEG_CACHE_LOOKUP_FINISHED, OSEG_SERVER_LOOKUP_FINISHED, OSEG_LOOKUP_FINISHED, SPACE_TO_SPACE_ENQUEUED, DROPPED_AT_SPACE_ENQUEUED, SPACE_TO_SPACE_HIT_NETWORK, SPACE_TO_SPACE_READ_FROM_NET, SPACE_TO_SPACE_SMR_DEQUEUED, SPACE_TO_OH_ENQUEUED, NUM_PATHS }; class SIRIKATA_EXPORT Trace { public: Drops drops; ~Trace(); static void InitOptions(); Trace(const String& filename); #define CREATE_TRACE_CHECK_DECL(___name) \ bool check ## ___name () const; #define CREATE_TRACE_EVAL_DECL(___name, ...) \ void ___name( __VA_ARGS__ ); #define CREATE_TRACE_DECL(___name, ...) \ CREATE_TRACE_CHECK_DECL(___name) \ CREATE_TRACE_EVAL_DECL(___name, __VA_ARGS__) #define CREATE_TRACE_CHECK_DEF(__klass, ___name , ___log_var) \ bool __klass :: check ## ___name () const { \ return ___log_var->as<bool>(); \ } #define CREATE_TRACE_EVAL_DEF(__klass, ___name , ... ) \ void __klass :: ___name ( __VA_ARGS__ ) #define CREATE_TRACE_DEF(__klass, ___name , ___log_var, ... ) \ CREATE_TRACE_CHECK_DEF(__klass, ___name, ___log_var) \ CREATE_TRACE_EVAL_DEF(__klass, ___name, __VA_ARGS__) CREATE_TRACE_DECL(timestampMessageCreation, const Time&t, uint64 packetId, MessagePath path, ObjectMessagePort optionalMessageSourcePort=0, ObjectMessagePort optionalMessageDestPort=0); CREATE_TRACE_DECL(timestampMessage, const Time&t, uint64 packetId, MessagePath path); void writeRecord(uint16 type_hint, BatchedBuffer::IOVec* data, uint32 iovcnt); template<typename T> void writeRecord(uint16 type_hint, const T& pl) { if (mShuttingDown) return; std::string serialized_pl; bool serialized_success = pl.SerializeToString(&serialized_pl); assert(serialized_success); const uint32 num_data = 1; BatchedBuffer::IOVec data_vec[num_data] = { BatchedBuffer::IOVec(&(serialized_pl[0]), serialized_pl.size()) }; writeRecord(type_hint, data_vec, num_data); } public: void prepareShutdown(); void shutdown(); private: void storageThread(const String& filename); BatchedBuffer data; bool mShuttingDown; Thread* mStorageThread; Sirikata::AtomicValue<bool> mFinishStorage; static OptionValue* mLogMessage; }; } #define TRACE(___trace, ___name, ...) \ { \ if ( ___trace-> check ## ___name () ) \ ___trace-> ___name ( __VA_ARGS__ ); \ } while(0) #define CONTEXT_TRACE(___name, ...) \ TRACE( mContext->trace(), ___name, mContext->simTime(), __VA_ARGS__) #define CONTEXT_TRACE_NO_TIME(___name, ...) \ TRACE( mContext->trace(), ___name, __VA_ARGS__) } #ifdef CBR_TIMESTAMP_PACKETS #define TIMESTAMP_FULL(trace, time, packetId, path) TRACE(trace, timestampMessage, time, packetId, path) #define TIMESTAMP_SIMPLE(packetId, path) TIMESTAMP_FULL(mContext->trace(), mContext->simTime(), packetId, path) #define TIMESTAMP(packet, path) TIMESTAMP_SIMPLE(packet->unique(), path) #define TIMESTAMP_START(prefix, packet) \ Sirikata::uint64 prefix ## _uniq = packet->unique(); #define TIMESTAMP_END(prefix, path) TIMESTAMP_SIMPLE(prefix ## _uniq, path) #define TIMESTAMP_PAYLOAD(packet, path) TIMESTAMP_SIMPLE(packet->payload_id(), path) #define TIMESTAMP_PAYLOAD_START(prefix, packet) \ Sirikata::uint64 prefix ## _uniq = packet->payload_id(); #define TIMESTAMP_PAYLOAD_END(prefix, path) TIMESTAMP_SIMPLE(prefix ## _uniq, path) #define TIMESTAMP_CREATED(packet, path) TRACE(mContext->trace(), timestampMessageCreation, mContext->simTime(), packet->unique(), path, packet->source_port(), packet->dest_port()) #else #define TIMESTAMP_FULL(trace, time, packetId, path) #define TIMESTAMP_SIMPLE(packetId, path) #define TIMESTAMP(packet, path) #define TIMESTAMP_START(prefix, packet) #define TIMESTAMP_END(prefix, path) #define TIMESTAMP_PAYLOAD(packet, path) #define TIMESTAMP_PAYLOAD_START(prefix, packet) #define TIMESTAMP_PAYLOAD_END(prefix, path) #define TIMESTAMP_CREATED(packet, path) #endif #endif
#ifndef _SIRIKATA_CORE_TRACE_HPP_ #define _SIRIKATA_CORE_TRACE_HPP_ #include <sirikata/core/util/Platform.hpp> #include <sirikata/core/util/Thread.hpp> #include <sirikata/core/util/AtomicTypes.hpp> #include <sirikata/core/network/ObjectMessage.hpp> #include <sirikata/core/trace/BatchedBuffer.hpp> namespace Sirikata { namespace Trace { #define TRACE_DROP(nam) ((mContext->trace()->drops.n[::Sirikata::Trace::Drops::nam]=#nam )&&++(mContext->trace()->drops.d[::Sirikata::Trace::Drops::nam])); SILOG(drop,insane,#nam) struct Drops { enum { OH_DROPPED_AT_SEND, OH_DROPPED_AT_RECEIVE_QUEUE, SPACE_DROPPED_AT_MAIN_STRAND_CROSSING, DROPPED_AT_FORWARDED_LOCALLY, DROPPED_DURING_FORWARDING,
ObjectMessagePort optionalMessageDestPort=0); CREATE_TRACE_DECL(timestampMessage, const Time&t, uint64 packetId, MessagePath path); void writeRecord(uint16 type_hint, BatchedBuffer::IOVec* data, uint32 iovcnt); template<typename T> void writeRecord(uint16 type_hint, const T& pl) { if (mShuttingDown) return; std::string serialized_pl; bool serialized_success = pl.SerializeToString(&serialized_pl); assert(serialized_success); const uint32 num_data = 1; BatchedBuffer::IOVec data_vec[num_data] = { BatchedBuffer::IOVec(&(serialized_pl[0]), serialized_pl.size()) }; writeRecord(type_hint, data_vec, num_data); } public: void prepareShutdown(); void shutdown(); private: void storageThread(const String& filename); BatchedBuffer data; bool mShuttingDown; Thread* mStorageThread; Sirikata::AtomicValue<bool> mFinishStorage; static OptionValue* mLogMessage; }; } #define TRACE(___trace, ___name, ...) \ { \ if ( ___trace-> check ## ___name () ) \ ___trace-> ___name ( __VA_ARGS__ ); \ } while(0) #define CONTEXT_TRACE(___name, ...) \ TRACE( mContext->trace(), ___name, mContext->simTime(), __VA_ARGS__) #define CONTEXT_TRACE_NO_TIME(___name, ...) \ TRACE( mContext->trace(), ___name, __VA_ARGS__) } #ifdef CBR_TIMESTAMP_PACKETS #define TIMESTAMP_FULL(trace, time, packetId, path) TRACE(trace, timestampMessage, time, packetId, path) #define TIMESTAMP_SIMPLE(packetId, path) TIMESTAMP_FULL(mContext->trace(), mContext->simTime(), packetId, path) #define TIMESTAMP(packet, path) TIMESTAMP_SIMPLE(packet->unique(), path) #define TIMESTAMP_START(prefix, packet) \ Sirikata::uint64 prefix ## _uniq = packet->unique(); #define TIMESTAMP_END(prefix, path) TIMESTAMP_SIMPLE(prefix ## _uniq, path) #define TIMESTAMP_PAYLOAD(packet, path) TIMESTAMP_SIMPLE(packet->payload_id(), path) #define TIMESTAMP_PAYLOAD_START(prefix, packet) \ Sirikata::uint64 prefix ## _uniq = packet->payload_id(); #define TIMESTAMP_PAYLOAD_END(prefix, path) TIMESTAMP_SIMPLE(prefix ## _uniq, path) #define TIMESTAMP_CREATED(packet, path) TRACE(mContext->trace(), timestampMessageCreation, mContext->simTime(), packet->unique(), path, packet->source_port(), packet->dest_port()) #else #define TIMESTAMP_FULL(trace, time, packetId, path) #define TIMESTAMP_SIMPLE(packetId, path) #define TIMESTAMP(packet, path) #define TIMESTAMP_START(prefix, packet) #define TIMESTAMP_END(prefix, path) #define TIMESTAMP_PAYLOAD(packet, path) #define TIMESTAMP_PAYLOAD_START(prefix, packet) #define TIMESTAMP_PAYLOAD_END(prefix, path) #define TIMESTAMP_CREATED(packet, path) #endif #endif
DROPPED_DURING_FORWARDING_ROUTING, DROPPED_AT_SPACE_ENQUEUED, DROPPED_CSFQ_OVERFLOW, DROPPED_CSFQ_PROBABILISTIC, NUM_DROPS }; uint64 d[NUM_DROPS]; const char*n[NUM_DROPS]; Drops() { memset(d,0,NUM_DROPS*sizeof(uint64)); memset(n,0,NUM_DROPS*sizeof(const char*)); } void output(); }; #define ProximityTag 0 #define ObjectLocationTag 1 #define ServerDatagramQueuedTag 4 #define ServerDatagramSentTag 5 #define ServerDatagramReceivedTag 6 #define SegmentationChangeTag 10 #define MigrationBeginTag 11 #define MigrationAckTag 12 #define MigrationRoundTripTag 18 #define ServerLocationTag 13 #define ServerObjectEventTag 14 #define ObjectSegmentationCraqLookupRequestAnalysisTag 15 #define ObjectSegmentationProcessedRequestAnalysisTag 16 #define ObjectPingTag 17 #define ObjectPingCreatedTag 32 #define ObjectHitPointTag 34 #define OSegTrackedSetResultAnalysisTag 19 #define OSegShutdownEventTag 20 #define ObjectGeneratedLocationTag 22 #define OSegCacheResponseTag 23 #define OSegLookupNotOnServerAnalysisTag 24 #define OSegCumulativeTraceAnalysisTag 25 #define MessageTimestampTag 30 #define MessageCreationTimestampTag 31 #define ObjectConnectedTag 33 enum MessagePath { NONE, CREATED, DESTROYED, OH_HIT_NETWORK, OH_DROPPED_AT_SEND, OH_NET_RECEIVED, OH_DROPPED_AT_RECEIVE_QUEUE, OH_RECEIVED, SPACE_DROPPED_AT_MAIN_STRAND_CROSSING, HANDLE_OBJECT_HOST_MESSAGE, HANDLE_SPACE_MESSAGE, FORWARDED_LOCALLY, DROPPED_AT_FORWARDED_LOCALLY, FORWARDING_STARTED, FORWARDED_LOCALLY_SLOW_PATH, DROPPED_DURING_FORWARDING, OSEG_CACHE_CHECK_STARTED, OSEG_CACHE_CHECK_FINISHED, OSEG_LOOKUP_STARTED, OSEG_CACHE_LOOKUP_FINISHED, OSEG_SERVER_LOOKUP_FINISHED, OSEG_LOOKUP_FINISHED, SPACE_TO_SPACE_ENQUEUED, DROPPED_AT_SPACE_ENQUEUED, SPACE_TO_SPACE_HIT_NETWORK, SPACE_TO_SPACE_READ_FROM_NET, SPACE_TO_SPACE_SMR_DEQUEUED, SPACE_TO_OH_ENQUEUED, NUM_PATHS }; class SIRIKATA_EXPORT Trace { public: Drops drops; ~Trace(); static void InitOptions(); Trace(const String& filename); #define CREATE_TRACE_CHECK_DECL(___name) \ bool check ## ___name () const; #define CREATE_TRACE_EVAL_DECL(___name, ...) \ void ___name( __VA_ARGS__ ); #define CREATE_TRACE_DECL(___name, ...) \ CREATE_TRACE_CHECK_DECL(___name) \ CREATE_TRACE_EVAL_DECL(___name, __VA_ARGS__) #define CREATE_TRACE_CHECK_DEF(__klass, ___name , ___log_var) \ bool __klass :: check ## ___name () const { \ return ___log_var->as<bool>(); \ } #define CREATE_TRACE_EVAL_DEF(__klass, ___name , ... ) \ void __klass :: ___name ( __VA_ARGS__ ) #define CREATE_TRACE_DEF(__klass, ___name , ___log_var, ... ) \ CREATE_TRACE_CHECK_DEF(__klass, ___name, ___log_var) \ CREATE_TRACE_EVAL_DEF(__klass, ___name, __VA_ARGS__) CREATE_TRACE_DECL(timestampMessageCreation, const Time&t, uint64 packetId, MessagePath path, ObjectMessagePort optionalMessageSourcePort=0,
random
[ { "content": "struct Batch {\n\n static const uint16 max_size = 65535;\n\n uint16 size;\n\n T items[max_size];\n\n\n\n Batch() : size(0) {}\n\n\n\n bool full() const {\n\n return (size >= max_size);\n\n }\n\n\n\n uint32 avail() const {\n\n return max_size - size;\n\n }\n\n}...
C++
source/MaterialXContrib/MaterialXMaya/ShadingNodeOverrides.cpp
muenstc/MaterialX
b8365086a738fddae683065d78f65410aacd0dc4
#include "ShadingNodeOverrides.h" #include "MaterialXNode.h" #include "Plugin.h" #include "MaterialXUtil.h" #include "MayaUtil.h" #include <maya/MDGModifier.h> #include <maya/MGlobal.h> #include <maya/MShaderManager.h> #include <maya/MPxShadingNodeOverride.h> #include <maya/MPxSurfaceShadingNodeOverride.h> #include <MaterialXFormat/Util.h> #include <MaterialXGenShader/Util.h> #include <MaterialXGenShader/HwShaderGenerator.h> #include <MaterialXGenOgsXml/OgsFragment.h> #include <MaterialXGenOgsXml/OgsXmlGenerator.h> #include <MaterialXRender/ImageHandler.h> #include <iostream> namespace mx = MaterialX; namespace MaterialXMaya { const MString SurfaceOverride::REGISTRANT_ID = "materialXSurface", SurfaceOverride::DRAW_CLASSIFICATION = "drawdb/shader/surface/materialX"; const MString TextureOverride::REGISTRANT_ID = "materialXTexture", TextureOverride::DRAW_CLASSIFICATION = "drawdb/shader/texture/2d/materialX"; namespace { MStatus bindFileTexture(MHWRender::MShaderInstance& shaderInstance, const std::string& parameterName, const mx::FileSearchPath& searchPath, const std::string& fileName, const MHWRender::MSamplerStateDesc& samplerDescription, MHWRender::MTextureDescription& textureDescription, const mx::StringVec* udimIdentifiers = nullptr) { MStatus status = MStatus::kFailure; MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); MHWRender::MTextureManager* const textureManager = renderer ? renderer->getTextureManager() : nullptr; if (textureManager) { MayaUtil::TextureUniquePtr texturePtr; if (udimIdentifiers && !udimIdentifiers->empty()) { const std::vector<mx::Vector2> udimCoordinates{mx::getUdimCoordinates(*udimIdentifiers)}; if (udimCoordinates.size() != udimIdentifiers->size()) { throw mx::Exception("Failed to resolve UDIM information for file: " + fileName); } mx::StringResolverPtr resolver = mx::StringResolver::create(); MStringArray mTilePaths; MFloatArray mTilePositions; for (size_t i = 0; i < udimIdentifiers->size(); ++i) { resolver->setUdimString((*udimIdentifiers)[i]); mx::FilePath resolvedPath = MaterialXUtil::findInSubdirectories( searchPath, resolver->resolve(fileName, mx::FILENAME_TYPE_STRING)); mTilePaths.append(resolvedPath.asString().c_str()); mTilePositions.append(udimCoordinates[i][0]); mTilePositions.append(udimCoordinates[i][1]); } mx::Vector2 scaleUV; mx::Vector2 offsetUV; mx::getUdimScaleAndOffset(udimCoordinates, scaleUV, offsetUV); unsigned int udimBakeWidth = 4096; unsigned int udimBakeHeight = 4096; const float ratio = scaleUV[1] / scaleUV[0]; if (ratio > 1.0) { udimBakeHeight = static_cast<unsigned int>(std::truncf(static_cast<float>(udimBakeHeight) * ratio)); } else { udimBakeWidth = static_cast<unsigned int>(std::truncf(static_cast<float>(udimBakeWidth) * ratio)); } static const MColor undefinedColor; MStringArray failedTilePaths; MFloatArray uvScaleOffset; texturePtr.reset(textureManager->acquireTiledTexture(fileName.c_str(), mTilePaths, mTilePositions, undefinedColor, udimBakeWidth, udimBakeHeight, failedTilePaths, uvScaleOffset)); } else { const mx::FilePath imagePath = MaterialXUtil::findInSubdirectories(searchPath, fileName); if (!imagePath.isEmpty()) { texturePtr.reset( textureManager->acquireTexture(imagePath.asString().c_str(), mx::EMPTY_STRING.c_str())); } } MHWRender::MTextureAssignment textureAssignment; textureAssignment.texture = texturePtr.get(); if (texturePtr) { texturePtr->textureDescription(textureDescription); } else { MString message("*Unable to find image file: "); message += fileName.c_str(); message += " in search paths: "; message += searchPath.asString().c_str(); MGlobal::displayError(message); } status = shaderInstance.setParameter(parameterName.c_str(), textureAssignment); if (!status) { MString message("*Unable to bind image file: "); message += fileName.c_str(); MGlobal::displayError(message); } } if (MayaUtil::SamplerUniquePtr samplerState{MHWRender::MStateManager::acquireSamplerState(samplerDescription)}) { const std::string samplerParameterName = mx::OgsXmlGenerator::textureToSamplerName(parameterName); status = shaderInstance.setParameter(samplerParameterName.c_str(), *samplerState); } return status; } void bindEnvironmentLighting(MHWRender::MShaderInstance& shaderInstance, const MStringArray& parameterList, const mx::FileSearchPath& imageSearchPath, const MaterialXNode& node) { MHWRender::MSamplerStateDesc samplerDescription; samplerDescription.filter = MHWRender::MSamplerState::kAnisotropic; samplerDescription.maxAnisotropy = 16; MStatus status; MHWRender::MTextureDescription textureDescription; if (parameterList.indexOf(mx::HW::ENV_IRRADIANCE.c_str()) >= 0) { status = bindFileTexture(shaderInstance, mx::HW::ENV_IRRADIANCE, imageSearchPath, node.getEnvIrradianceFileName().asChar(), samplerDescription, textureDescription, nullptr); } if (parameterList.indexOf(mx::HW::ENV_RADIANCE.c_str()) >= 0) { status = bindFileTexture(shaderInstance, mx::HW::ENV_RADIANCE, imageSearchPath, node.getEnvRadianceFileName().asChar(), samplerDescription, textureDescription, nullptr); if (status == MStatus::kSuccess) { if (parameterList.indexOf(mx::HW::ENV_RADIANCE_MIPS.c_str()) >= 0) { const int mipCount = static_cast<int>(std::log2(std::max(textureDescription.fWidth, textureDescription.fHeight))) + 1; status = shaderInstance.setParameter(mx::HW::ENV_RADIANCE_MIPS.c_str(), mipCount); } if (parameterList.indexOf(mx::HW::ENV_RADIANCE_SAMPLES.c_str()) >= 0) { constexpr int envSamples = 16; status = shaderInstance.setParameter(mx::HW::ENV_RADIANCE_SAMPLES.c_str(), envSamples); } } } if (parameterList.indexOf(mx::HW::ENV_MATRIX.c_str()) >= 0) { constexpr float Y_ROTATION_PI[4][4] { -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; static const MFloatMatrix ENV_MATRIX(Y_ROTATION_PI); status = shaderInstance.setParameter(mx::HW::ENV_MATRIX.c_str(), ENV_MATRIX); } } } template <class BASE> ShadingNodeOverride<BASE>::ShadingNodeOverride(const MObject& obj) : BASE(obj) , _object(obj) { } template <class BASE> ShadingNodeOverride<BASE>::~ShadingNodeOverride() { } template <class BASE> MString ShadingNodeOverride<BASE>::fragmentName() const { MStatus status; MFnDependencyNode depNode(_object, &status); const auto* const node = dynamic_cast<MaterialXNode*>(depNode.userNode()); const OgsFragment* const data = node ? node->getOgsFragment() : nullptr; if (data) { return data->getLightRigName().empty() ? data->getFragmentName().c_str() : data->getLightRigName().c_str(); } return ""; } template <class BASE> bool ShadingNodeOverride<BASE>::valueChangeRequiresFragmentRebuild(const MPlug* plug) const { if ( *plug == MaterialXNode::DOCUMENT_ATTRIBUTE || *plug == MaterialXNode::ELEMENT_ATTRIBUTE || *plug == MaterialXNode::ENV_RADIANCE_ATTRIBUTE || *plug == MaterialXNode::ENV_IRRADIANCE_ATTRIBUTE ) { return true; } return BASE::valueChangeRequiresFragmentRebuild(plug); } template <class BASE> void ShadingNodeOverride<BASE>::updateShader(MHWRender::MShaderInstance& shaderInstance, const MHWRender::MAttributeParameterMappingList& mappings) { MStatus status; MFnDependencyNode depNode(_object, &status); const auto* const node = dynamic_cast<MaterialXNode*>(depNode.userNode()); if (!node) { return; } const OgsFragment* const ogsFragment = node->getOgsFragment(); if (!ogsFragment) { return; } MStringArray parameterList; shaderInstance.parameterList(parameterList); mx::FilePath documentPath(node->getDocumentFilePath().asChar()); documentPath = documentPath.getParentPath(); mx::FileSearchPath imageSearchPath = Plugin::instance().getResourceSearchPath(); mx::FileSearchPath lightSearchPath = Plugin::instance().getLightSearchPath(); imageSearchPath.prepend(documentPath); lightSearchPath.prepend(documentPath); bindEnvironmentLighting(shaderInstance, parameterList, lightSearchPath, *node); mx::DocumentPtr document = ogsFragment->getDocument(); mx::flattenFilenames(document, imageSearchPath); mx::ValuePtr udimSetValue = document->getGeomPropValue("udimset"); const mx::StringVec* udimIdentifiers = nullptr; if (udimSetValue && udimSetValue->isA<mx::StringVec>()) { udimIdentifiers = &(udimSetValue->asA<mx::StringVec>()); } const std::vector<MSamplerState::TextureAddress> addressModes { MSamplerState::TextureAddress::kTexBorder, MSamplerState::TextureAddress::kTexClamp, MSamplerState::TextureAddress::kTexWrap, MSamplerState::TextureAddress::kTexMirror }; const std::vector<MHWRender::MSamplerState::TextureFilter> filterModes { MHWRender::MSamplerState::kMinMagMipPoint, MHWRender::MSamplerState::kMinMagMipLinear, MHWRender::MSamplerState::kAnisotropic }; const mx::StringMap& inputs = ogsFragment->getPathInputMap(); for (const auto& input : inputs) { const std::string& elementPath = input.first; mx::ElementPtr element = document->getDescendant(elementPath); if (!element) { std::string nodePath = mx::parentNamePath(elementPath); mx::ElementPtr uniformParent = document->getDescendant(nodePath); if (uniformParent) { mx::NodePtr uniformNode = uniformParent->asA<mx::Node>(); if (uniformNode) { mx::StringVec pathVec = mx::splitNamePath(elementPath); element = uniformNode->addInputFromNodeDef(pathVec[pathVec.size() - 1]); } } if (!element) { continue; } } mx::ValueElementPtr valueElement = element->asA<mx::ValueElement>(); if (!valueElement) { continue; } const std::string& inputName = input.second; const MHWRender::MAttributeParameterMapping* const mapping = mappings.findByParameterName(inputName.c_str()); const MString resolvedName = mapping ? mapping->resolvedParameterName() : inputName.c_str(); mx::ValuePtr mtxValue = valueElement->getValue(); if (mtxValue) { if (mtxValue->isA<mx::Matrix44>()) { mx::Matrix44 matrix44 = mtxValue->asA<mx::Matrix44>(); MFloatMatrix mayaValue; for (unsigned int i = 0; i < 4; i++) { for (unsigned int j = 0; j < 4; j++) { mayaValue[i][j] = matrix44[i][j]; } } status = shaderInstance.setParameter(resolvedName, mayaValue); } else if (mtxValue->isA<mx::Matrix33>()) { mx::Matrix33 matrix33 = mtxValue->asA<mx::Matrix33>(); MFloatMatrix mayaValue; mayaValue.setToIdentity(); for (unsigned int i = 0; i < 3; i++) { for (unsigned int j = 0; j < 3; j++) { mayaValue[i][j] = matrix33[i][j]; } } std::string matrix4Name = OgsFragment::getMatrix4Name(resolvedName.asChar()); status = shaderInstance.setParameter(matrix4Name.c_str(), mayaValue); } else if (valueElement->getType() == mx::FILENAME_TYPE_STRING) { const std::string textureParameterName(resolvedName.asChar()); const std::string& valueString = valueElement->getValueString(); if (!valueString.empty()) { MHWRender::MTextureDescription textureDescription; mx::ImageSamplingProperties samplingProperties = ogsFragment->getImageSamplingProperties(textureParameterName); MHWRender::MSamplerStateDesc samplerDescription; samplerDescription.borderColor[0] = samplingProperties.defaultColor[0]; samplerDescription.borderColor[1] = samplingProperties.defaultColor[1]; samplerDescription.borderColor[2] = samplingProperties.defaultColor[2]; samplerDescription.borderColor[3] = samplingProperties.defaultColor[3]; samplerDescription.addressV = MSamplerState::TextureAddress::kTexWrap; if (samplingProperties.vaddressMode != mx::ImageSamplingProperties::AddressMode::UNSPECIFIED) { samplerDescription.addressV = addressModes[static_cast<int>(samplingProperties.vaddressMode)]; } samplerDescription.addressU = MSamplerState::TextureAddress::kTexWrap; if (samplingProperties.uaddressMode != mx::ImageSamplingProperties::AddressMode::UNSPECIFIED) { samplerDescription.addressU = addressModes[static_cast<int>(samplingProperties.uaddressMode)]; } samplerDescription.filter = MHWRender::MSamplerState::kMinMagMipLinear; samplerDescription.maxAnisotropy = 16; if (samplingProperties.filterType != mx::ImageSamplingProperties::FilterType::UNSPECIFIED) { samplerDescription.filter = filterModes[static_cast<int>(samplingProperties.filterType)]; } status = bindFileTexture(shaderInstance, textureParameterName, imageSearchPath, valueString, samplerDescription, textureDescription, udimIdentifiers); } } } } } template class ShadingNodeOverride<MHWRender::MPxShadingNodeOverride>; template class ShadingNodeOverride<MHWRender::MPxSurfaceShadingNodeOverride>; MHWRender::MPxSurfaceShadingNodeOverride* SurfaceOverride::creator(const MObject& obj) { std::cout.rdbuf(std::cerr.rdbuf()); return new SurfaceOverride(obj); } MString SurfaceOverride::transparencyParameter() const { return mx::OgsXmlGenerator::VP_TRANSPARENCY_NAME.c_str(); } MHWRender::MPxShadingNodeOverride* TextureOverride::creator(const MObject& obj) { std::cout.rdbuf(std::cerr.rdbuf()); return new TextureOverride(obj); } }
#include "ShadingNodeOverrides.h" #include "MaterialXNode.h" #include "Plugin.h" #include "MaterialXUtil.h" #include "MayaUtil.h" #include <maya/MDGModifier.h> #include <maya/MGlobal.h> #include <maya/MShaderManager.h> #include <maya/MPxShadingNodeOverride.h> #include <maya/MPxSurfaceShadingNodeOverride.h> #include <MaterialXFormat/Util.h> #include <MaterialXGenShader/Util.h> #include <MaterialXGenShader/HwShaderGenerator.h> #include <MaterialXGenOgsXml/OgsFragment.h> #include <MaterialXGenOgsXml/OgsXmlGenerator.h> #include <MaterialXRender/ImageHandler.h> #include <iostream> namespace mx = MaterialX; namespace MaterialXMaya { const MString SurfaceOverride::REGISTRANT_ID = "materialXSurface", SurfaceOverride::DRAW_CLASSIFICATION = "drawdb/shader/surface/materialX"; const MString TextureOverride::REGISTRANT_ID = "materialXTexture", TextureOverride::DRAW_CLASSIFICATION = "drawdb/shader/texture/2d/materialX"; namespace { MStatus bindFileTexture(MHWRender::MShaderInstance& shaderInstance, const std::string& parameterName, const mx::FileSearchPath& searchPath, const std::string& fileName, const MHWRender::MSamplerStateDesc& samplerDescription, MHWRender::MTextureDescription& textureDescription, const mx::StringVec* udimIdentifiers = nullptr) { MStatus status = MStatus::kFailure; MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); MHWRender::MTextureManager* const textureManager = renderer ? renderer->getTextureManager() : nullptr; if (textureManager) { MayaUtil::TextureUniquePtr texturePtr; if (udimIdentifiers && !udimIdentifiers->empty()) { const std::vector<mx::Vector2> udimCoordinates{mx::getUdimCoordinates(*udimIdentifiers)}; if (udimCoordinates.size() != udimIdentifiers->size()) { throw mx::Exception("Failed to resolve UDIM information for file: " + fileName); } mx::StringResolverPtr resolver = mx::StringResolver::create(); MStringArray mTilePaths; MFloatArray mTilePositions; for (size_t i = 0; i < udimIdentifiers->size(); ++i) { resolver->setUdimString((*udimIdentifiers)[i]); mx::FilePath resolvedPath = MaterialXUtil::findInSubdirectories( searchPath, resolver->resolve(fileName, mx::FILENAME_TYPE_STRING)); mTilePaths.append(resolvedPath.asString().c_str()); mTilePositions.append(udimCoordinates[i][0]); mTilePositions.append(udimCoordinates[i][1]); } mx::Vector2 scaleUV; mx::Vector2 offsetUV; mx::getUdimScaleAndOffset(udimCoordinates, scaleUV, offsetUV); unsigned int udimBakeWidth = 4096; unsigned int udimBakeHeight = 4096; const float ratio = scaleUV[1] / scaleUV[0]; if (ratio > 1.0) { udimBakeHeight = static_cast<unsigned int>(std::truncf(static_cast<float>(udimBakeHeight) * ratio)); } else { udimBakeWidth = static_cast<unsigned int>(std::truncf(static_cast<float>(udimBakeWidth) * ratio)); } static const MColor undefinedColor; MStringArray failedTilePaths; MFloatArray uvScaleOffset; texturePtr.reset(textureManager->acquireTiledTexture(fileName.c_str(), mTilePaths, mTilePositions, undefinedColor, udimBakeWidth, udimBakeHeight, failedTilePaths, uvScaleOffset)); } else { const mx::FilePath imagePath = MaterialXUtil::findInSubdirectories(searchPath, fileName); if (!imagePath.isEmpty()) { texturePtr.reset( textureManager->acquireTexture(imagePath.asString().c_str(), mx::EMPTY_STRING.c_str())); } } MHWRender::MTextureAssignment textureAssignment; textureAssignment.texture = texturePtr.get(); if (texturePtr) { texturePtr->textureDescription(textureDescription); } else { MString message("*Unable to find image file: "); message += fileName.c_str(); message += " in search paths: "; message += searchPath.asString().c_str(); MGlobal::displayError(message); } status = shaderInstance.setParameter(parameterName.c_str(), textureAssignment); if (!status) { MString message("*Unable to bind image file: "); message += fileName.c_str(); MGlobal::displayError(message); } } if (MayaUtil::SamplerUniquePtr samplerState{MHWRender::MStateManager::acquireSamplerState(samplerDescription)}) { const std::string samplerParameterName = mx::OgsXmlGenerator::textureToSamplerName(parameterName); status = shaderInstance.setParameter(samplerParameterName.c_str(), *samplerState); } return status; } void bindEnvironmentLighting(MHWRender::MShaderInstance& shaderInstance, const MStringArray& parameterList, const mx::FileSearchPath& imageSearchPath, const MaterialXNode& node) { MHWRender::MSamplerStateDesc samplerDescription; samplerDescription.filter = MHWRender::MSamplerState::kAnisotropic; samplerDescription.maxAnisotropy = 16; MStatus status; MHWRender::MTextureDescription textureDescription; if (parameterList.indexOf(mx::HW::ENV_IRRADIANCE.c_str()) >= 0) { status = bindFileTexture(shaderInstance, mx::HW::ENV_IRRADIANCE, imageSearchPath, node.getEnvIrradianceFileName().asChar(), samplerDescription, textureDescription, nullptr); } if (parameterList.indexOf(mx::HW::ENV_RADIANCE.c_str()) >= 0) { status = bindFileTexture(shaderInstance, mx::HW::ENV_RADIANCE, imageSearchPath, node.getEnvRadianceFileName().asChar(), samplerDescription, textureDescription, nullptr); if (status == MStatus::kSuccess) { if (parameterList.indexOf(mx::HW::ENV_RADIANCE_MIPS.c_str()) >= 0) { const int mipCount = static_cast<int>(std::log2(std::max(textureDescription.fWidth, textureDescription.fHeight))) + 1; status = shaderInstance.setParameter(mx::HW::ENV_RADIANCE_MIPS.c_str(), mipCount); } if (parameterList.indexOf(mx::HW::ENV_RADIANCE_SAMPLES.c_str()) >= 0) { constexpr int envSamples = 16; status = shaderInstance.setParameter(mx::HW::ENV_RADIANCE_SAMPLES.c_str(), envSamples); } } } if (parameterList.indexOf(mx::HW::ENV_MATRIX.c_str()) >= 0) { constexpr float Y_ROTATION_PI[4][4] { -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; static const MFloatMatrix ENV_MATRIX(Y_ROTATION_PI); status = shaderInstance.setParameter(mx::HW::ENV_MATRIX.c_str(), ENV_MATRIX); } } } template <class BASE> ShadingNodeOverride<BASE>::ShadingNodeOverride(const MObject& obj) : BASE(obj) , _object(obj) { } template <class BASE> ShadingNodeOverride<BASE>::~ShadingNodeOverride() { } template <class BASE> MString ShadingNodeOverride<BASE>::fragmentName() const { MStatus status; MFnDependencyNode depNode(_object, &status); const auto* const node = dynamic_cast<MaterialXNode*>(depNode.userNode()); const OgsFragment* const data = node ? node->getOgsFragment() : nullptr; if (data) { return data->getLightRigName().empty() ? data->getFragmentName().c_str() : data->getLightRigName().c_str(); } return ""; } template <class BASE> bool ShadingNodeOverride<BASE>::valueChangeRequiresFragmentRebuild(const MPlug* plug) const { if ( *plug == MaterialXNode::DOCUMENT_ATTRIBUTE || *plug == MaterialXNode::ELEMENT_ATTRIBUTE || *plug == MaterialXNode::ENV_RADIANCE_ATTRIBUTE || *plug == MaterialXNode::ENV_IRRADIANCE_ATTRIBUTE ) { return true; } return BASE::valueChangeRequiresFragmentRebuild(plug); } template <class BASE> void ShadingNodeOverride<BASE>::updateShader(MHWRender::MShaderInstance& shaderInstance, const MHWRender::MAttributeParameterMappingList& mappings) { MStatus status; MFnDependencyNode depNode(_object, &status); const auto* const node = dynamic_cast<MaterialXNode*>(depNode.userNode()); if (!node) { return; } const OgsFragment* const ogsFragment = node->getOgsFragment(); if (!ogsFragment) { return; } MStringArray parameterList; shaderInstance.parameterList(parameterList); mx::FilePath documentPath(node->getDocumentFilePath().asChar()); documentPath = documentPath.getParentPath(); mx::FileSearchPath imageSearchPath = Plugin::instance().getResourceSearchPath(); mx::FileSearchPath lightSearchPath = Plugin::instance().getLightSearchPath(); imageSearchPath.prepend(documentPath); lightSearchPath.prepend(documentPath); bindEnvironmentLighting(shaderInstance, parameterList, lightSearchPath, *node); mx::DocumentPtr document = ogsFragment->getDocument(); mx::flattenFilenames(document, imageSearchPath); mx::ValuePtr udimSetValue = document->getGeomPropValue("udimset"); const mx::StringVec* udimIdentifiers = nullptr; if (udimSetValue && udimSetValue->isA<mx::StringVec>()) { udimIdentifiers = &(udimSetValue->asA<mx::StringVec>()); } const std::vector<MSamplerState::TextureAddress> addressModes { MSamplerState::TextureAddress::kTexBorder, MSamplerState::TextureAddress::kTexClamp, MSamplerState::TextureAddress::kTexWrap, MSamplerState::TextureAddress::kTexMirror }; const std::vector<MHWRender::MSamplerState::TextureFilter> filterModes { MHWRender::MSamplerState::kMinMagMipPoint, MHWRender::MSamplerState::kMinMagMipLinear, MHWRender::MSamplerState::kAnisotropic }; const mx::StringMap& inputs = ogsFragment->getPathInputMap(); for (const auto& input : inputs) { const std::string& elementPath = input.first; mx::ElementPtr element = document->getDescendant(elementPath); if (!element) { std::string nodePath = mx::parentNamePath(elementPath); mx::ElementPtr uniformParent = document->getDescendant(nodePath); if (uniformParent) { mx::NodePtr uniformNode = uniformParent->asA<mx::Node>(); if (uniformNode) { mx::StringVec pathVec = mx::splitNamePath(elementPath); element = uniformNode->addInputFromNodeDef(pathVec[pathVec.size() - 1]); } } if (!element) { continue; } } mx::ValueElementPtr valueElement = element->asA<mx::ValueElement>(); if (!valueElement) { continue; } const std::string& inputName = input.second; const MHWRender::MAttributeParameterMapping* const mapping = mappings.findByParameterName(inputName.c_str()); const MString resolvedName = mapping ? mapping->resolvedParameterName() : inputName.c_str(); mx::ValuePtr mtxValue = valueElement->getValue(); if (mtxValue) { if (mtxValue->isA<mx::Matrix44>()) { mx::Matrix44 matrix44 = mtxValue->asA<mx::Matrix44>(); MFloatMatrix mayaValue; for (unsigned int i = 0; i < 4; i++) { for (unsigned int j = 0; j < 4; j++) { mayaValue[i][j] = matrix44[i][j]; } } status = shaderInstance.setParameter(resolvedName, mayaValue); } else if (mtxValue->isA<mx::Matrix33>()) { mx::Matrix33 matrix33 = mtxValue->asA<mx::Matrix33>(); MFloatMatrix mayaValue; mayaValue.setToIdentity(); for (unsigned int i = 0; i < 3; i++) { for (unsigned int j = 0; j < 3; j++) { mayaValue[i][j] = matrix33[i][j]; } } std::string matrix4Name = OgsFragment::getMatrix4Name(resolvedName.asChar()); status = shaderInstance.setParameter(matrix4Name.c_str(), mayaValue); } else if (valueElement->getType() == mx::FILENAME_TYPE_STRING) { const std::string textureParameterName(resolvedName.asChar()); const std::string& valueString = valueElement->getValueString(); if (!valueString.empty()) { MHWRender::MTextureDescription textureDescription; mx::ImageSamplingProperties samplingProperties = ogsFragment->getImageSamplingProperties(textureParameterName); MHWRender::MSamplerStateDesc samplerDescription; samplerDescription.borderColor[0] = samplingProperties.defaultColor[0]; samplerDescription.borderColor[1] = samplingProperties.defaultColor[1]; samplerDescription.borderColor[2] = samplingProperties.defaultColor[2]; samplerDescription.borderColor[3] = samplingProperties.defaultColor[3]; samplerDescription.addressV = MSamplerState::TextureAddress::kTe
template class ShadingNodeOverride<MHWRender::MPxShadingNodeOverride>; template class ShadingNodeOverride<MHWRender::MPxSurfaceShadingNodeOverride>; MHWRender::MPxSurfaceShadingNodeOverride* SurfaceOverride::creator(const MObject& obj) { std::cout.rdbuf(std::cerr.rdbuf()); return new SurfaceOverride(obj); } MString SurfaceOverride::transparencyParameter() const { return mx::OgsXmlGenerator::VP_TRANSPARENCY_NAME.c_str(); } MHWRender::MPxShadingNodeOverride* TextureOverride::creator(const MObject& obj) { std::cout.rdbuf(std::cerr.rdbuf()); return new TextureOverride(obj); } }
xWrap; if (samplingProperties.vaddressMode != mx::ImageSamplingProperties::AddressMode::UNSPECIFIED) { samplerDescription.addressV = addressModes[static_cast<int>(samplingProperties.vaddressMode)]; } samplerDescription.addressU = MSamplerState::TextureAddress::kTexWrap; if (samplingProperties.uaddressMode != mx::ImageSamplingProperties::AddressMode::UNSPECIFIED) { samplerDescription.addressU = addressModes[static_cast<int>(samplingProperties.uaddressMode)]; } samplerDescription.filter = MHWRender::MSamplerState::kMinMagMipLinear; samplerDescription.maxAnisotropy = 16; if (samplingProperties.filterType != mx::ImageSamplingProperties::FilterType::UNSPECIFIED) { samplerDescription.filter = filterModes[static_cast<int>(samplingProperties.filterType)]; } status = bindFileTexture(shaderInstance, textureParameterName, imageSearchPath, valueString, samplerDescription, textureDescription, udimIdentifiers); } } } } }
function_block-function_prefixed
[ { "content": "/// @class FileSearchPath\n\n/// A sequence of file paths, which may be queried to find the first instance\n\n/// of a given filename on the file system.\n\nclass MX_FORMAT_API FileSearchPath\n\n{\n\n public:\n\n using Iterator = FilePathVec::iterator;\n\n using ConstIterator = FilePathVec:...
C++
tutorials/Embedding/word2vec.hpp
ChanhyoLee/TextDataset
397571f476a89ad42ef3ed77b82c76fc19ac3e33
#include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <ctime> #include <cstdlib> #include "../../WICWIU_src/Tensor.hpp" #include "../../WICWIU_src/DataLoader.hpp" #define NUMOFWORD 71291 //text8에서 단어의 개수! using namespace std; enum OPTION { TESTING, TRAINING }; template<typename DTYPE> void Make_INPUT(string pImagePath, DTYPE **pImage) { } template<typename DTYPE> void Make_LABEL(int numOfLable, int dimOfLabel, DTYPE **pLabel) { for (int i = 0; i < numOfLabel; i++) { pLabel[i] = new DTYPE[dimOfLabel]; pLabel[i][0] = 1; for(int j=1; j< dimOfLabel; j++) pLabel[i][j] = 0; } } template<typename DTYPE> class TextDataSet : public Dataset<DTYPE>{ private: DTYPE **m_aaInput; DTYPE **m_aaLabel; int m_numOfInput; int m_numOfLabel; int m_window; int m_negative; int m_dimOfInput; int m_dimOfLabel; OPTION m_option; public: TextDataSet(string pTextPath, int window, int negative, OPTION pOPTION) { m_aaInput = NULL; m_aaLabel = NULL; m_numOfInput = 0; m_numOfLabel = 0; m_window = 0; m_negative = 0; m_dimOfInput = 0; m_dimOfLabel = 0; m_option = pOPTION; Alloc(pTextPath, window, negative); } virtual ~TextDataSet() { Delete(); } virtual void Alloc(string pTextPath, int window, int negative); virtual void Delete(); virtual std::vector<Tensor<DTYPE> *>* GetData(int idx); virtual int GetLength(); }; template<typename DTYPE> void TextDataSet<DTYPE>::Alloc(string pTextPath, int window, int negative) { m_window = window; m_negative = negative; m_numOfInput = NUMOFWORD * (m_window - 1); m_numOfLabel = NUMOFWORD * (m_window - 1); m_dimOfInput = m_negative + 2; m_dimOfLabel = m_negative + 1; if (m_option == TRAINING) { m_aaInput = new DTYPE *[m_numOfInput]; Make_INPUT(pTextPath, m_aaInput); m_aaLabel = new DTYPE *[m_numOfLabel]; Make_LABEL(m_numOfLabel, m_dimOfLabel, m_aaLabel); } else if (m_option == TESTING) { m_aaInput = new DTYPE *[m_numOfInput]; Make_INPUT(pImagePath, m_aaInput); m_aaLabel = new DTYPE *[m_numOfInput]; Make_LABEL(m_numOfLabel, m_dimOfLabel, m_aaLabel); } else { printf("invalid option\n"); exit(-1); } } template<typename DTYPE> void TextDataSet<DTYPE>::Delete() { if (m_aaInput) { for (int i = 0; i < m_numOfInput; i++) { if (m_aaInput[i]) { delete[] m_aaInput[i]; m_aaInput[i] = NULL; } } delete m_aaInput; m_aaInput = NULL; } if (m_aaLabel) { for (int i = 0; i < m_numOfLabel; i++) { if (m_aaLabel[i]) { delete[] m_aaLabel[i]; m_aaLabel[i] = NULL; } } delete m_aaLabel; m_aaLabel = NULL; } } template<typename DTYPE> std::vector<Tensor<DTYPE> *> *TextDataSet<DTYPE>::GetData(int idx) { std::vector<Tensor<DTYPE> *> *result = new std::vector<Tensor<DTYPE> *>(0, NULL); Tensor<DTYPE> *image = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfInput); Tensor<DTYPE> *label = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfLabel); for (int i = 0; i < m_dimOfInput; i++) { (*image)[i] = m_aaInput[idx][i]; } (*label)[ (int)m_aaLabel[idx][0] ] = 1.f; result->push_back(image); result->push_back(label); return result; } template<typename DTYPE> int TextDataSet<DTYPE>::GetLength() { return m_numOfInput; }
#include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <ctime> #include <cstdlib> #include "../../WICWIU_src/Tensor.hpp" #include "../../WICWIU_src/DataLoader.hpp" #define NUMOFWORD 71291 //text8에서 단어의 개수! using namespace std; enum OPTION { TESTING, TRAINING }; template<typename DTYPE> void Make_INPUT(string pImagePath, DTYPE **pImage) { } template<typename DTYPE> void Make_LABEL(int numOfLable, int dimOfLabel, DTYPE **pLabel) { for (int i = 0; i < numOfLabel; i++) { pLabel[i] = new DTYPE[dimOfLabel]; pLabel[i][0] = 1; for(int j=1; j< dimOfLabel; j++) pLabel[i][j] = 0; } } template<typename DTYPE> class TextDataSet : public Dataset<DTYPE>{ private: DTYPE **m_aaInput; DTYPE **m_aaLabel; int m_numOfInput; int m_numOfLabel; int m_window; int m_negative; int m_dimOfInput; int m_dimOfLabel; OPTION m_option; public: TextDataSet(string pTextPath, int window, int negative, OPTION pOPTION) { m_aaInput = NULL; m_aaLabel = NULL; m_numOfInput = 0; m_numOfLabel = 0; m_window = 0; m_negative = 0; m_dimOfInput = 0; m_dimOfLabel = 0; m_option = pOPTION; Alloc(pTextPath, window, negative); } virtual ~TextDataSet() { Delete(); } virtual void Alloc(string pTextPath, int window, int negative); virtual void Delete(); virtual std::vector<Tensor<DTYPE> *>* GetData(int idx); virtual int GetLength(); }; template<typename DTYPE> void TextDataSet<DTYPE>::Alloc(string pTextPath, int window, int negative) { m_window = window; m_negative = negative; m_numOfInput = NUMOFWORD * (m_window - 1); m_numOfLabel = NUMOFWORD * (m_window - 1); m_dimOfInput = m_negative + 2; m_dimOfLabel = m_negative + 1; if (m_option == TRAINING) { m_aaInput = new DTYPE *[m_numOfInput]; Make_INPUT(pTextPath, m_aaInput); m_aaLabel = new DTYPE *[m_numOfLabel]; Make_LABEL(m_numOfLabel, m_dimOfLabel, m_aaLabel); } else if (m_option == TESTING) { m_aaInput = new DTYPE *[m_numOfInput]; Make_INPUT(pImagePath, m_aaInput); m_aaLabel = new DTYPE *[m_numOfInput]; Make_LABEL(m_numOfLabel, m_dimOfLabel, m_aaLabel); } else { printf("invalid option\n"); exit(-1); } } template<typename DTYPE> void TextDataSet<DTYPE>::Delete() { if (m_aaInput) { for (int i = 0; i < m_numOfInput; i++) { if (m_aaInput[i]) { delete[] m_aaInput[i]; m_aaInput[i] = NULL; } } delete m_aaInput; m_aaInput = NULL; } if (m_aaLabel) { for (int i = 0; i < m_numOfLabel; i++) { if (m_aaLabel[
template<typename DTYPE> std::vector<Tensor<DTYPE> *> *TextDataSet<DTYPE>::GetData(int idx) { std::vector<Tensor<DTYPE> *> *result = new std::vector<Tensor<DTYPE> *>(0, NULL); Tensor<DTYPE> *image = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfInput); Tensor<DTYPE> *label = Tensor<DTYPE>::Zeros(1, 1, 1, 1, m_dimOfLabel); for (int i = 0; i < m_dimOfInput; i++) { (*image)[i] = m_aaInput[idx][i]; } (*label)[ (int)m_aaLabel[idx][0] ] = 1.f; result->push_back(image); result->push_back(label); return result; } template<typename DTYPE> int TextDataSet<DTYPE>::GetLength() { return m_numOfInput; }
i]) { delete[] m_aaLabel[i]; m_aaLabel[i] = NULL; } } delete m_aaLabel; m_aaLabel = NULL; } }
function_block-function_prefixed
[ { "content": "class NEG : public LossFunction<DTYPE>{\n\nprivate:\n\n DTYPE m_epsilon = 1e-6f; // for backprop\n\n\n\npublic:\n\n\n\n NEG(Operator<DTYPE> *pOperator, Operator<DTYPE> *pLabel, int epsilon = 1e-6f) : LossFunction<DTYPE>(pOperator, pLabel) {\n\n #ifdef __DEBUG__\n\n std::cout <...
C++
include/GafferBindings/SignalBinding.inl
ddesmond/gaffer
4f25df88103b7893df75865ea919fb035f92bac0
#ifndef GAFFERBINDINGS_SIGNALBINDING_INL #define GAFFERBINDINGS_SIGNALBINDING_INL #include "IECorePython/ExceptionAlgo.h" #include "IECorePython/ScopedGILLock.h" #include "IECorePython/ScopedGILRelease.h" #include "boost/signals.hpp" #include "boost/version.hpp" namespace GafferBindings { namespace Detail { template<typename Signal, typename Caller> struct Slot; template<typename Result, typename... Args, typename Combiner, typename Caller> struct Slot<boost::signal<Result( Args... ), Combiner>, Caller> { Slot( boost::python::object slot ) : m_slot( boost::python::borrowed( slot.ptr() ) ) { } ~Slot() { IECorePython::ScopedGILLock gilLock; m_slot.reset(); } using Signal = boost::signal<Result( Args... ), Combiner>; typename Signal::slot_result_type operator()( Args&&... args ) { IECorePython::ScopedGILLock gilLock; try { return Caller()( boost::python::object( m_slot ), std::forward<Args>( args )... ); } catch( const boost::python::error_already_set &e ) { IECorePython::ExceptionAlgo::translatePythonException(); } } boost::python::handle<PyObject> m_slot; }; struct Trackable : public boost::signals::trackable { }; template<typename Visitor, typename Signal, typename Caller> void visit_each( Visitor &visitor, const Slot<Signal, Caller> &slot, int ) { boost::python::object gaffer = boost::python::import( "Gaffer" ); boost::python::object weakMethod = gaffer.attr( "WeakMethod" ); if( PyObject_IsInstance( slot.m_slot.get(), weakMethod.ptr() ) ) { boost::python::object self = boost::python::object( slot.m_slot ).attr( "instance" )(); boost::python::extract<Trackable &> e( self ); if( e.check() ) { boost::visit_each( visitor, e(), 0 ); } } } GAFFERBINDINGS_API boost::python::object pythonConnection( const boost::signals::connection &connection, bool scoped ); template<typename Signal, typename SlotCaller> boost::python::object connect( Signal &s, boost::python::object &slot, bool scoped ) { return pythonConnection( s.connect( Slot<Signal, SlotCaller>( slot ) ), scoped ); } template<typename Signal, typename SlotCaller> boost::python::object connectInGroup( Signal &s, int group, boost::python::object &slot, bool scoped ) { return pythonConnection( s.connect( group, Slot<Signal, SlotCaller>( slot ) ), scoped ); } } template<typename Signal> struct DefaultSignalCaller; template<typename Result, typename... Args, typename Combiner> struct DefaultSignalCaller<boost::signal<Result( Args... ), Combiner>> { using Signal = boost::signal<Result( Args... ), Combiner>; static Result call( Signal &s, Args... args ) { IECorePython::ScopedGILRelease gilRelease; return s( args... ); } }; template<typename Signal> struct DefaultSlotCaller; template<typename Result, typename... Args, typename Combiner> struct DefaultSlotCaller<boost::signal<Result( Args... ), Combiner>> { using Signal = boost::signal<Result ( Args... )>; typename Signal::slot_result_type operator()( boost::python::object slot, Args&&... args ) { return boost::python::extract<typename Signal::slot_result_type>( slot( std::forward<Args>( args )... ) )(); } }; template<typename Signal, typename SignalCaller, typename SlotCaller> SignalClass<Signal, SignalCaller, SlotCaller>::SignalClass( const char *className, const char *docString ) : boost::python::class_<Signal, boost::noncopyable>( className, docString ) { this->def( "connect", &Detail::connect<Signal, SlotCaller>, ( boost::python::arg( "slot" ), boost::python::arg( "scoped" ) = true ) ); this->def( "connect", &Detail::connectInGroup<Signal, SlotCaller>, ( boost::python::arg( "group" ), boost::python::arg( "slot" ), boost::python::arg( "scoped" ) = true ) ); this->def( "num_slots", &Signal::num_slots ); this->def( "empty", &Signal::empty ); this->def( "__call__", &SignalCaller::call ); } } #endif
#ifndef GAFFERBINDINGS_SIGNALBINDING_INL #define GAFFERBINDINGS_SIGNALBINDING_INL #include "IECorePython/ExceptionAlgo.h" #include "IECorePython/ScopedGILLock.h" #include "IECorePython/ScopedGILRelease.h" #include "boost/signals.hpp" #include "boost/version.hpp" namespace GafferBindings { namespace Detail { template<typename Signal, typename Caller> struct Slot; template<typename Result, typename... Args, typename Combiner, typename Caller> struct Slot<boost::signal<Result( Args... ), Combiner>, Caller> { Slot( boost::python::object slot ) : m_slot( boost::python::borrowed( slot.ptr() ) ) { } ~Slot() { IECorePython::ScopedGILLock gilLock; m_slot.reset(); } using Signal = boost::signal<Result( Args... ), Combiner>; typename Signal::slot_result_type operator()( Args&&... args ) { IECorePython::ScopedGILLock gilLock; try { return Caller()( boost::python::object( m_slot ), std::forward<Args>( args )... ); } catch( const boost::python::error_already_set &e ) { IECorePython::ExceptionAlgo::translatePythonException(); } } boost::python::handle<PyObject> m_slot; }; struct Trackable : public boost::signals::trackable { }; template<typename Visitor, typename Signal, typename Caller> void visit_each( Visitor &visitor, const Slot<Signal, Caller> &slot, int ) { boost::python::object gaffer = boost::python::import( "Gaffer" ); boost::python::object weakMethod = gaffer.attr( "WeakMethod" ); if( PyObject_IsInstance( slot.m_slot.ge
GAFFERBINDINGS_API boost::python::object pythonConnection( const boost::signals::connection &connection, bool scoped ); template<typename Signal, typename SlotCaller> boost::python::object connect( Signal &s, boost::python::object &slot, bool scoped ) { return pythonConnection( s.connect( Slot<Signal, SlotCaller>( slot ) ), scoped ); } template<typename Signal, typename SlotCaller> boost::python::object connectInGroup( Signal &s, int group, boost::python::object &slot, bool scoped ) { return pythonConnection( s.connect( group, Slot<Signal, SlotCaller>( slot ) ), scoped ); } } template<typename Signal> struct DefaultSignalCaller; template<typename Result, typename... Args, typename Combiner> struct DefaultSignalCaller<boost::signal<Result( Args... ), Combiner>> { using Signal = boost::signal<Result( Args... ), Combiner>; static Result call( Signal &s, Args... args ) { IECorePython::ScopedGILRelease gilRelease; return s( args... ); } }; template<typename Signal> struct DefaultSlotCaller; template<typename Result, typename... Args, typename Combiner> struct DefaultSlotCaller<boost::signal<Result( Args... ), Combiner>> { using Signal = boost::signal<Result ( Args... )>; typename Signal::slot_result_type operator()( boost::python::object slot, Args&&... args ) { return boost::python::extract<typename Signal::slot_result_type>( slot( std::forward<Args>( args )... ) )(); } }; template<typename Signal, typename SignalCaller, typename SlotCaller> SignalClass<Signal, SignalCaller, SlotCaller>::SignalClass( const char *className, const char *docString ) : boost::python::class_<Signal, boost::noncopyable>( className, docString ) { this->def( "connect", &Detail::connect<Signal, SlotCaller>, ( boost::python::arg( "slot" ), boost::python::arg( "scoped" ) = true ) ); this->def( "connect", &Detail::connectInGroup<Signal, SlotCaller>, ( boost::python::arg( "group" ), boost::python::arg( "slot" ), boost::python::arg( "scoped" ) = true ) ); this->def( "num_slots", &Signal::num_slots ); this->def( "empty", &Signal::empty ); this->def( "__call__", &SignalCaller::call ); } } #endif
t(), weakMethod.ptr() ) ) { boost::python::object self = boost::python::object( slot.m_slot ).attr( "instance" )(); boost::python::extract<Trackable &> e( self ); if( e.check() ) { boost::visit_each( visitor, e(), 0 ); } } }
function_block-function_prefixed
[]
C++
Sandbox2D/src/2dapp.cpp
dovker/Rosewood
5131a061632732222ce68e5da5a257b8bda36ea5
#include "Rosewood.h" #include "Rosewood/Core/EntryPoint.h" #include "imgui.h" #include "Sofa.h" #include "2DCameraController.h" const std::string Rosewood::FileSystem::ProjectRoot = "../../../Sandbox2D/"; class ExampleLayer : public Rosewood::Layer { public: unsigned int scrWidth = Rosewood::Application::Get().GetWindow().GetWidth(); unsigned int scrHeight = Rosewood::Application::Get().GetWindow().GetHeight(); float lastX = scrWidth / 2.0f; float lastY = scrHeight / 2.0f; Rosewood::Ref<Rosewood::Texture> texture; Rosewood::Ref<Rosewood::Texture> fontTexture; Sofa sofa; Rosewood::Ref<Rosewood::SpriteFont> font; Rosewood::Ref<Rosewood::VertexArray> m_VertexArray; Rosewood::Ref<Rosewood::Framebuffer> m_Framebuffer; Rosewood::Ref<Rosewood::Sound> sound; Rosewood::Ref<Rosewood::RenderMesh> mesh; Rosewood::Ref<Rosewood::RenderMesh> flatMesh; Rosewood::Ref<Rosewood::RenderMesh> planeMesh; Rosewood::Ref<Rosewood::DecalLight> decal; CameraControl camera = CameraControl(glm::vec2( (float)scrWidth, (float)scrHeight)); bool open = true; std::string text = "Help my pp is very hard because this works! :))) XDD ; \nHello love! This should be in a new line! \nHippopotamus!12 Hippopotamus! Hippopotamus!"; float scroll = 0.0f; float intensity = 1.0f; float intensityDecal = 1.0f; float gamma = 2.2f; float exposure = 1.0f; glm::vec3 color = glm::vec3(1.0f); glm::vec3 colorDecal = glm::vec3(1.0f); glm::vec3 bcs = glm::vec3(0.0f, 1.0f, 1.0f); glm::vec2 bwpoint = glm::vec2(0.0f, 1.0f); float linear = 0.014; float quadratic = 0.0007; glm::vec3 direction = {0.0f, 0.0f, -1.0f}; glm::vec3 ambient = glm::vec3(0.1f); float mouseX = 0.0f; float mouseY = 0.0f; ExampleLayer() : Layer("Example") { Rosewood::Ref<Rosewood::Texture> albedo = Rosewood::AssetManager::Load<Rosewood::Texture>("TestBox.png", "Deferred_Albedo"); Rosewood::Ref<Rosewood::Texture> normal = Rosewood::AssetManager::Load<Rosewood::Texture>("Deferred_Normal.png", "Deferred_Normal"); Rosewood::Ref<Rosewood::Texture> spec = Rosewood::AssetManager::Load<Rosewood::Texture>("Deferred_Specular.png", "Deferred_Specular"); Rosewood::Ref<Rosewood::Texture> lightTex = Rosewood::AssetManager::Load<Rosewood::Texture>("awesomeface.png", "DecalLight"); sofa.Load(); texture = lightTex; Rosewood::AssetManager::Load<Rosewood::Sound>("sound.mp3", "Sound"); Rosewood::AssetManager::Load<Rosewood::Texture>("Chroma.png", "Sprite_Font"); mesh = Rosewood::RenderMesh::CreateFoldedQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}, 0.5f); flatMesh = Rosewood::RenderMesh::CreateFlatQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}); planeMesh= Rosewood::RenderMesh::CreatePerpendicularQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}); sound = Rosewood::AssetManager::Get<Rosewood::Sound>("Sound"); fontTexture = Rosewood::AssetManager::Get<Rosewood::Texture>("Sprite_Font"); decal = Rosewood::DecalLight::Create(texture, {mouseX, mouseY, 0.0f}, direction, color * intensityDecal, {texture->GetWidth(), texture->GetHeight()}); font = Rosewood::SpriteFont::Create(fontTexture, "!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ", 9, 9); Rosewood::DeferredRenderer::Init(); } void OnUpdate(Rosewood::Timestep timestep) override { camera.ProcessKeyboard(timestep.GetSeconds()); { Rosewood::GraphicsCommand::SetClearColor(glm::vec4(0.1f, 0.12f, 0.1f, 1.0f)); Rosewood::GraphicsCommand::Clear(); } Rosewood::DeferredRenderer::SetAmbient(ambient); Rosewood::DeferredRenderer::SetGamma(gamma); Rosewood::DeferredRenderer::SetExposure(exposure); Rosewood::DeferredRenderer::SetBCS(bcs); Rosewood::DeferredRenderer::SetBWPoint(bwpoint); Rosewood::DeferredRenderer::Begin(camera.GetCamera()); sofa.Draw(glm::vec3(0.0f, 0.0f, 0.0f)); mouseX = Rosewood::Input::GetMouseX() + camera.GetCamera().GetPosition().x; mouseY = Rosewood::Input::GetMouseY() + camera.GetCamera().GetPosition().y; decal->SetPosRot(glm::vec3(mouseX, mouseY, scroll), direction); decal->color = colorDecal * intensityDecal; Rosewood::DeferredRenderer::SubmitDecalLight(decal); Rosewood::DeferredRenderer::BeginLights(); Rosewood::DeferredRenderer::DrawPointLight(glm::vec3(mouseX, mouseY, scroll), color, intensity, 1.0, linear, quadratic); Rosewood::DeferredRenderer::DrawDecals(); Rosewood::DeferredRenderer::End(); } float col[3] {1.0f, 1.0f, 1.0f}; float colDec[3] {1.0f, 1.0f, 1.0f}; float ambCol[3] {0.1f, 0.1f, 0.1f}; float dir[3] {0.0f, 0.0f, -1.0f}; void OnImGuiRender() override { auto stats = Rosewood::BatchRenderer::GetStats(); ImGui::Begin("This is 2D Spritebatch System", &open, 0); ImGui::Text("Camera Pos: %f, %f, %f", camera.GetCamera().GetPosition().x, camera.GetCamera().GetPosition().y, camera.GetCamera().GetPosition().z); ImGui::Text("Batch stats: %i, %i", stats.DrawCount, stats.QuadCount); ImGui::Text("Scroll: %f", scroll); ImGui::Separator(); ImGui::SliderFloat3("Direction", dir, -1.0f, 1.0f); direction = glm::normalize(glm::vec3(dir[0], dir[1], dir[2])); ImGui::SliderFloat("Exposure", &exposure, 0.0f, 10.0f); ImGui::SliderFloat("Gamma", &gamma, 0.0f, 10.0f); ImGui::SliderFloat("Brightness", &bcs.x, -1.0f, 1.0f); ImGui::SliderFloat("Contrast", &bcs.y, 0.0f, 10.0f); ImGui::SliderFloat("Saturation", &bcs.z, 0.0f, 10.0f); ImGui::SliderFloat("Black Point", &bwpoint.x, 0.0f, 1.0f); ImGui::SliderFloat("White Point", &bwpoint.y, -1.0f, 1.0f); if(ImGui::Button("RECOMPILE RENDERER SHADERS")) Rosewood::DeferredRenderer::ReloadShaders(); ImGui::Separator(); ImGui::ColorPicker3("Decal Color", colDec); colorDecal = {colDec[0], colDec[1], colDec [2]}; ImGui::InputFloat("Decal Intensity", &intensityDecal); ImGui::ColorPicker3("Light Color", col); color = {col[0], col[1], col [2]}; ImGui::ColorPicker3("Ambient Color", ambCol); ambient = {ambCol[0], ambCol[1], ambCol[2]}; ImGui::InputFloat("Linear", &linear, 0.1f, 0.0f, "%.19f"); ImGui::InputFloat("Quadratic", &quadratic, 0.1f, 0.0f, "%.19f"); ImGui::InputFloat("Intensity", &intensity); ImGui::Separator(); int w = scrWidth; int h = scrHeight; ImGui::InputInt("px", &w); ImGui::InputInt("px", &h); ImGui::Image((void*)Rosewood::DeferredRenderer::GetAlbedoID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetPosID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetNormalID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetLightID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetDepthID(), {576, 324}); ImGui::Image((void*)decal->depth->GetDepthAttachmentRendererID(), {576, 324}); ImGui::End(); } void OnEvent(Rosewood::Event& event) override { Rosewood::EventDispatcher dispatcher(event); dispatcher.Dispatch<Rosewood::MouseButtonPressedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseButtonPressedEvent)); dispatcher.Dispatch<Rosewood::MouseButtonReleasedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseButtonReleasedEvent)); dispatcher.Dispatch<Rosewood::MouseMovedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseMovedEvent)); dispatcher.Dispatch<Rosewood::MouseScrolledEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseScrolledEvent)); dispatcher.Dispatch<Rosewood::KeyPressedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnKeyPressedEvent)); dispatcher.Dispatch<Rosewood::KeyReleasedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnKeyReleasedEvent)); dispatcher.Dispatch<Rosewood::WindowResizeEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnWindowResizeEvent)); } bool OnMouseButtonPressedEvent(Rosewood::MouseButtonPressedEvent& e) { if(e.GetMouseButton() == MOUSE_BUTTON_LEFT) { float mouseX = Rosewood::Input::GetMouseX() + camera.GetCamera().GetPosition().x; float mouseY = Rosewood::Input::GetMouseY() + camera.GetCamera().GetPosition().y; } return false; } bool OnMouseButtonReleasedEvent(Rosewood::MouseButtonReleasedEvent& e) { return false; } bool firstMouse = true; bool OnMouseMovedEvent(Rosewood::MouseMovedEvent& e) { return false; } bool OnMouseScrolledEvent(Rosewood::MouseScrolledEvent& e) { scroll += e.GetYOffset(); return false; } bool OnKeyPressedEvent(Rosewood::KeyPressedEvent& e) { int key = e.GetKeyCode(); if (key == KEY_R) Rosewood::Application::Get().GetWindow().LockCursor(); else if (key == KEY_T) Rosewood::Application::Get().GetWindow().UnlockCursor(); else if (key == KEY_F) sound->Play(); return false; } bool OnKeyReleasedEvent(Rosewood::KeyReleasedEvent& e) { return false; } bool OnWindowResizeEvent(Rosewood::WindowResizeEvent& e) { scrWidth = e.GetWidth(); scrHeight = e.GetHeight(); camera.ProcessScreenResize(glm::vec2(scrWidth, scrHeight)); Rosewood::GraphicsCommand::SetViewport(0, 0, scrWidth, scrHeight); return false; } }; class Sandbox : public Rosewood::Application { public: Sandbox() { PushLayer(new ExampleLayer()); } ~Sandbox() { Rosewood::BatchRenderer::Shutdown(); } }; Rosewood::Application* Rosewood::CreateApplication() { return new Sandbox(); }
#include "Rosewood.h" #include "Rosewood/Core/EntryPoint.h" #include "imgui.h" #include "Sofa.h" #include "2DCameraController.h" const std::string Rosewood::FileSystem::ProjectRoot = "../../../Sandbox2D/"; class ExampleLayer : public Rosewood::Layer { public: unsigned int scrWidth = Rosewood::Application::Get().GetWindow().GetWidth(); unsigned int scrHeight = Rosewood::Application::Get().GetWindow().GetHeight(); float lastX = scrWidth / 2.0f; float lastY = scrHeight / 2.0f; Rosewood::Ref<Rosewood::Texture> texture; Rosewood::Ref<Rosewood::Texture> fontTexture; Sofa sofa; Rosewood::Ref<Rosewood::SpriteFont> font; Rosewood::Ref<Rosewood::VertexArray> m_VertexArray; Rosewood::Ref<Rosewood::Framebuffer> m_Framebuffer; Rosewood::Ref<Rosewood::Sound> sound; Rosewood::Ref<Rosewood::RenderMesh> mesh; Rosewood::Ref<Rosewood::RenderMesh> flatMesh; Rosewood::Ref<Rosewood::RenderMesh> planeMesh; Rosewood::Ref<Rosewood::DecalLight> decal; CameraControl camera = CameraControl(glm::vec2( (float)scrWidth, (float)scrHeight)); bool open = true; std::string text = "Help my pp is very hard because this works! :))) XDD ; \nHello love! This should be in a new line! \nHippopotamus!12 Hippopotamus! Hippopotamus!"; float scroll = 0.0f; float intensity = 1.0f; float intensityDecal = 1.0f; float gamma = 2.2f; float exposure = 1.0f; glm::vec3 color = glm::vec3(1.0f); glm::vec3 colorDecal = glm::vec3(1.0f); glm::vec3 bcs = glm::vec3(0.0f, 1.0f, 1.0f); glm::vec2 bwpoint = glm::vec2(0.0f, 1.0f); float linear = 0.014; float quadratic = 0.0007; glm::vec3 direction = {0.0f, 0.0f, -1.0f}; glm::vec3 ambient = glm::vec3(0.1f); float mouseX = 0.0f; float mouseY = 0.0f; ExampleLayer() : Layer("Example") { Rosewood::Ref<Rosewood::Texture> albedo = Rosewood::AssetManager::Load<Rosewood::Texture>("TestBox.png", "Deferred_Albedo"); Rosewood::Ref<Rosewood::Texture> normal = Rosewood::AssetManager::Load<Rosewood::Texture>("Deferred_Normal.png", "Deferred_Normal"); Rosewood::Ref<Rosewood::Texture> spec = Rosewood::AssetManager::Load<Rosewood::Texture>("Deferred_Specular.png", "Deferred_Specular"); Rosewood::Ref<Rosewood::Texture> lightTex = Rosewood::AssetManager::Load<Rosewood::Texture>("awesomeface.png", "DecalLight"); sofa.Load(); texture = lightTex; Rosewood::AssetManager::Load<Rosewood::Sound>("sound.mp3", "Sound"); Rosewood::AssetManager::Load<Rosewood::Texture>("Chroma.png", "Sprite_Font"); mesh = Rosewood::RenderMesh::CreateFoldedQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}, 0.5f); flatMesh = Rosewood::RenderMesh::CreateFlatQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}); planeMesh= Rosewood::RenderMesh::CreatePerpendicularQuad(std::vector<Rosewood::Ref<Rosewood::Texture>>{albedo, normal, spec}); sound = Rosewood::AssetManager::Get<Rosewood::Sound>("Sound"); fontTexture = Rosewood::AssetManager::Get<Rosewood::Texture>("Sprite_Font"); decal = Rosewood::DecalLight::Create(texture, {mouseX, mouseY, 0.0f}, direction, color * intensityDecal, {texture->GetWidth(), texture->GetHeight()}); font = Rosewood::SpriteFont::Create(fontTexture, "!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ", 9, 9); Rosewood::DeferredRenderer::Init(); } void OnUpdate(Rosewood::Timestep timestep) override { camera.ProcessKeyboard(timestep.GetSeconds()); { Rosewood::GraphicsCommand::SetClearColor(glm::vec4(0.1f, 0.12f, 0.1f, 1.0f)); Rosewood::GraphicsCommand::Clear(); } Rosewood::DeferredRenderer::SetAmbient(ambient); Rosewood::DeferredRenderer::SetGamma(gamma); Rosewood::DeferredRenderer::SetExposure(exposure); Rosewood::DeferredRenderer::SetBCS(bcs); Rosewood::DeferredRenderer::SetBWPoint(bwpoint); Rosewood::DeferredRenderer::Begin(camera.GetCamera()); sofa.Draw(glm::vec3(0.0f, 0.0f, 0.0f)); mouseX = Rosewood::Input::GetMouseX() + camera.GetCamera().GetPosition().x; mouseY = Rosewood::Input::GetMouseY() + camera.GetCamera().GetPosition().y; decal->SetPosRot(glm::vec3(mouseX, mouseY, scroll), direction); decal->color = colorDecal * intensityDecal; Rosewood::DeferredRenderer::SubmitDecalLight(decal); Rosewood::DeferredRenderer::BeginLights(); Rosewood::DeferredRenderer::DrawPointLight(glm::vec3(mouseX, mouseY, scroll), color, intensity, 1.0, linear, quadratic); Rosewood::DeferredRenderer::DrawDecals(); Rosewood::DeferredRenderer::End(); } float col[3] {1.0f, 1.0f, 1.0f}; float colDec[3] {1.0f, 1.0f, 1.0f}; float ambCol[3] {0.1f, 0.1f, 0.1f}; float dir[3] {0.0f, 0.0f, -1.0f}; void OnImGuiRender() override { auto stats = Rosewood::BatchRenderer::GetStats(); ImGui::Begin("This is 2D Spritebatch System", &open, 0); ImGui::Text("Camera Pos: %f, %f, %f", camera.GetCamera().GetPosition().x, camera.GetCamera().GetPosition().y, camera.GetCamera().GetPosition().z); ImGui::Text("Batch stats: %i, %i", stats.DrawCount, stats.QuadCount); ImGui::Text("Scroll: %f", scroll); ImGui::Separator(); ImGui::SliderFloat3("Direction", dir, -1.0f, 1.0f); direction = glm::normalize(glm::vec3(dir[0], dir[1], dir[2])); ImGui::SliderFloat("Exposure", &exposure, 0.0f, 10.0f); ImGui::SliderFloat("Gamma", &gamma, 0.0f, 10.0f); ImGui::SliderFloat("Brightness", &bcs.x, -1.0f, 1.0f); ImGui::SliderFloat("Contrast", &bcs.y, 0.0f, 10.0f); ImGui::SliderFloat("Saturation", &bcs.z, 0.0f, 10.0f); ImGui::SliderFloat("Black Point", &bwpoint.x, 0.0f, 1.0f); ImGui::SliderFloat("White Point", &bwpoint.y, -1.0f, 1.0f); if(ImGui::Button("RECOMPILE RENDERER SHADERS")) Rosewood::DeferredRenderer::ReloadShaders(); ImGui::Separator(); ImGui::ColorPicker3("Decal Color", colDec); colorDecal = {colDec[0], colDec[1], colDec [2]}; ImGui::InputFloat("Decal Intensity", &intensityDecal); ImGui::ColorPicker3("Light Color", col); color = {col[0], col[1], col [2]}; ImGui::ColorPicker3("Ambient Color", ambCol); ambient = {ambCol[0], ambCol[1], ambCol[2]}; ImGui::InputFloat("Linear", &linear, 0.1f, 0.0f, "%.19f"); ImGui::InputFloat("Quadratic", &quadratic, 0.1f, 0.0f, "%.19f"); ImGui::InputFloat("Intensity", &intensity); ImGui::Separator(); int w = scrWidth; int h = scrHeight; ImGui::InputInt("px", &w); ImGui::InputInt("px", &h); ImGui::Image((void*)Rosewood::DeferredRenderer::GetAlbedoID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetPosID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetNormalID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetLightID(), {576, 324}); ImGui::Image((void*)Rosewood::DeferredRenderer::GetDepthID(), {576, 324}); ImGui::Image((void*)decal->depth->GetDepthAttachmentRendererID(), {576, 324}); ImGui::End(); } void OnEvent(Rosewood::Event& event) override { Rosewood::EventDispatcher dispatcher(event); dispatcher.Dispatch<Rosewood::MouseButtonPressedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseButtonPressedEvent)); dispatcher.Dispatch<Rosewood::MouseButtonReleasedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseButtonReleasedEvent)); dispatcher.Dispatch<Rosewood::MouseMovedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseMovedEvent)); dispatcher.Dispatch<Rosewood::MouseScrolledEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnMouseScrolledEvent)); dispatcher.Dispatch<Rosewood::KeyPressedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnKeyPressedEvent)); dispatcher.Dispatch<Rosewood::KeyReleasedEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnKeyReleasedEvent)); dispatcher.Dispatch<Rosewood::WindowResizeEvent>(RW_BIND_EVENT_FN(ExampleLayer::OnWindowResizeEvent)); } bool OnMouseButtonPressedEvent(Rosewood::MouseButtonPressedEvent& e) { if(e.GetMouseButton() == MOUSE_BUTTON_LEFT) { float mouseX = Rosewood::Input::GetMouseX() + camera.GetCamera().GetPosition().x; float mouseY = Rosewood::Input::GetMouseY() + camera.GetCamera().GetPosition().y; } return false; } bool OnMouseButtonReleasedEvent(Rosewood::MouseButtonReleasedEvent& e) { return false; } bool firstMouse = true; bool OnMouseMovedEvent(Rosewood::MouseMovedEvent& e) { return false; } bool OnMouseScrolledEvent(Rosewood::MouseScrolledEvent& e) { scroll += e.GetYOffset(); return false; } bool OnKeyPressedEvent(Rosewood::KeyPressedEvent& e) { int key = e.GetKeyCode(); if (key == KEY_R) Rosewood::Applicatio
bool OnKeyReleasedEvent(Rosewood::KeyReleasedEvent& e) { return false; } bool OnWindowResizeEvent(Rosewood::WindowResizeEvent& e) { scrWidth = e.GetWidth(); scrHeight = e.GetHeight(); camera.ProcessScreenResize(glm::vec2(scrWidth, scrHeight)); Rosewood::GraphicsCommand::SetViewport(0, 0, scrWidth, scrHeight); return false; } }; class Sandbox : public Rosewood::Application { public: Sandbox() { PushLayer(new ExampleLayer()); } ~Sandbox() { Rosewood::BatchRenderer::Shutdown(); } }; Rosewood::Application* Rosewood::CreateApplication() { return new Sandbox(); }
n::Get().GetWindow().LockCursor(); else if (key == KEY_T) Rosewood::Application::Get().GetWindow().UnlockCursor(); else if (key == KEY_F) sound->Play(); return false; }
function_block-function_prefixed
[ { "content": "\tclass KeyEvent : public Event\n\n\t{\n\n\tpublic:\n\n\t\tinline int GetKeyCode() const { return m_KeyCode; }\n\n\n\n\t\tEVENT_CLASS_CATEGORY(EventCategoryKeyboard | EventCategoryInput)\n\n\tprotected:\n\n\t\tKeyEvent(int keycode)\n\n\t\t\t: m_KeyCode(keycode) {}\n\n\n\n\t\tint m_KeyCode;\n\n\t};...
C++
eip_device/src/eip_device_node.cpp
wpmccormick/eip_device
808628a7ede642eead1ed9b81db34c0c73ff8b5c
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/capability.h> #include <sys/capability.h> extern "C" { #include "trace.h" #include "opener_api.h" #include "cipcommon.h" #include "trace.h" #include "POSIX/networkconfig.h" #include "doublylinkedlist.h" #include "cipconnectionobject.h" #include "appcontype.h" #include "cipidentity.h" #include "generic_networkhandler.h" } #include <ros/ros.h> #include "eip_device.h" #define DEVICE_SERIAL_NUM 123456789 using namespace std; void LeaveStack(int signal); int g_end_stack = 0; EipDevice eipDevice; int main(int argc, char **argv) { cap_t capabilities; cap_value_t capabilies_list[1]; ros::init(argc, argv, "eip_device"); ros::NodeHandle nh("~"); ROS_INFO("Starting eip_device ..."); ros::Time::init(); double freq; nh.param<double>("frequency", freq, 1); ros::Rate throttle(freq); string device; nh.param<std::string>("device", device, "eth0"); ROS_INFO_STREAM("Using Ethernet device: " << device); ROS_INFO("Getting Ethernet port capabilities ..."); capabilities = cap_get_proc(); if (NULL == capabilities) { ROS_ERROR("Could not get capabilities"); exit(0); } capabilies_list[0] = CAP_NET_RAW; if (-1 == cap_set_flag(capabilities, CAP_EFFECTIVE, 1, capabilies_list, CAP_SET) ) { cap_free(capabilities); ROS_ERROR("Could not set CAP_NET_RAW capability"); exit(0); } if (-1 == cap_set_proc(capabilities) ) { cap_free(capabilities); ROS_ERROR("Could not push CAP_NET_RAW capability to process"); exit(0); } if (-1 == cap_free(capabilities) ) { ROS_ERROR("Could not free capabilites value"); exit(0); } DoublyLinkedListInitialize(&connection_list, CipConnectionObjectListArrayAllocator, CipConnectionObjectListArrayFree); if (kEipStatusError == ConfigureNetworkInterface(device.c_str()) ) { ROS_ERROR("Network interface %s not found.\n", device.c_str()); exit(0); } ConfigureDomainName(); ConfigureHostName(); ConfigureMacAddress(device.c_str()); SetDeviceSerialNumber(DEVICE_SERIAL_NUM); EipUint16 unique_connection_id = rand(); CipStackInit(unique_connection_id); if (kEipStatusOk == NetworkHandlerInitialize() ) { g_end_stack = 0; } else { ROS_ERROR("Error initializing NetworkHandler! Exiting eip_device!"); exit(0); } ros::Publisher eip_data_pub = nh.advertise<eip_device::EipDataAsmOut>("eip_data_fmplc", 1); ros::Publisher eip_config_pub = nh.advertise<eip_device::EipDataAsmCfg>("eip_data_config", 1); ros::Publisher eip_status_pub = nh.advertise<eip_device::EipDeviceStatus>("eip_status", 100); ros::Subscriber eip_unsol_data_sub = nh.subscribe("eip_data_toplc_u", 1, &EipDevice::LoadAsmIn_Callback, &eipDevice); ros::Subscriber eip_sol_data_sub = nh.subscribe("eip_data_toplc_s", 1, &EipDevice::LoadAsmIn_Callback, &eipDevice); ROS_INFO("Starting Process Loop"); int EipStatus = kEipStatusOk; while(ros::ok() && (1 != g_end_stack) && (EipStatus == kEipStatusOk))2 { EipStatus = NetworkHandlerProcessOnce(); if (EipStatus != kEipStatusOk) { ROS_ERROR_STREAM("Error in NetworkHandler loop! Exiting eip_device! -- " << EipStatus ); break; } eipDevice.data_asm_out.raw_plc_data.assign(g_assembly_data096, g_assembly_data096 + OUTPUT_ASSEMBLY_BUFFER_SIZE); eipDevice.data_asm_cfg.raw_plc_data.assign(g_assembly_data097, g_assembly_data097 + CONFIG_ASSEMBLY_BUFFER_SIZE); eip_data_pub.publish(eipDevice.data_asm_out); eip_config_pub.publish(eipDevice.data_asm_cfg); eip_status_pub.publish(eipDevice.device_status); ros::spinOnce(); throttle.sleep(); } ROS_INFO("Finish network handler"); NetworkHandlerFinish(); ROS_INFO("Shutdown CIP Stack"); ShutdownCipStack(); return g_end_stack; } void LeaveStack(int signal) { (void) signal; OPENER_TRACE_STATE("got signal HUP\n"); ROS_INFO("HUP Signal!"); g_end_stack = 1; }
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/capability.h> #include <sys/capability.h> extern "C" { #include "trace.h" #include "opener_api.h" #include "cipcommon.h" #include "trace.h" #include "POSIX/networkconfig.h" #include "doublylinkedlist.h" #include "cipconnectionobject.h" #include "appcontype.h" #include "cipidentity.h" #include "generic_networkhandler.h" } #include <ros/ros.h> #include "eip_device.h" #define DEVICE_SERIAL_NUM 123456789 using namespace std; void LeaveStack(int signal); int g_end_stack = 0; EipDevice eipDevice; int main(int argc, char **argv) { cap_t capabilities; cap_value_t capabilies_list[1]; ros::init(argc, argv, "eip_device"); ros::NodeHandle nh("~"); ROS_INFO("Starting eip_device ..."); ros::Time::init(); double freq; nh.param<double>("frequency", freq, 1); ros::Rate throttle(freq); string device; nh.param<std::string>("device", device, "eth0"); ROS_INFO_STREAM("Using Ethernet device: " << device); ROS_INFO("Getting Ethernet port capabilities ..."); capabilities = cap_get_proc(); if (NULL == capabilities) { ROS_ERROR("Could not get capabilities"); exit(0); } capabilies_list[0] = CAP_NET_RAW;
if (-1 == cap_set_proc(capabilities) ) { cap_free(capabilities); ROS_ERROR("Could not push CAP_NET_RAW capability to process"); exit(0); } if (-1 == cap_free(capabilities) ) { ROS_ERROR("Could not free capabilites value"); exit(0); } DoublyLinkedListInitialize(&connection_list, CipConnectionObjectListArrayAllocator, CipConnectionObjectListArrayFree); if (kEipStatusError == ConfigureNetworkInterface(device.c_str()) ) { ROS_ERROR("Network interface %s not found.\n", device.c_str()); exit(0); } ConfigureDomainName(); ConfigureHostName(); ConfigureMacAddress(device.c_str()); SetDeviceSerialNumber(DEVICE_SERIAL_NUM); EipUint16 unique_connection_id = rand(); CipStackInit(unique_connection_id); if (kEipStatusOk == NetworkHandlerInitialize() ) { g_end_stack = 0; } else { ROS_ERROR("Error initializing NetworkHandler! Exiting eip_device!"); exit(0); } ros::Publisher eip_data_pub = nh.advertise<eip_device::EipDataAsmOut>("eip_data_fmplc", 1); ros::Publisher eip_config_pub = nh.advertise<eip_device::EipDataAsmCfg>("eip_data_config", 1); ros::Publisher eip_status_pub = nh.advertise<eip_device::EipDeviceStatus>("eip_status", 100); ros::Subscriber eip_unsol_data_sub = nh.subscribe("eip_data_toplc_u", 1, &EipDevice::LoadAsmIn_Callback, &eipDevice); ros::Subscriber eip_sol_data_sub = nh.subscribe("eip_data_toplc_s", 1, &EipDevice::LoadAsmIn_Callback, &eipDevice); ROS_INFO("Starting Process Loop"); int EipStatus = kEipStatusOk; while(ros::ok() && (1 != g_end_stack) && (EipStatus == kEipStatusOk))2 { EipStatus = NetworkHandlerProcessOnce(); if (EipStatus != kEipStatusOk) { ROS_ERROR_STREAM("Error in NetworkHandler loop! Exiting eip_device! -- " << EipStatus ); break; } eipDevice.data_asm_out.raw_plc_data.assign(g_assembly_data096, g_assembly_data096 + OUTPUT_ASSEMBLY_BUFFER_SIZE); eipDevice.data_asm_cfg.raw_plc_data.assign(g_assembly_data097, g_assembly_data097 + CONFIG_ASSEMBLY_BUFFER_SIZE); eip_data_pub.publish(eipDevice.data_asm_out); eip_config_pub.publish(eipDevice.data_asm_cfg); eip_status_pub.publish(eipDevice.device_status); ros::spinOnce(); throttle.sleep(); } ROS_INFO("Finish network handler"); NetworkHandlerFinish(); ROS_INFO("Shutdown CIP Stack"); ShutdownCipStack(); return g_end_stack; } void LeaveStack(int signal) { (void) signal; OPENER_TRACE_STATE("got signal HUP\n"); ROS_INFO("HUP Signal!"); g_end_stack = 1; }
if (-1 == cap_set_flag(capabilities, CAP_EFFECTIVE, 1, capabilies_list, CAP_SET) ) { cap_free(capabilities); ROS_ERROR("Could not set CAP_NET_RAW capability"); exit(0); }
if_condition
[ { "content": "#ifndef EIP_DEVICE_H\n\n#define EIP_DEVICE_H\n\n\n\n#define INPUT_ASSEMBLY_BUFFER_SIZE 32\n\n#define OUTPUT_ASSEMBLY_BUFFER_SIZE 32\n\n#define CONFIG_ASSEMBLY_BUFFER_SIZE 10\n\n#define EXPLICIT_ASSEMBLY_BUFFER_SIZE 32\n\n\n\n#include <iostream>\n\n#include <string>\n\n#include<memory>\n\n\n\ne...
C++
src/Plugins/TundraLogic/Client.cpp
realXtend/tundra-urho3d
436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8
#include "StableHeaders.h" #include "Client.h" #include "UserConnectedResponseData.h" #include "TundraLogic.h" #include "KristalliProtocol.h" #include "SyncManager.h" #include "SyncState.h" #include "MsgLogin.h" #include "MsgLoginReply.h" #include "Framework.h" #include "Scene.h" #include "SceneAPI.h" #include "AssetAPI.h" #include "LoggingFunctions.h" #include "TundraLogicUtils.h" #include "TundraMessages.h" #include "Placeable.h" #include "UrhoRenderer.h" #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/Resource/XMLElement.h> #include <Urho3D/Core/StringUtils.h> using namespace kNet; namespace Tundra { Client::Client(TundraLogic* owner) : Object(owner->GetContext()), owner_(owner), framework_(owner->GetFramework()), loginstate_(NotConnected), reconnect_(false), client_id_(0) { serverUserConnection_ = KNetUserConnectionPtr(new KNetUserConnection(context_)); serverUserConnection_->properties["authenticated"] = true; serverUserConnection_->syncState = SharedPtr<SceneSyncState>(new SceneSyncState(0, false)); } Client::~Client() { } void Client::Update(float) { if (!owner_->IsServer()) CheckLogin(); } void Client::Login(const String& address, unsigned short port, const String& username, const String& password, const String &protocol) { if (IsConnected()) DoLogout(); SetLoginProperty("username", username); SetLoginProperty("password", password); String p = protocol.Trimmed().ToLower(); kNet::SocketTransportLayer transportLayer = kNet::StringToSocketTransportLayer(p.CString()); if (transportLayer == kNet::InvalidTransportLayer && !p.Empty()) { LogError("Client::Login: Cannot log to server using unrecognized protocol: " + p); return; } Login(address, port, transportLayer); } void Client::Login(const String& address, unsigned short port, kNet::SocketTransportLayer protocol) { if (owner_->IsServer()) { LogError("Already running a server, cannot login to a world as a client"); return; } reconnect_ = false; KristalliProtocol *kristalli = owner_->KristalliProtocol(); if (protocol == kNet::InvalidTransportLayer) { LogInfo("Client::Login: No protocol specified, using the default value."); protocol = kristalli->defaultTransport; } SetLoginProperty("protocol", String(SocketTransportLayerToString(protocol).c_str()).ToLower()); SetLoginProperty("address", address); SetLoginProperty("port", port); SetLoginProperty("client-version", "2.5.4.1"); SetLoginProperty("client-name", "Name"); SetLoginProperty("client-organization", "Org"); kristalli->NetworkMessageReceived.Connect(this, &Client::HandleKristalliMessage); kristalli->ConnectionAttemptFailed.Connect(this, &Client::OnConnectionAttemptFailed); kristalli->Connect(address.CString(), port, protocol); loginstate_ = ConnectionPending; client_id_ = 0; } void Client::Logout() { DelayedLogout(); } void Client::DelayedLogout() { DoLogout(false); } void Client::DoLogout(bool fail) { if (loginstate_ != NotConnected) { if (MessageConnection()) { owner_->KristalliProtocol()->Disconnect(); LogInfo("Disconnected"); } serverUserConnection_->connection = 0; loginstate_ = NotConnected; client_id_ = 0; framework_->Scene()->RemoveScene("TundraClient"); framework_->Asset()->ForgetAllAssets(); Disconnected.Emit(); } if (fail) { String failreason = LoginProperty("LoginFailed").GetString(); LoginFailed.Emit(failreason); } else { properties_.Clear(); } SharedPtr<KristalliProtocol> kristalli = owner_->KristalliProtocol(); kristalli->NetworkMessageReceived.Disconnect(this, &Client::HandleKristalliMessage); kristalli->ConnectionAttemptFailed.Disconnect(this, &Client::OnConnectionAttemptFailed); LogInfo("Client logged out."); } bool Client::IsConnected() const { return loginstate_ == LoggedIn; } void Client::SetLoginProperty(String key, Urho3D::Variant value) { key = key.Trimmed(); if (value.IsEmpty()) properties_.Erase(properties_.Find(key)); else properties_[key] = value; } Urho3D::Variant Client::LoginProperty(String key) const { key = key.Trimmed(); auto i = properties_.Find(key); if (i != properties_.End()) return i.ptr_; else return Urho3D::Variant(); } bool Client::HasLoginProperty(String key) const { auto i = properties_.Find(key); if (i == properties_.End()) return false; else return !i->second_.IsEmpty(); } String Client::LoginPropertiesAsXml() const { Urho3D::XMLFile xml(owner_->GetContext()); Urho3D::XMLElement rootElem = xml.CreateRoot("login"); for(auto iter = properties_.Begin(); iter != properties_.End(); ++iter) { Urho3D::XMLElement element = rootElem.CreateChild(iter->first_); element.SetAttribute("value", iter->second_.ToString()); } return xml.ToString(); } void Client::CheckLogin() { kNet::MessageConnection* connection = MessageConnection(); switch(loginstate_) { case ConnectionPending: if (connection && connection->GetConnectionState() == kNet::ConnectionOK) { loginstate_ = ConnectionEstablished; MsgLogin msg; AboutToConnect.Emit(); msg.loginData = StringToBuffer(LoginPropertiesAsXml()); DataSerializer ds(msg.Size() + 4); msg.SerializeTo(ds); ds.AddVLE<kNet::VLE8_16_32>(cHighestSupportedProtocolVersion); connection->SendMessage(msg.messageID, msg.reliable, msg.inOrder, msg.priority, 0, ds.GetData(), ds.BytesFilled()); } break; case LoggedIn: if (!connection || connection->GetConnectionState() != kNet::ConnectionOK) loginstate_ = ConnectionPending; break; } } kNet::MessageConnection* Client::MessageConnection() { return owner_->KristalliProtocol()->MessageConnection(); } KNetUserConnectionPtr Client::ServerUserConnection() const { return serverUserConnection_; } void Client::OnConnectionAttemptFailed() { String address = LoginProperty("address").GetString(); String port = LoginProperty("port").GetString(); String protocol = LoginProperty("protocol").GetString(); String failReason = "Could not connect to host"; if (!address.Empty()) { failReason.Append(" " + address); if (!port.Empty()) failReason.Append(":" + port); if (!protocol.Empty()) failReason.Append(" with " + protocol.ToUpper()); } SetLoginProperty("LoginFailed", failReason); DoLogout(true); } void Client::HandleKristalliMessage(kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t messageId, const char* data, size_t numBytes) { if (source != MessageConnection()) { LogWarning("Client: dropping message " + String(messageId) + " from unknown source"); return; } switch(messageId) { case MsgLoginReply::messageID: { HandleLoginReply(source, data, numBytes); } break; } NetworkMessageReceived.Emit(packetId, messageId, data, numBytes); serverUserConnection_->EmitNetworkMessageReceived(packetId, messageId, data, numBytes); } void Client::HandleLoginReply(kNet::MessageConnection* , const char *data, size_t numBytes) { DataDeserializer dd(data, numBytes); MsgLoginReply msg; msg.DeserializeFrom(dd); serverUserConnection_->protocolVersion = ProtocolOriginal; if (dd.BytesLeft()) serverUserConnection_->protocolVersion = (NetworkProtocolVersion)dd.ReadVLE<kNet::VLE8_16_32>(); if (msg.success) { loginstate_ = LoggedIn; client_id_ = msg.userID; LogInfo("Logged in successfully"); if (!reconnect_) { serverUserConnection_->connection = MessageConnection(); ScenePtr scene = framework_->Scene()->CreateScene("TundraClient", true, false); owner_->SyncManager()->RegisterToScene(scene); UserConnectedResponseData responseData; if (msg.loginReplyData.size() > 0) { String responseDataStr((const char *)&msg.loginReplyData[0], (int)msg.loginReplyData.size()); responseData.responseDataXml = new Urho3D::XMLFile(context_); responseData.responseDataXml->FromString(responseDataStr); } Connected.Emit(&responseData); } else { ScenePtr scene = framework_->Scene()->SceneByName("TundraClient"); if (scene) scene->RemoveAllEntities(true, AttributeChange::LocalOnly); } reconnect_ = true; } else { String response((const char *)&msg.loginReplyData[0], (int)msg.loginReplyData.size()); if (!response.Empty()) SetLoginProperty("LoginFailed", response); DoLogout(true); } } void Client::HandleClientJoined(kNet::MessageConnection* , const MsgClientJoined& ) { } void Client::HandleClientLeft(kNet::MessageConnection* , const MsgClientLeft& ) { } }
#include "StableHeaders.h" #include "Client.h" #include "UserConnectedResponseData.h" #include "TundraLogic.h" #include "KristalliProtocol.h" #include "SyncManager.h" #include "SyncState.h" #include "MsgLogin.h" #include "MsgLoginReply.h" #include "Framework.h" #include "Scene.h" #include "SceneAPI.h" #include "AssetAPI.h" #include "LoggingFunctions.h" #include "TundraLogicUtils.h" #include "TundraMessages.h" #include "Placeable.h" #include "UrhoRenderer.h" #include <Urho3D/Resource/XMLFile.h> #include <Urho3D/Resource/XMLElement.h> #include <Urho3D/Core/StringUtils.h> using namespace kNet; namespace Tundra { Client::Client(TundraLogic* owner) : Object(owner->GetContext()), owner_(owner), framework_(owner->GetFramework()), loginstate_(NotConnected), reconnect_(false), client_id_(0) { serverUserConnection_ = KNetUserConnectionPtr(new KNetUserConnection(context_)); serverUserConnection_->properties["authenticated"] = true; serverUserConnection_->syncState = SharedPtr<SceneSyncState>(new SceneSyncState(0, false)); } Client::~Client() { } void Client::Update(float) { if (!owner_->IsServer()) CheckLogin(); } void Client::Login(const String& address, unsigned short port, const String& username, const String& password, const String &protocol) { if (IsConnected()) DoLogout(); SetLoginProperty("username", username); SetLoginProperty("password", password); String p = protocol.Trimmed().ToLower(); kNet::SocketTransportLayer transportLayer = kNet::StringToSocketTransportLayer(p.CString()); if (transportLayer == kNet::InvalidTransportLayer && !p.Empty()) { LogError("Client::Login: Cannot log to server using unrecognized protocol: " + p); return; } Login(address, port, transportLayer); } void Client::Login(const String& address, unsigned short port, kNet::SocketTransportLayer protocol) { if (owner_->IsServer()) { LogError("Already running a server, cannot login to a world as a client"); return; } reconnect_ = false; KristalliProtocol *kristalli = owner_->KristalliProtocol();
SetLoginProperty("protocol", String(SocketTransportLayerToString(protocol).c_str()).ToLower()); SetLoginProperty("address", address); SetLoginProperty("port", port); SetLoginProperty("client-version", "2.5.4.1"); SetLoginProperty("client-name", "Name"); SetLoginProperty("client-organization", "Org"); kristalli->NetworkMessageReceived.Connect(this, &Client::HandleKristalliMessage); kristalli->ConnectionAttemptFailed.Connect(this, &Client::OnConnectionAttemptFailed); kristalli->Connect(address.CString(), port, protocol); loginstate_ = ConnectionPending; client_id_ = 0; } void Client::Logout() { DelayedLogout(); } void Client::DelayedLogout() { DoLogout(false); } void Client::DoLogout(bool fail) { if (loginstate_ != NotConnected) { if (MessageConnection()) { owner_->KristalliProtocol()->Disconnect(); LogInfo("Disconnected"); } serverUserConnection_->connection = 0; loginstate_ = NotConnected; client_id_ = 0; framework_->Scene()->RemoveScene("TundraClient"); framework_->Asset()->ForgetAllAssets(); Disconnected.Emit(); } if (fail) { String failreason = LoginProperty("LoginFailed").GetString(); LoginFailed.Emit(failreason); } else { properties_.Clear(); } SharedPtr<KristalliProtocol> kristalli = owner_->KristalliProtocol(); kristalli->NetworkMessageReceived.Disconnect(this, &Client::HandleKristalliMessage); kristalli->ConnectionAttemptFailed.Disconnect(this, &Client::OnConnectionAttemptFailed); LogInfo("Client logged out."); } bool Client::IsConnected() const { return loginstate_ == LoggedIn; } void Client::SetLoginProperty(String key, Urho3D::Variant value) { key = key.Trimmed(); if (value.IsEmpty()) properties_.Erase(properties_.Find(key)); else properties_[key] = value; } Urho3D::Variant Client::LoginProperty(String key) const { key = key.Trimmed(); auto i = properties_.Find(key); if (i != properties_.End()) return i.ptr_; else return Urho3D::Variant(); } bool Client::HasLoginProperty(String key) const { auto i = properties_.Find(key); if (i == properties_.End()) return false; else return !i->second_.IsEmpty(); } String Client::LoginPropertiesAsXml() const { Urho3D::XMLFile xml(owner_->GetContext()); Urho3D::XMLElement rootElem = xml.CreateRoot("login"); for(auto iter = properties_.Begin(); iter != properties_.End(); ++iter) { Urho3D::XMLElement element = rootElem.CreateChild(iter->first_); element.SetAttribute("value", iter->second_.ToString()); } return xml.ToString(); } void Client::CheckLogin() { kNet::MessageConnection* connection = MessageConnection(); switch(loginstate_) { case ConnectionPending: if (connection && connection->GetConnectionState() == kNet::ConnectionOK) { loginstate_ = ConnectionEstablished; MsgLogin msg; AboutToConnect.Emit(); msg.loginData = StringToBuffer(LoginPropertiesAsXml()); DataSerializer ds(msg.Size() + 4); msg.SerializeTo(ds); ds.AddVLE<kNet::VLE8_16_32>(cHighestSupportedProtocolVersion); connection->SendMessage(msg.messageID, msg.reliable, msg.inOrder, msg.priority, 0, ds.GetData(), ds.BytesFilled()); } break; case LoggedIn: if (!connection || connection->GetConnectionState() != kNet::ConnectionOK) loginstate_ = ConnectionPending; break; } } kNet::MessageConnection* Client::MessageConnection() { return owner_->KristalliProtocol()->MessageConnection(); } KNetUserConnectionPtr Client::ServerUserConnection() const { return serverUserConnection_; } void Client::OnConnectionAttemptFailed() { String address = LoginProperty("address").GetString(); String port = LoginProperty("port").GetString(); String protocol = LoginProperty("protocol").GetString(); String failReason = "Could not connect to host"; if (!address.Empty()) { failReason.Append(" " + address); if (!port.Empty()) failReason.Append(":" + port); if (!protocol.Empty()) failReason.Append(" with " + protocol.ToUpper()); } SetLoginProperty("LoginFailed", failReason); DoLogout(true); } void Client::HandleKristalliMessage(kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t messageId, const char* data, size_t numBytes) { if (source != MessageConnection()) { LogWarning("Client: dropping message " + String(messageId) + " from unknown source"); return; } switch(messageId) { case MsgLoginReply::messageID: { HandleLoginReply(source, data, numBytes); } break; } NetworkMessageReceived.Emit(packetId, messageId, data, numBytes); serverUserConnection_->EmitNetworkMessageReceived(packetId, messageId, data, numBytes); } void Client::HandleLoginReply(kNet::MessageConnection* , const char *data, size_t numBytes) { DataDeserializer dd(data, numBytes); MsgLoginReply msg; msg.DeserializeFrom(dd); serverUserConnection_->protocolVersion = ProtocolOriginal; if (dd.BytesLeft()) serverUserConnection_->protocolVersion = (NetworkProtocolVersion)dd.ReadVLE<kNet::VLE8_16_32>(); if (msg.success) { loginstate_ = LoggedIn; client_id_ = msg.userID; LogInfo("Logged in successfully"); if (!reconnect_) { serverUserConnection_->connection = MessageConnection(); ScenePtr scene = framework_->Scene()->CreateScene("TundraClient", true, false); owner_->SyncManager()->RegisterToScene(scene); UserConnectedResponseData responseData; if (msg.loginReplyData.size() > 0) { String responseDataStr((const char *)&msg.loginReplyData[0], (int)msg.loginReplyData.size()); responseData.responseDataXml = new Urho3D::XMLFile(context_); responseData.responseDataXml->FromString(responseDataStr); } Connected.Emit(&responseData); } else { ScenePtr scene = framework_->Scene()->SceneByName("TundraClient"); if (scene) scene->RemoveAllEntities(true, AttributeChange::LocalOnly); } reconnect_ = true; } else { String response((const char *)&msg.loginReplyData[0], (int)msg.loginReplyData.size()); if (!response.Empty()) SetLoginProperty("LoginFailed", response); DoLogout(true); } } void Client::HandleClientJoined(kNet::MessageConnection* , const MsgClientJoined& ) { } void Client::HandleClientLeft(kNet::MessageConnection* , const MsgClientLeft& ) { } }
if (protocol == kNet::InvalidTransportLayer) { LogInfo("Client::Login: No protocol specified, using the default value."); protocol = kristalli->defaultTransport; }
if_condition
[ { "content": "/// Implements kNet protocol -based server and client functionality.\n\nclass TUNDRALOGIC_API KristalliProtocol : public Object, public kNet::IMessageHandler, public kNet::INetworkServerListener\n\n{\n\n URHO3D_OBJECT(KristalliProtocol, Object);\n\n\n\npublic:\n\n KristalliProtocol(TundraLog...
C++
Audio/src/Windows/AudioOutput_WASAPI.cpp
Pants/unnamed-sdvx-clone
28a4b537e40bfe45a48c63c20f5dc4ae5702feab
#include "stdafx.h" #include "AudioOutput.hpp" #include "Shared/Thread.hpp" #ifdef _WIN32 #include "Audioclient.h" #include "Mmdeviceapi.h" #include "comdef.h" #include "Functiondiscoverykeys_devpkey.h" #define REFTIME_NS (100) #define REFTIMES_PER_MICROSEC (1000/REFTIME_NS) #define REFTIMES_PER_MILLISEC (REFTIMES_PER_MICROSEC * 1000) #define REFTIMES_PER_SEC (REFTIMES_PER_MILLISEC * 1000) #define SAFE_RELEASE(punk) \ if ((punk) != NULL) \ { (punk)->Release(); (punk) = nullptr; } static const uint32_t freq = 44100; static const uint32_t channels = 2; static const uint32_t numBuffers = 2; static const uint32_t bufferLength = 10; static const REFERENCE_TIME bufferDuration = (REFERENCE_TIME)(bufferLength * REFTIMES_PER_MILLISEC); class NotificationClient : public IMMNotificationClient { public: class AudioOutput_Impl* output; virtual HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(_In_ LPCWSTR pwstrDeviceId, _In_ DWORD dwNewState); virtual HRESULT STDMETHODCALLTYPE OnDeviceAdded(_In_ LPCWSTR pwstrDeviceId); virtual HRESULT STDMETHODCALLTYPE OnDeviceRemoved(_In_ LPCWSTR pwstrDeviceId); virtual HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(_In_ EDataFlow flow, _In_ ERole role, _In_ LPCWSTR pwstrDefaultDeviceId); virtual HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(_In_ LPCWSTR pwstrDeviceId, _In_ const PROPERTYKEY key); virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { return E_NOINTERFACE; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; } virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; } }; class AudioOutput_Impl { public: struct IAudioClient* m_audioClient = nullptr; struct IAudioRenderClient* m_audioRenderClient = nullptr; struct IMMDevice* m_device = nullptr; tWAVEFORMATEX m_format; IMMDeviceEnumerator* m_deviceEnumerator = nullptr; uint32_t m_numBufferFrames; NotificationClient m_notificationClient; double m_bufferLength; static const uint32 m_dummyChannelCount = 2; static const uint32 m_dummyBufferLength = (uint32)((double)freq * 0.2); float m_dummyBuffer[m_dummyBufferLength * m_dummyChannelCount]; double m_dummyTimerPos; Timer m_dummyTimer; IMMDevice* m_pendingDevice = nullptr; bool m_pendingDeviceChange = false; bool m_runAudioThread = false; Thread m_audioThread; IMixer* m_mixer = nullptr; bool m_exclusive = false; public: AudioOutput_Impl() { m_notificationClient.output = this; } ~AudioOutput_Impl() { Stop(); CloseDevice(); SAFE_RELEASE(m_pendingDevice); if(m_deviceEnumerator) { m_deviceEnumerator->UnregisterEndpointNotificationCallback(&m_notificationClient); SAFE_RELEASE(m_deviceEnumerator); } } void Start() { if(m_runAudioThread) return; m_runAudioThread = true; m_audioThread = Thread(&AudioOutput_Impl::AudioThread, this); } void Stop() { if(!m_runAudioThread) return; m_runAudioThread = false; if(m_audioThread.joinable()) m_audioThread.join(); } bool Init(bool exclusive) { m_exclusive = exclusive; HRESULT res; const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); CoInitialize(nullptr); if(!m_deviceEnumerator) { res = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&m_deviceEnumerator); if(res != S_OK) throw _com_error(res); m_deviceEnumerator->RegisterEndpointNotificationCallback(&m_notificationClient); } IMMDevice* defaultDevice = nullptr; m_deviceEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eMultimedia, &defaultDevice); return OpenDevice(defaultDevice); } void CloseDevice() { if(m_audioClient) m_audioClient->Stop(); SAFE_RELEASE(m_device); SAFE_RELEASE(m_audioClient); SAFE_RELEASE(m_audioRenderClient); } IMMDevice* FindDevice(LPCWSTR devId) { assert(m_deviceEnumerator); IMMDevice* newDevice = nullptr; if(m_deviceEnumerator->GetDevice(devId, &newDevice) != S_OK) { SAFE_RELEASE(newDevice); return nullptr; } return newDevice; } bool OpenDevice(LPCWSTR devId) { return OpenDevice(FindDevice(devId)); } bool OpenDevice(IMMDevice* device) { CloseDevice(); if(!device) return OpenNullDevice(); HRESULT res = 0; m_device = device; res = m_device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void**)&m_audioClient); if(res != S_OK) throw _com_error(res); WAVEFORMATEX* mixFormat = nullptr; res = m_audioClient->GetMixFormat(&mixFormat); if (m_exclusive) { REFERENCE_TIME defaultDevicePeriod, minDevicePeriod; m_audioClient->GetDevicePeriod(&defaultDevicePeriod, &minDevicePeriod); res = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mixFormat, NULL); if (res == AUDCLNT_E_UNSUPPORTED_FORMAT) { Log("Default format not supported in exclusive mode, attempting other formats", Logger::Error); int numFormats = 2; WORD formats[2] = { WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT }; int numRates = 5; long sampleRates[5] = {192000L, 96000L, 88200L, 48000L, 44100L}; int numDepths = 3; int bitDepths[3] = {32, 24, 16 }; Vector<WAVEFORMATEX> allFormats; for (size_t f = 0; f < numFormats; f++) { for (size_t d = 0; d < numDepths; d++) { for (size_t r = 0; r < numRates; r++) { long avgBytesPerSec = (bitDepths[d] / 8) * sampleRates[r] * 2; WAVEFORMATEX newformat; newformat.wFormatTag = formats[f]; newformat.nChannels = 2; newformat.nSamplesPerSec = sampleRates[r]; newformat.nAvgBytesPerSec = avgBytesPerSec; newformat.nBlockAlign = 4; newformat.wBitsPerSample = bitDepths[d]; newformat.cbSize = 0; allFormats.Add(newformat); } } } int attemptingFormat = 0; while (res != S_OK) { *mixFormat = allFormats[attemptingFormat]; Logf("Attempting exclusive mode format:\nSample Rate: %dhz,\nBit Depth: %dbit,\nFormat: %s\n-----", Logger::Info, mixFormat->nSamplesPerSec, mixFormat->wBitsPerSample, mixFormat->wFormatTag == WAVE_FORMAT_PCM ? "PCM" : "IEEE FLOAT" ); res = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mixFormat, NULL); attemptingFormat++; if (attemptingFormat >= allFormats.size()) { break; } } if (res == S_OK) Log("Format successful", Logger::Info); else Log("No accepted format found", Logger::Error); } res = m_audioClient->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, 0, bufferDuration, defaultDevicePeriod, mixFormat, nullptr); } else { res = m_audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, bufferDuration, 0, mixFormat, nullptr); } m_format = *mixFormat; CoTaskMemFree(mixFormat); if(res != S_OK) { Log("Failed to initialize audio client with the selected settings", Logger::Error); SAFE_RELEASE(device); SAFE_RELEASE(m_audioClient); return false; } res = m_audioClient->GetService(__uuidof(IAudioRenderClient), (void**)&m_audioRenderClient); if(res != S_OK) { Log("Failed to get audio render client service.", Logger::Error); SAFE_RELEASE(device); SAFE_RELEASE(m_audioClient); return false; } m_audioClient->GetBufferSize(&m_numBufferFrames); m_bufferLength = (double)m_numBufferFrames / (double)m_format.nSamplesPerSec; res = m_audioClient->Start(); return true; } bool OpenNullDevice() { m_format.nSamplesPerSec = freq; m_format.nChannels = 2; m_dummyTimer.Restart(); m_dummyTimerPos = 0; return true; } bool NullBegin(float*& buffer, uint32_t& numSamples) { if(m_dummyTimer.Milliseconds() > 2) { m_dummyTimerPos += m_dummyTimer.SecondsAsDouble(); m_dummyTimer.Restart(); uint32 availableSamples = (uint32)(m_dummyTimerPos * (double)m_format.nSamplesPerSec); if(availableSamples > 0) { numSamples = Math::Min(m_dummyBufferLength, availableSamples); m_dummyTimerPos = 0; buffer = m_dummyBuffer; return true; } } return false; } bool Begin(float*& buffer, uint32_t& numSamples) { if(m_pendingDeviceChange) { OpenDevice(m_pendingDevice); m_pendingDeviceChange = false; } if(!m_device) return NullBegin(buffer, numSamples); uint32_t numFramesPadding; m_audioClient->GetCurrentPadding(&numFramesPadding); numSamples = m_numBufferFrames - numFramesPadding; if(numSamples > 0) { HRESULT hr = m_audioRenderClient->GetBuffer(numSamples, (BYTE**)&buffer); if(hr != S_OK) { if(hr == AUDCLNT_E_DEVICE_INVALIDATED) { Logf("Audio device unplugged", Logger::Warning); return false; } else { assert(false); } } return true; } return false; } void End(uint32_t numSamples) { if(!m_device) return; if(numSamples > 0) { m_audioRenderClient->ReleaseBuffer(numSamples, 0); } } void AudioThread() { while(m_runAudioThread) { int32 sleepDuration = 1; float* data; uint32 numSamples; if(Begin(data, numSamples)) { if(m_mixer) m_mixer->Mix(data, numSamples); End(numSamples); } std::this_thread::sleep_for(std::chrono::microseconds(100)); } } }; HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceStateChanged(_In_ LPCWSTR pwstrDeviceId, _In_ DWORD dwNewState) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceAdded(_In_ LPCWSTR pwstrDeviceId) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceRemoved(_In_ LPCWSTR pwstrDeviceId) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDefaultDeviceChanged(_In_ EDataFlow flow, _In_ ERole role, _In_ LPCWSTR pwstrDefaultDeviceId) { if(flow == EDataFlow::eRender && role == ERole::eMultimedia) { output->m_pendingDeviceChange = true; output->m_pendingDevice = output->FindDevice(pwstrDefaultDeviceId); } return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnPropertyValueChanged(_In_ LPCWSTR pwstrDeviceId, _In_ const PROPERTYKEY key) { return S_OK; } AudioOutput::AudioOutput() { m_impl = new AudioOutput_Impl(); } AudioOutput::~AudioOutput() { delete m_impl; } bool AudioOutput::Init(bool exclusive) { return m_impl->Init(exclusive); } void AudioOutput::Start(IMixer* mixer) { m_impl->m_mixer = mixer; m_impl->Start(); } void AudioOutput::Stop() { m_impl->Stop(); m_impl->m_mixer = nullptr; } uint32_t AudioOutput::GetNumChannels() const { return m_impl->m_format.nChannels; } uint32_t AudioOutput::GetSampleRate() const { return m_impl->m_format.nSamplesPerSec; } double AudioOutput::GetBufferLength() const { return m_impl->m_bufferLength; } bool AudioOutput::IsIntegerFormat() const { return m_impl->m_format.wFormatTag == WAVE_FORMAT_PCM && m_impl->m_format.wBitsPerSample != 32; } #endif
#include "stdafx.h" #include "AudioOutput.hpp" #include "Shared/Thread.hpp" #ifdef _WIN32 #include "Audioclient.h" #include "Mmdeviceapi.h" #include "comdef.h" #include "Functiondiscoverykeys_devpkey.h" #define REFTIME_NS (100) #define REFTIMES_PER_MICROSEC (1000/REFTIME_NS) #define REFTIMES_PER_MILLISEC (REFTIMES_PER_MICROSEC * 1000) #define REFTIMES_PER_SEC (REFTIMES_PER_MILLISEC * 1000) #define SAFE_RELEASE(punk) \ if ((punk) != NULL) \ { (punk)->Release(); (punk) = nullptr; } static const uint32_t freq = 44100; static const uint32_t channels = 2; static const uint32_t numBuffers = 2; static const uint32_t bufferLength = 10; static const REFERENCE_TIME bufferDuration = (REFERENCE_TIME)(bufferLength * REFTIMES_PER_MILLISEC); class NotificationClient : public IMMNotificationClient { public: class AudioOutput_Impl* output; virtual HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(_In_ LPCWSTR pwstrDeviceId, _In_ DWORD dwNewState); virtual HRESULT STDMETHODCALLTYPE OnDeviceAdded(_In_ LPCWSTR pwstrDeviceId); virtual HRESULT STDMETHODCALLTYPE OnDeviceRemoved(_In_ LPCWSTR pwstrDeviceId); virtual HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(_In_ EDataFlow flow, _In_ ERole role, _In_ LPCWSTR pwstrDefaultDeviceId); virtual HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(_In_ LPCWSTR pwstrDeviceId, _In_ const PROPERTYKEY key); virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { return E_NOINTERFACE; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { return 0; } virtual ULONG STDMETHODCALLTYPE Release(void) { return 0; } }; class AudioOutput_Impl { public: struct IAudioClient* m_audioClient = nullptr; struct IAudioRenderClient* m_audioRenderClient = nullptr; struct IMMDevice* m_device = nullptr; tWAVEFORMATEX m_format; IMMDeviceEnumerator* m_deviceEnumerator = nullptr; uint32_t m_numBufferFrames; NotificationClient m_notificationClient; double m_bufferLength; static const uint32 m_dummyChannelCount = 2; static const uint32 m_dummyBufferLength = (uint32)((double)freq * 0.2); float m_dummyBuffer[m_dummyBufferLength * m_dummyChannelCount]; double m_dummyTimerPos; Timer m_dummyTimer; IMMDevice* m_pendingDevice = nullptr; bool m_pendingDeviceChange = false; bool m_runAudioThread = false; Thread m_audioThread; IMixer* m_mixer = nullptr; bool m_exclusive = false; public: AudioOutput_Impl() { m_notificationClient.output = this; } ~AudioOutput_Impl() { Stop(); CloseDevice(); SAFE_RELEASE(m_pendingDevice); if(m_deviceEnumerator) { m_deviceEnumerator->UnregisterEndpointNotificationCallback(&m_notificationClient); SAFE_RELEASE(m_deviceEnumerator); } } void Start() { if(m_runAudioThread) return; m_runAudioThread = true; m_audioThread = Thread(&AudioOutput_Impl::AudioThread, this); } void Stop() { if(!m_runAudioThread) return; m_runAudioThread = false; if(m_audioThread.joinable()) m_audioThread.join(); } bool Init(bool exclusive) { m_exclusive = exclusive; HRESULT res; const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); CoInitialize(nullptr); if(!m_deviceEnumerator) { res = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&m_deviceEnumerator); if(res != S_OK) throw _com_error(res); m_deviceEnumerator->RegisterEndpointNotificationCallback(&m_notificationClient); } IMMDevice* defaultDevice = nullptr; m_deviceEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eMultimedia, &defaultDevice); return OpenDevice(defaultDevice); } void CloseDevice() { if(m_audioClient) m_audioClient->Stop(); SAFE_RELEASE(m_device); SAFE_RELEASE(m_audioClient); SAFE_RELEASE(m_audioRenderClient); } IMMDevice* FindDevice(LPCWSTR devId) { assert(m_deviceEnumerator); IMMDevice* newDevice = nullptr; if(m_deviceEnumerator->GetDevice(devId, &newDevice) != S_OK) { SAFE_RELEASE(newDevice); return nullptr; } return newDevice; } bool OpenDevice(LPCWSTR devId) { return OpenDevice(FindDevice(devId)); } bool OpenDevice(IMMDevice* device) { CloseDevice(); if(!device) return OpenNullDevice(); HRESULT res = 0; m_device = device; res = m_device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void**)&m_audioClient); if(res != S_OK) throw _com_error(res); WAVEFORMATEX* mixFormat = nullptr; res = m_audioClient->GetMixFormat(&mixFormat); if (m_exclusive) { REFERENCE_TIME defaultDevicePeriod, minDevicePeriod; m_audioClient->GetDevicePeriod(&defaultDevicePeriod, &minDevicePeriod); res = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mixFormat, NULL); if (res == AUDCLNT_E_UNSUPPORTED_FORMAT) { Log("Default format not supported in exclusive mode, attempting other formats", Logger::Error); int numFormats = 2; WORD formats[2] = { WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT }; int numRates = 5; long sampleRates[5] = {192000L, 96000L, 88200L, 48000L, 44100L}; int numDepths = 3; int bitDepths[3] = {32, 24, 16 }; Vector<WAVEFORMATEX> allFormats; for (size_t f = 0; f < numFormats; f++) { for (size_t d = 0; d < numDepths; d++) { for (size_t r = 0; r < numRates; r++) { long avgBytesPerSec = (bitDepths[d] / 8) * sampleRates[r] * 2; WAVEFORMATEX newformat; newformat.wFormatTag = formats[f]; newformat.nChannels = 2; newformat.nSamplesPerSec = sampleRates[r]; newformat.nAvgBytesPerSec = avgBytesPerSec; newformat.nBlockAlign = 4; newformat.wBitsPerSample = bitDepths[d]; newformat.cbSize = 0; allFormats.Add(newformat); } } } int attemptingFormat = 0; while (res != S_OK) { *mixFormat = allFormats[attemptingFormat];
; res = m_audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, mixFormat, NULL); attemptingFormat++; if (attemptingFormat >= allFormats.size()) { break; } } if (res == S_OK) Log("Format successful", Logger::Info); else Log("No accepted format found", Logger::Error); } res = m_audioClient->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE, 0, bufferDuration, defaultDevicePeriod, mixFormat, nullptr); } else { res = m_audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, bufferDuration, 0, mixFormat, nullptr); } m_format = *mixFormat; CoTaskMemFree(mixFormat); if(res != S_OK) { Log("Failed to initialize audio client with the selected settings", Logger::Error); SAFE_RELEASE(device); SAFE_RELEASE(m_audioClient); return false; } res = m_audioClient->GetService(__uuidof(IAudioRenderClient), (void**)&m_audioRenderClient); if(res != S_OK) { Log("Failed to get audio render client service.", Logger::Error); SAFE_RELEASE(device); SAFE_RELEASE(m_audioClient); return false; } m_audioClient->GetBufferSize(&m_numBufferFrames); m_bufferLength = (double)m_numBufferFrames / (double)m_format.nSamplesPerSec; res = m_audioClient->Start(); return true; } bool OpenNullDevice() { m_format.nSamplesPerSec = freq; m_format.nChannels = 2; m_dummyTimer.Restart(); m_dummyTimerPos = 0; return true; } bool NullBegin(float*& buffer, uint32_t& numSamples) { if(m_dummyTimer.Milliseconds() > 2) { m_dummyTimerPos += m_dummyTimer.SecondsAsDouble(); m_dummyTimer.Restart(); uint32 availableSamples = (uint32)(m_dummyTimerPos * (double)m_format.nSamplesPerSec); if(availableSamples > 0) { numSamples = Math::Min(m_dummyBufferLength, availableSamples); m_dummyTimerPos = 0; buffer = m_dummyBuffer; return true; } } return false; } bool Begin(float*& buffer, uint32_t& numSamples) { if(m_pendingDeviceChange) { OpenDevice(m_pendingDevice); m_pendingDeviceChange = false; } if(!m_device) return NullBegin(buffer, numSamples); uint32_t numFramesPadding; m_audioClient->GetCurrentPadding(&numFramesPadding); numSamples = m_numBufferFrames - numFramesPadding; if(numSamples > 0) { HRESULT hr = m_audioRenderClient->GetBuffer(numSamples, (BYTE**)&buffer); if(hr != S_OK) { if(hr == AUDCLNT_E_DEVICE_INVALIDATED) { Logf("Audio device unplugged", Logger::Warning); return false; } else { assert(false); } } return true; } return false; } void End(uint32_t numSamples) { if(!m_device) return; if(numSamples > 0) { m_audioRenderClient->ReleaseBuffer(numSamples, 0); } } void AudioThread() { while(m_runAudioThread) { int32 sleepDuration = 1; float* data; uint32 numSamples; if(Begin(data, numSamples)) { if(m_mixer) m_mixer->Mix(data, numSamples); End(numSamples); } std::this_thread::sleep_for(std::chrono::microseconds(100)); } } }; HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceStateChanged(_In_ LPCWSTR pwstrDeviceId, _In_ DWORD dwNewState) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceAdded(_In_ LPCWSTR pwstrDeviceId) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDeviceRemoved(_In_ LPCWSTR pwstrDeviceId) { return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnDefaultDeviceChanged(_In_ EDataFlow flow, _In_ ERole role, _In_ LPCWSTR pwstrDefaultDeviceId) { if(flow == EDataFlow::eRender && role == ERole::eMultimedia) { output->m_pendingDeviceChange = true; output->m_pendingDevice = output->FindDevice(pwstrDefaultDeviceId); } return S_OK; } HRESULT STDMETHODCALLTYPE NotificationClient::OnPropertyValueChanged(_In_ LPCWSTR pwstrDeviceId, _In_ const PROPERTYKEY key) { return S_OK; } AudioOutput::AudioOutput() { m_impl = new AudioOutput_Impl(); } AudioOutput::~AudioOutput() { delete m_impl; } bool AudioOutput::Init(bool exclusive) { return m_impl->Init(exclusive); } void AudioOutput::Start(IMixer* mixer) { m_impl->m_mixer = mixer; m_impl->Start(); } void AudioOutput::Stop() { m_impl->Stop(); m_impl->m_mixer = nullptr; } uint32_t AudioOutput::GetNumChannels() const { return m_impl->m_format.nChannels; } uint32_t AudioOutput::GetSampleRate() const { return m_impl->m_format.nSamplesPerSec; } double AudioOutput::GetBufferLength() const { return m_impl->m_bufferLength; } bool AudioOutput::IsIntegerFormat() const { return m_impl->m_format.wFormatTag == WAVE_FORMAT_PCM && m_impl->m_format.wBitsPerSample != 32; } #endif
Logf("Attempting exclusive mode format:\nSample Rate: %dhz,\nBit Depth: %dbit,\nFormat: %s\n-----", Logger::Info, mixFormat->nSamplesPerSec, mixFormat->wBitsPerSample, mixFormat->wFormatTag == WAVE_FORMAT_PCM ? "PCM" : "IEEE FLOAT" )
call_expression
[ { "content": "struct StaticBinding : public IFunctionBinding<R, A...>\n\n{\n\n\tStaticBinding(R(*func)(A...)) : func(func) {};\n\n\tvirtual R Call(A... args) override\n\n\t{\n\n\t\treturn (*func)(args...);\n\n\t}\n\n\tR(*func)(A...);\n\n};\n\n\n\n/* Lambda function binding */\n\ntemplate<typename T, typename R,...
C++
src/local_edge.cc
yjxiong/convnet
f51261942ce5121255c7edd61ce1a589509e76e5
#include "local_edge.h" #include "cudamat_conv.cuh" #include <iostream> LocalEdge::LocalEdge(const config::Edge& edge_config) : EdgeWithWeight(edge_config), kernel_size_(edge_config.kernel_size()), stride_(edge_config.stride()), padding_(edge_config.padding()) {} void LocalEdge::SetTiedTo(Edge* e) { EdgeWithWeight::SetTiedTo(e); LocalEdge* ee = dynamic_cast<LocalEdge*> (e); kernel_size_ = ee->GetKernelSize(); stride_ = ee->GetStride(); padding_ = ee->GetPadding(); } void LocalEdge::DisplayWeights() { if (img_display_ != NULL) { weights_.CopyToHost(); img_display_->DisplayWeights(weights_.GetHostData(), kernel_size_, num_output_channels_, 250, false); } } void LocalEdge::SetImageSize(int image_size) { Edge::SetImageSize(image_size); num_modules_ = (image_size + 2 * padding_ - kernel_size_) / stride_ + 1; } void LocalEdge::AllocateMemoryFprop() { int input_size = kernel_size_ * kernel_size_ * num_input_channels_ * num_modules_ * num_modules_; int bias_locs = num_modules_ * num_modules_; weights_.AllocateGPUMemory(num_output_channels_, input_size); bias_.AllocateGPUMemory(1, num_output_channels_ * bias_locs); } void LocalEdge::AllocateMemoryBprop() { int input_size = kernel_size_ * kernel_size_ * num_input_channels_ * num_modules_ * num_modules_; int bias_locs = num_modules_ * num_modules_; grad_weights_.AllocateGPUMemory(num_output_channels_, input_size); weight_optimizer_->AllocateMemory(num_output_channels_, input_size); grad_bias_.AllocateGPUMemory(1, num_output_channels_ * bias_locs); bias_optimizer_->AllocateMemory(1, num_output_channels_ * bias_locs); } void LocalEdge::AllocateMemory(bool fprop_only) { if (is_tied_) return; Edge::AllocateMemory(fprop_only); num_modules_ = (image_size_ + 2 * padding_ - kernel_size_) / stride_ + 1; cout << name_ << " "; printf("Kernel: %d-%d-%d to %d ", kernel_size_, kernel_size_, num_input_channels_, num_output_channels_); printf("Layer: %d-%d-%d (%d) ", image_size_, image_size_, num_input_channels_, image_size_ * image_size_ * num_input_channels_); AllocateMemoryFprop(); if (!fprop_only) AllocateMemoryBprop(); cout << " Allocated weight " << weights_.GetRows() << " " << weights_.GetCols() << " Locally Connected" << endl; if (num_input_channels_ == 3) { int num_filters = num_output_channels_; int num_filters_w = int(sqrt(num_filters)); int num_filters_h = num_filters / num_filters_w + (((num_filters % num_filters_w) > 0) ? 1 : 0); int width = 250; int height = (width * num_filters_h) / num_filters_w; img_display_ = new ImageDisplayer(width, height, 3, false, "weights"); } } void LocalEdge::ComputeUp(Matrix& input, Matrix& output, bool overwrite) { cudamat *input_mat = input.GetMat(), *output_mat = output.GetMat(), *w_mat = is_tied_? tied_edge_->GetWeight().GetMat() : weights_.GetMat(); int scale_targets = overwrite ? 0 : 1; localUp(input_mat, w_mat, output_mat, num_modules_, -padding_, stride_, num_input_channels_, 1, scale_targets); if (!has_no_bias_) { cudamat* b_mat = is_tied_? tied_edge_->GetBias().GetMat() : bias_.GetMat(); add_row_vec(output_mat, b_mat, output_mat); } } void LocalEdge::ComputeDown(Matrix& deriv_output, Matrix& input, Matrix& output, Matrix& deriv_input, bool overwrite) { cudamat* deriv_output_mat = deriv_output.GetMat(); cudamat* deriv_input_mat = deriv_input.GetMat(); cudamat* w_mat = is_tied_? tied_edge_->GetWeight().GetMat() : weights_.GetMat(); int scale_targets = overwrite ? 0 : 1; localDown(deriv_output_mat, w_mat, deriv_input_mat, image_size_, -padding_, stride_, num_input_channels_, 1, scale_targets); } void LocalEdge::ComputeOuter(Matrix& input, Matrix& deriv_output) { cudamat* input_mat = input.GetMat(); cudamat* deriv_output_mat = deriv_output.GetMat(); cudamat* dw_mat = is_tied_ ? tied_edge_->GetGradWeight().GetMat() : grad_weights_.GetMat(); const int batch_size = input.GetRows(); int scale_targets = GetNumGradsReceived() > 0 ? 1 : 0; localOutp(input_mat, deriv_output_mat, dw_mat, num_modules_, kernel_size_, -padding_, stride_, num_input_channels_, 1, scale_targets, scale_gradients_ / batch_size); if (!has_no_bias_) { cudamat* db_mat = is_tied_ ? tied_edge_->GetGradBias().GetMat() : grad_bias_.GetMat(); Matrix ones; Matrix::GetOnes(1, batch_size, ones); dot(ones.GetMat(), deriv_output_mat, db_mat, scale_targets, scale_gradients_ / batch_size); } IncrementNumGradsReceived(); }
#include "local_edge.h" #include "cudamat_conv.cuh" #include <iostream> LocalEdge::LocalEdge(const config::Edge& edge_config) : EdgeWithWeight(edge_config), kernel_size_(edge_config.kernel_size()), stride_(edge_config.stride()), padding_(edge_config.padding()) {} void LocalEdge::SetTiedTo(Edge* e) { EdgeWithWeight::SetTiedTo(e); LocalEdge* ee = dynamic_cast<LocalEdge*> (e); kernel_size_ = ee->GetKernelSize(); stride_ = ee->GetStride(); padding_ = ee->GetPadding(); } void LocalEdge::DisplayWeights() {
} void LocalEdge::SetImageSize(int image_size) { Edge::SetImageSize(image_size); num_modules_ = (image_size + 2 * padding_ - kernel_size_) / stride_ + 1; } void LocalEdge::AllocateMemoryFprop() { int input_size = kernel_size_ * kernel_size_ * num_input_channels_ * num_modules_ * num_modules_; int bias_locs = num_modules_ * num_modules_; weights_.AllocateGPUMemory(num_output_channels_, input_size); bias_.AllocateGPUMemory(1, num_output_channels_ * bias_locs); } void LocalEdge::AllocateMemoryBprop() { int input_size = kernel_size_ * kernel_size_ * num_input_channels_ * num_modules_ * num_modules_; int bias_locs = num_modules_ * num_modules_; grad_weights_.AllocateGPUMemory(num_output_channels_, input_size); weight_optimizer_->AllocateMemory(num_output_channels_, input_size); grad_bias_.AllocateGPUMemory(1, num_output_channels_ * bias_locs); bias_optimizer_->AllocateMemory(1, num_output_channels_ * bias_locs); } void LocalEdge::AllocateMemory(bool fprop_only) { if (is_tied_) return; Edge::AllocateMemory(fprop_only); num_modules_ = (image_size_ + 2 * padding_ - kernel_size_) / stride_ + 1; cout << name_ << " "; printf("Kernel: %d-%d-%d to %d ", kernel_size_, kernel_size_, num_input_channels_, num_output_channels_); printf("Layer: %d-%d-%d (%d) ", image_size_, image_size_, num_input_channels_, image_size_ * image_size_ * num_input_channels_); AllocateMemoryFprop(); if (!fprop_only) AllocateMemoryBprop(); cout << " Allocated weight " << weights_.GetRows() << " " << weights_.GetCols() << " Locally Connected" << endl; if (num_input_channels_ == 3) { int num_filters = num_output_channels_; int num_filters_w = int(sqrt(num_filters)); int num_filters_h = num_filters / num_filters_w + (((num_filters % num_filters_w) > 0) ? 1 : 0); int width = 250; int height = (width * num_filters_h) / num_filters_w; img_display_ = new ImageDisplayer(width, height, 3, false, "weights"); } } void LocalEdge::ComputeUp(Matrix& input, Matrix& output, bool overwrite) { cudamat *input_mat = input.GetMat(), *output_mat = output.GetMat(), *w_mat = is_tied_? tied_edge_->GetWeight().GetMat() : weights_.GetMat(); int scale_targets = overwrite ? 0 : 1; localUp(input_mat, w_mat, output_mat, num_modules_, -padding_, stride_, num_input_channels_, 1, scale_targets); if (!has_no_bias_) { cudamat* b_mat = is_tied_? tied_edge_->GetBias().GetMat() : bias_.GetMat(); add_row_vec(output_mat, b_mat, output_mat); } } void LocalEdge::ComputeDown(Matrix& deriv_output, Matrix& input, Matrix& output, Matrix& deriv_input, bool overwrite) { cudamat* deriv_output_mat = deriv_output.GetMat(); cudamat* deriv_input_mat = deriv_input.GetMat(); cudamat* w_mat = is_tied_? tied_edge_->GetWeight().GetMat() : weights_.GetMat(); int scale_targets = overwrite ? 0 : 1; localDown(deriv_output_mat, w_mat, deriv_input_mat, image_size_, -padding_, stride_, num_input_channels_, 1, scale_targets); } void LocalEdge::ComputeOuter(Matrix& input, Matrix& deriv_output) { cudamat* input_mat = input.GetMat(); cudamat* deriv_output_mat = deriv_output.GetMat(); cudamat* dw_mat = is_tied_ ? tied_edge_->GetGradWeight().GetMat() : grad_weights_.GetMat(); const int batch_size = input.GetRows(); int scale_targets = GetNumGradsReceived() > 0 ? 1 : 0; localOutp(input_mat, deriv_output_mat, dw_mat, num_modules_, kernel_size_, -padding_, stride_, num_input_channels_, 1, scale_targets, scale_gradients_ / batch_size); if (!has_no_bias_) { cudamat* db_mat = is_tied_ ? tied_edge_->GetGradBias().GetMat() : grad_bias_.GetMat(); Matrix ones; Matrix::GetOnes(1, batch_size, ones); dot(ones.GetMat(), deriv_output_mat, db_mat, scale_targets, scale_gradients_ / batch_size); } IncrementNumGradsReceived(); }
if (img_display_ != NULL) { weights_.CopyToHost(); img_display_->DisplayWeights(weights_.GetHostData(), kernel_size_, num_output_channels_, 250, false); }
if_condition
[ { "content": "#include \"conv_edge.h\"\n\n#include \"cudamat_conv.cuh\"\n\n#include <iostream>\n\n\n\nConvEdge::ConvEdge(const config::Edge& edge_config) :\n\n EdgeWithWeight(edge_config),\n\n kernel_size_(edge_config.kernel_size()),\n\n stride_(edge_config.stride()),\n\n padding_(edge_config.padding()),\n\...
C++
coursework/os/code/src/emsh/fs/stream.cpp
huaouo/history_code
475193986caf025c9569fb0690a12bed0cf630b4
#include <math.h> #include <string.h> #include "stream.h" #include "lnkblk.h" namespace emsh::fs { Stream::Stream(const uint16_t iaddr) : io(IO::get_instance()), fs(FS::get_instance()), iaddr(iaddr), inode(fs.read_inode(iaddr)), read_pos(0), write_pos(0) {} bool Stream::truncate(size_t len) { if (len > inode.size) return false; auto original_blk_index = static_cast<int>(inode.size / BLK_SIZE); if (inode.size % BLK_SIZE == 0) --original_blk_index; auto target_blk_index = static_cast<int>(len / BLK_SIZE); if (len % BLK_SIZE == 0) --target_blk_index; if (target_blk_index < original_blk_index) { for (auto blk_index = original_blk_index; blk_index > target_blk_index; --blk_index) { if (blk_index < INODE_DADDR_BLK_CNT) { fs.free_dblk(inode.d_addr[blk_index]); inode.d_addr[blk_index] = 0; } else if (blk_index < INODE_DJADDR_BLK_CNT) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; fs.free_dblk(j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]); j_blk->addr[blk_index - INODE_DADDR_BLK_CNT] = 0; io.write_block(&_j_blk, inode.j_addr); if (blk_index == INODE_DADDR_BLK_CNT) { fs.free_dblk(inode.j_addr); inode.j_addr = 0; } } else { auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); Blk _j_blk = io.read_block(inode.jj_addr); auto j_blk = (LnkBlk *) &_j_blk; Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; fs.free_dblk(jj_blk->addr[blk_index_offset]); jj_blk->addr[blk_index_offset] = 0; io.write_block(&_jj_blk, j_blk->addr[blk_index_id]); if (blk_index_offset == 0) { fs.free_dblk(j_blk->addr[blk_index_id]); j_blk->addr[blk_index_id] = 0; io.write_block(&_j_blk, inode.jj_addr); } if (blk_index_remain == 0) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; } } } } inode.size = len; inode.stamp = time(nullptr); fs.write_inode(&inode, iaddr); return true; } size_t Stream::write(const char *data, size_t len) { if (!fs.can_alloc_dblk(static_cast<uint16_t>(len/BLK_SIZE))) return 0; size_t data_pos = 0; auto current_blk_left_bytes = write_pos - write_pos / BLK_SIZE * BLK_SIZE; auto new_alloc_blk_num = static_cast<uint16_t>( ceil(static_cast<double>(len - current_blk_left_bytes) / BLK_SIZE)); if (!fs.can_alloc_dblk(new_alloc_blk_num)) return 0; while (true) { bool alloc_fail = false; auto blk_index = static_cast<uint16_t>(write_pos / BLK_SIZE); auto offset = static_cast<uint16_t>(write_pos % BLK_SIZE); auto write_cycle_size = static_cast<uint16_t>( std::min(static_cast<size_t>(BLK_SIZE - offset), len - data_pos)); if (write_cycle_size == 0) break; uint16_t blk_id = 0; if (blk_index < INODE_DADDR_BLK_CNT) { if ((blk_id = inode.d_addr[blk_index]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { alloc_fail = true; } else { blk_id = inode.d_addr[blk_index] = new_blk_id; fs.write_inode(&inode, iaddr); } } } else if (blk_index < INODE_DJADDR_BLK_CNT) { bool prev_alloc = false; if (inode.j_addr == 0) { uint16_t new_j_addr = fs.alloc_dblk(); if (new_j_addr == DBLK_FAIL_ID) { alloc_fail = true; } else { prev_alloc = true; inode.j_addr = new_j_addr; fs.write_inode(&inode, iaddr); io.clear_block(new_j_addr); } } if (!alloc_fail) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; if ((blk_id = j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { if (prev_alloc) { fs.free_dblk(inode.j_addr); inode.j_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { blk_id = j_blk->addr[blk_index - INODE_DADDR_BLK_CNT] = new_blk_id; io.write_block(&_j_blk, inode.j_addr); } } } } else { bool pprev_alloc = false, prev_alloc = false; auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); if (inode.jj_addr == 0) { uint16_t new_j_blk_id = fs.alloc_dblk(); if (new_j_blk_id == DBLK_FAIL_ID) { alloc_fail = true; } else { inode.jj_addr = new_j_blk_id; fs.write_inode(&inode, iaddr); io.clear_block(new_j_blk_id); pprev_alloc = true; } } Blk _j_blk{}; auto j_blk = (LnkBlk *) &_j_blk; if (!alloc_fail) { _j_blk = io.read_block(inode.jj_addr); if (j_blk->addr[blk_index_id] == 0) { uint16_t new_jj_blk_id = fs.alloc_dblk(); if (new_jj_blk_id == DBLK_FAIL_ID) { if (pprev_alloc) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { j_blk->addr[blk_index_id] = new_jj_blk_id; io.write_block(&_j_blk, inode.jj_addr); io.clear_block(new_jj_blk_id); prev_alloc = true; } } } if (!alloc_fail) { Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; if ((blk_id = jj_blk->addr[blk_index_offset]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { if (prev_alloc) { fs.free_dblk(j_blk->addr[blk_index_id]); j_blk->addr[blk_index_id] = 0; io.write_block(&_j_blk, inode.jj_addr); } if (pprev_alloc) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { blk_id = jj_blk->addr[blk_index_offset] = new_blk_id; io.write_block(&_jj_blk, j_blk->addr[blk_index_id]); } } } } if (alloc_fail) break; IF_INTERNAL_ERROR(blk_id == 0); Blk blk = io.read_block(blk_id); memcpy((char *) &blk + offset, data + data_pos, write_cycle_size); io.write_block(&blk, blk_id); write_pos += write_cycle_size; data_pos += write_cycle_size; if (write_pos > inode.size) inode.size = write_pos; } inode.stamp = time(nullptr); fs.write_inode(&inode, iaddr); return data_pos; } size_t Stream::read(char *data, size_t len) { size_t data_pos = 0; while (true) { auto blk_index = static_cast<uint16_t>(read_pos / BLK_SIZE); auto offset = static_cast<uint16_t>(read_pos % BLK_SIZE); auto read_cycle_size = static_cast<uint16_t>( std::min(static_cast<size_t>(BLK_SIZE - offset), std::min(inode.size - read_pos, len - data_pos))); if (read_cycle_size == 0) break; Blk blk{}; if (blk_index < INODE_DADDR_BLK_CNT) { blk = io.read_block(inode.d_addr[blk_index]); } else if (blk_index < INODE_DJADDR_BLK_CNT) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; blk = io.read_block(j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]); } else { auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); Blk _j_blk = io.read_block(inode.jj_addr); auto j_blk = (LnkBlk *) &_j_blk; Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; blk = io.read_block(jj_blk->addr[blk_index_offset]); } memcpy(data + data_pos, (char *) &blk + offset, read_cycle_size); read_pos += read_cycle_size; data_pos += read_cycle_size; } return data_pos; } void Stream::seekw(size_t pos) { if (pos > inode.size) pos = inode.size; write_pos = pos; } void Stream::seekr(size_t pos) { if (pos >= inode.size) pos = inode.size; read_pos = pos; } size_t Stream::get_wpos() { return write_pos; } size_t Stream::get_rpos() { return read_pos; } size_t Stream::size() { return inode.size; } }
#include <math.h> #include <string.h> #include "stream.h" #include "lnkblk.h" namespace emsh::fs { Stream::Stream(const uint16_t iaddr) : io(IO::get_instance()), fs(FS::get_instance()), iaddr(iaddr), inode(fs.read_inode(iaddr)), read_pos(0), write_pos(0) {} bool Stream::truncate(size_t len) { if (len > inode.size) return false; auto original_blk_index = static_cast<int>(inode.size / BLK_SIZE); if (inode.size % BLK_SIZE == 0) --original_blk_index; auto target_blk_index = static_cast<int>(len / BLK_SIZE); if (len % BLK_SIZE == 0) --target_blk_index; if (target_blk_index < original_blk_index) { for (auto blk_index = original_blk_index; blk_index > target_blk_index; --blk_index) { if (blk_index < INODE_DADDR_BLK_CNT) { fs.free_dblk(inode.d_addr[blk_index]); inode.d_addr[blk_index] = 0; } else if (blk_index < INODE_DJADDR_BLK_CNT) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; fs.free_dblk(j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]); j_blk->addr[blk_index - INODE_DADDR_BLK_CNT] = 0; io.write_block(&_j_blk, inode.j_addr); if (blk_index == INODE_DADDR_BLK_CNT) { fs.free_dblk(inode.j_addr); inode.j_addr = 0; } } else { auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); Blk _j_blk = io.read_block(inode.jj_addr); auto j_blk = (LnkBlk *) &_j_blk; Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; fs.free_dblk(jj_blk->addr[blk_index_offset]); jj_blk->addr[blk_index_offset] = 0; io.write_block(&_jj_blk, j_blk->addr[blk_index_id]); if (blk_index_offset == 0) { fs.free_dblk(j_blk->addr[blk_index_id]); j_blk->addr[blk_index_id] = 0; io.write_block(&_j_blk, inode.jj_addr); } if (blk_index_remain == 0) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; } } } } inode.size = len; inode.stamp = time(nullptr); fs.write_inode(&inode, iaddr); return true; } size_t Stream::write(const char *data, size_t len) { if (!fs.can_alloc_dblk(static_cast<uint16_t>(len/BLK_SIZE))) return 0; size_t data_pos = 0; auto current_blk_left_bytes = write_pos - write_pos / BLK_SIZE * BLK_SIZE; auto new_alloc_blk_num = static_cast<uint16_t>( ceil(static_cast<double>(len - current_blk_left_bytes) / BLK_SIZE)); if (!fs.can_alloc_dblk(new_alloc_blk_num)) return 0; while (true) { bool alloc_fail = false; auto blk_index = static_cast<uint16_t>(write_pos / BLK_SIZE); auto offset = static_cast<uint16_t>(write_pos % BLK_SIZE); auto write_cycle_size = static_cast<uint16_t>( std::min(static_cast<size_t>(BLK_SIZE - offset), len - data_pos)); if (write_cycle_size == 0) break; uint16_t blk_id = 0; if (blk_index < INODE_DADDR_BLK_CNT) { if ((blk_id = inode.d_addr[blk_index]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { alloc_fail = true; } else { blk_id = inode.d_addr[blk_index] = new_blk_id; fs.write_inode(&inode, iaddr); } } } else if (blk_index < INODE_DJADDR_BLK_CNT) { bool prev_alloc = false; if (inode.j_addr == 0) { uint16_t new_j_addr = fs.alloc_dblk(); if (new_j_addr == DBLK_FAIL_ID) { alloc_fail = true; } else { prev_alloc = true; inode.j_addr = new_j_addr; fs.write_inode(&inode, iaddr); io.clear_block(new_j_addr); } } if (!alloc_fail) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; if ((blk_id = j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { if (prev_alloc) { fs.free_dblk(inode.j_addr); inode.j_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { blk_id = j_blk->addr[blk_index - INODE_DADDR_BLK_CNT] = new_blk_id; io.write_block(&_j_blk, inode.j_addr); } } } } else { bool pprev_alloc = false, prev_alloc = false; auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); if (inode.jj_addr == 0) { uint16_t new_j_blk_id = fs.alloc_dblk(); if (new_j_blk_id == DBLK_FAIL_ID) { alloc_fail = true; } else { inode.jj_addr = new_j_blk_id; fs.write_inode(&inode, iaddr); io.clear_block(new_j_blk_id); pprev_alloc = true; } } Blk _j_blk{}; auto j_blk = (LnkBlk *) &_j_blk; if (!alloc_fail) { _j_blk = io.read_block(inode.jj_addr); if (j_blk->addr[blk_index_id] == 0) { uint16_t new_jj_blk_id = fs.alloc_dblk(); if (new_jj_blk_id == DBLK_FAIL_ID) { if (pprev_alloc) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { j_blk->addr[blk_index_id] = new_jj_blk_id; io.write_block(&_j_blk, inode.jj_addr); io.clear_block(new_jj_blk_id); prev_alloc = true; } } } if (!alloc_fail) { Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; if ((blk_id = jj_blk->addr[blk_index_offset]) == 0) { uint16_t new_blk_id = fs.alloc_dblk(); if (new_blk_id == DBLK_FAIL_ID) { if (prev_alloc) { fs.free_dblk(j_blk->addr[blk_index_id]); j_blk->addr[blk_index_id] = 0; io.write_block(&_j_blk, inode.jj_addr); } if (pprev_alloc) { fs.free_dblk(inode.jj_addr); inode.jj_addr = 0; fs.write_inode(&inode, iaddr); } alloc_fail = true; } else { blk_id = jj_blk->addr[blk_index_offset] = new_blk_id; io.write_block(&_jj_blk, j_blk->addr[blk_index_id]); } } } } if (alloc_fail) break; IF_INTERNAL_ERROR(blk_id == 0); Blk blk = io.read_block(blk_id); memcpy((char *) &blk + offset, data + data_pos, write_cycle_size); io.write_block(&blk, blk_id); write_pos += write_cycle_size; data_pos += write_cycle_size; if (write_pos > inode.size) inode.size = write_pos; } inode.stamp = time(nullptr); fs.write_inode(&inode, iaddr); return data_pos; } size_t Stream::read(char *data, size_t len) { size_t data_pos = 0; while (true) { auto blk_index = static_cast<uint16_t>(read_pos / BLK_SIZE); auto offset = static_cast<uint16_t>(read_pos % BLK_SIZE); auto read_cycle_size = static_cast<uint16_t>( std::min(static_cast<size_t>(BLK_SIZE - offset), std::min(inode.size - read_pos, len - data_pos))); if (read_cycle_size == 0) break; Blk blk{}; if (blk_index < INODE_DADDR_BLK_CNT) { blk = io.read_block(inode.d_addr[blk_index]); } else
memcpy(data + data_pos, (char *) &blk + offset, read_cycle_size); read_pos += read_cycle_size; data_pos += read_cycle_size; } return data_pos; } void Stream::seekw(size_t pos) { if (pos > inode.size) pos = inode.size; write_pos = pos; } void Stream::seekr(size_t pos) { if (pos >= inode.size) pos = inode.size; read_pos = pos; } size_t Stream::get_wpos() { return write_pos; } size_t Stream::get_rpos() { return read_pos; } size_t Stream::size() { return inode.size; } }
if (blk_index < INODE_DJADDR_BLK_CNT) { Blk _j_blk = io.read_block(inode.j_addr); auto j_blk = (LnkBlk *) &_j_blk; blk = io.read_block(j_blk->addr[blk_index - INODE_DADDR_BLK_CNT]); } else { auto blk_index_remain = static_cast<uint16_t>(blk_index - INODE_DJADDR_BLK_CNT); auto blk_index_id = static_cast<uint16_t>(blk_index_remain / LNK_ENTRY_PER_BLK); auto blk_index_offset = static_cast<uint16_t>(blk_index_remain % LNK_ENTRY_PER_BLK); Blk _j_blk = io.read_block(inode.jj_addr); auto j_blk = (LnkBlk *) &_j_blk; Blk _jj_blk = io.read_block(j_blk->addr[blk_index_id]); auto jj_blk = (LnkBlk *) &_jj_blk; blk = io.read_block(jj_blk->addr[blk_index_offset]); }
if_condition
[]
C++
example/m5stack/transmitter/src/main.cpp
yukima77/EnOceanModule
c4d2cdf8738890333085980afb66478f499d21aa
#include <M5Stack.h> #include <SoftwareSerial.h> #define SYNC 0x55 // SYNC SoftwareSerial enoceanSerial(21, 22); const byte CRC8Table[256] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6A, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8D, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3}; byte len_data_dl = 0x01; byte len_raw_data = len_data_dl + 6; byte header[] = { 0x00, len_raw_data, 0x02, 0x0A, }; byte data[] = { 0x21, 0xAA, 0xAA, 0xAA, 0xAA, 0x08, 0xAA, 0xAA, 0xAA }; void setup() { M5.begin(); Serial.begin(9600); Serial.println(); enoceanSerial.begin(57600); M5.Lcd.clear(BLACK); } void loop() { int i; if (M5.BtnA.wasPressed()) { Serial.println("Pressed BtnA."); enoceanSerial.write(SYNC); enoceanSerial.write(header, 4); byte crc8h = 0; for (i = 0; i < 4; i++) { crc8h = CRC8Table[crc8h ^ header[i]]; }; enoceanSerial.write(crc8h); if (data[5] == 0x08) { data[5] = 0x09; Serial.println("Close"); M5.Lcd.clear(BLACK); M5.Lcd.setTextSize(5); M5.Lcd.println("Close"); } else if (data[5] == 0x09) { data[5] = 0x08; Serial.println("Open"); M5.Lcd.clear(BLACK); M5.Lcd.setTextSize(5); M5.Lcd.println("Open"); } enoceanSerial.write(data, len_raw_data + 2); byte crc8d = 0; for (i = 0; i < (len_raw_data + 2); i++) { crc8d = CRC8Table[crc8d ^ data[i]]; }; enoceanSerial.write(crc8d); } M5.Lcd.setCursor(5, 5); M5.update(); delay(100); }
#include <M5Stack.h> #include <SoftwareSerial.h> #define SYNC 0x55 // SYNC SoftwareSerial enoceanSerial(21, 22); const byte CRC8Table[256] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6A, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8D, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3}; byte len_data_dl = 0x01; byte len_raw_data = len_data_dl + 6; byte header[] = { 0x00, len_raw_data, 0x02, 0x0A, }; byte data[] = { 0x21, 0xAA, 0xAA, 0xAA, 0xAA, 0x08, 0xAA, 0xAA, 0xAA }; void setup() { M5.begin(); Serial.begin(9600); Serial.println(); enoceanSerial.begin(57600); M5.Lcd.clear(BLACK); } void loop() { int i; if (M5.BtnA.wasPressed()) { Serial.println("Pressed BtnA."); enoceanSerial.write(SYNC); enoceanSerial.write(header, 4); byte crc8h = 0; for (i = 0; i < 4; i++) { crc8h = CRC8Table[crc8h ^ header[i]]; }; enoceanSerial.write(crc8h); if (data[5] == 0x08) { data[5] = 0x09; Serial.println("Close"); M5.Lcd.clear(BLACK); M5.Lcd.setTextSize(5); M5.Lcd.println("Close"); } else
enoceanSerial.write(data, len_raw_data + 2); byte crc8d = 0; for (i = 0; i < (len_raw_data + 2); i++) { crc8d = CRC8Table[crc8d ^ data[i]]; }; enoceanSerial.write(crc8d); } M5.Lcd.setCursor(5, 5); M5.update(); delay(100); }
if (data[5] == 0x09) { data[5] = 0x08; Serial.println("Open"); M5.Lcd.clear(BLACK); M5.Lcd.setTextSize(5); M5.Lcd.println("Open"); }
if_condition
[ { "content": "#include <M5Stack.h>\n\n#include <SoftwareSerial.h>\n\n\n\n#define LCDHIGH 240\n\n#define LCDWIDTH 320\n\n\n\n#define TEMPID 0x05002729 // EnOceanモジュールID\n\n#define SYNC 0x55 // SYNCバイト\n\n\n\nSoftwareSerial enoceanSerial(21, 22); // RX, TX\n\n\n\nvoid setup()\n\n{\n\n M5.begin();\n\n\n\n...
C++
src/appleseed/foundation/array/meshalgorithm.cpp
jaichhabra/appleseed
bc952ad860ca6f93bfe4cdd2b966acac4cb42e20
#include "foundation/array/applyvisitor.h" #include "foundation/array/array.h" #include "foundation/array/arrayview.h" #include "foundation/array/exception.h" #include "foundation/array/meshalgorithm.h" #include <algorithm> #include <cstdint> namespace foundation { namespace { struct ComputeBBoxVisitor { AABB3f m_bbox; ComputeBBoxVisitor() { m_bbox.invalidate(); } explicit ComputeBBoxVisitor(const AABB3f& bbox) : m_bbox(bbox) { } void operator()(const ArrayView<Vector3f>& view) { for (const Vector3f& p : view) m_bbox.insert(p); } template <typename T> void operator()(const ArrayView<T>& view) { throw BadArrayTypeException(); } }; class FaceSidesInfoVisitor { public: explicit FaceSidesInfoVisitor(FaceSidesInfo& stats) : m_stats(stats) { } void operator()(const ArrayView<std::uint8_t>& view) { collect_stats(view); } void operator()(const ArrayView<std::uint16_t>& view) { collect_stats(view); } void operator()(const ArrayView<std::uint32_t>& view) { collect_stats(view); } template <typename T> void operator()(const ArrayView<T>& view) { throw BadArrayTypeException(); } private: FaceSidesInfo& m_stats; template <typename T> void collect_stats(const ArrayView<T>& view) { for (const T n : view) { m_stats.m_face_count++; if (n < 3) m_stats.m_invalid_count++; else if (n == 3) m_stats.m_triangle_count++; else if (n == 4) m_stats.m_quad_count++; else m_stats.m_ngon_count++; m_stats.m_max_face_sides = std::max( m_stats.m_max_face_sides, static_cast<size_t>(n)); } } }; } AABB3f compute_bounding_box(const Array& vertices) { ComputeBBoxVisitor v; apply_visitor(vertices, v); return v.m_bbox; } AABB3f compute_bounding_box(const Array& vertices, const AABB3f& initial_bbox) { ComputeBBoxVisitor v(initial_bbox); apply_visitor(vertices, v); return v.m_bbox; } FaceSidesInfo get_face_sides_info(const Array& verts_per_face) { FaceSidesInfo info; apply_visitor(verts_per_face, FaceSidesInfoVisitor(info)); return info; } }
#include "foundation/array/applyvisitor.h" #include "foundation/array/array.h" #include "foundation/array/arrayview.h" #include "foundation/array/exception.h" #include "foundation/array/meshalgorithm.h" #include <algorithm> #include <cstdint> namespace foundation { namespace { struct ComputeBBoxVisitor { AABB3f m_bbox; ComputeBBoxVisitor() { m_bbox.invalidate(); } explicit ComputeBBoxVisitor(const AABB3f& bbox) : m_bbox(bbox) { } void operator()(const ArrayView<Vector3f>& view) { for (const Vector3f& p : view) m_bbox.insert(p); } template <typename T> void operator()(const ArrayView<T>& view) { throw BadArrayTypeException(); } }; class FaceSidesInfoVisitor { public: explicit FaceSidesInfoVisitor(FaceSidesInfo& stats) : m_stats(stats) { } void operator()(const ArrayView<std::uint8_t>& view) { collect_stats(view); } void operator()(const ArrayView<std::uint16_t>& view) { collect_stats(view); } void operator()(const ArrayView<std::uint32_t>& view) { collect_stats(view); } template <typename T> void operator()(const ArrayView<T>& view) { throw BadArrayTypeException(); } private: FaceSidesInfo& m_stats; template <typename T> void collect_stats(const ArrayView<T>& view) { for (const T n : view) { m_stats.m_face_count++;
m_stats.m_max_face_sides = std::max( m_stats.m_max_face_sides, static_cast<size_t>(n)); } } }; } AABB3f compute_bounding_box(const Array& vertices) { ComputeBBoxVisitor v; apply_visitor(vertices, v); return v.m_bbox; } AABB3f compute_bounding_box(const Array& vertices, const AABB3f& initial_bbox) { ComputeBBoxVisitor v(initial_bbox); apply_visitor(vertices, v); return v.m_bbox; } FaceSidesInfo get_face_sides_info(const Array& verts_per_face) { FaceSidesInfo info; apply_visitor(verts_per_face, FaceSidesInfoVisitor(info)); return info; } }
if (n < 3) m_stats.m_invalid_count++; else if (n == 3) m_stats.m_triangle_count++; else if (n == 4) m_stats.m_quad_count++; else m_stats.m_ngon_count++;
if_condition
[ { "content": "class Matrix<T, N, N>\n\n{\n\n public:\n\n // Types.\n\n typedef T ValueType;\n\n typedef Matrix<T, N, N> MatrixType;\n\n\n\n // Dimensions and number of components.\n\n static const size_t Rows = N;\n\n static const size_t Columns = N;\n\n static const size_t Components = N ...
C++
apps/vdcwizard/dataholder.cpp
yyr/vapor
cdebac81212ffa3f811064bbd7625ffa9089782e
#include <stdlib.h> #include <stdio.h> #include <sstream> #include <iterator> #include <cstdio> #include <QDebug> #include <QString> #include <vapor/WrfVDFcreator.h> #include <vapor/vdfcreate.h> #include <vapor/Copy2VDF.h> #include <vapor/MetadataVDC.h> #include <vapor/WaveCodecIO.h> #include <vapor/DCReader.h> #include <vapor/DCReaderGRIB.h> #include <vapor/DCReaderMOM.h> #include <vapor/DCReaderROMS.h> #include <vapor/DCReaderWRF.h> #include <vapor/WrfVDCcreator.h> #include "dataholder.h" using namespace VAPoR; vector<const char*> errors; void ErrMsgCBHandler(const char* error, int){ errors.push_back(error); } vector<const char*> DataHolder::getErrors() { return errors; } void DataHolder::clearErrors() { errors.clear(); } DataHolder::DataHolder(){ MyBase::SetErrMsgCB(ErrMsgCBHandler); VDFstartTime = "0"; PDstartTime = "0"; reader = NULL; ncdfFilesChanged = true; vdfSettingsChanged = true; vdcSettingsChanged = true; } DataHolder::~DataHolder(){ } void DataHolder::deleteReader() { if (reader) delete reader; reader = NULL; } void DataHolder::getExtents(){ reader->GetLatLonExtents(0,lonExtents,latExtents); for (size_t i=1;i<atoi(VDFnumTS.c_str());i++){ double lonBuffer[2]; double latBuffer[2]; reader->GetLatLonExtents(i,lonBuffer,latBuffer); if (latBuffer[0]<latExtents[0]) latExtents[0]=latBuffer[0]; if (latBuffer[1]>latExtents[1]) latExtents[1]=latBuffer[1]; if (lonBuffer[0]<lonExtents[0]) lonExtents[0]=lonBuffer[0]; if (lonBuffer[1]>lonExtents[1]) lonExtents[1]=lonBuffer[1]; } } void DataHolder::setVDFstartTime(string startTime) { VDFstartTime = startTime; vdfSettingsChanged = true; } void DataHolder::setVDFnumTS(string numTS) { VDFnumTS = numTS; vdfSettingsChanged = true; } void DataHolder::setVDFDisplayedVars(vector<string> selectedVars) { VDFDisplayedVars = selectedVars; vdfSettingsChanged = true; } void DataHolder::setVDFSelectedVars(vector<string> selectedVars) { if (VDFSelectedVars != selectedVars) vdfSettingsChanged = true; VDFSelectedVars = selectedVars; } void DataHolder::addVDFDisplayedVar(string var) { VDFDisplayedVars.push_back(var); vdfSettingsChanged = true; } void DataHolder::addVDFSelectedVar(string var) { VDFSelectedVars.push_back(var); vdfSettingsChanged = true; } void DataHolder::deleteVDFSelectedVar(string var) { for (int i=0;i<VDFSelectedVars.size();i++) { if (VDFSelectedVars[i] == var) VDFSelectedVars.erase(VDFSelectedVars.begin()+i); } vdfSettingsChanged = true; } void DataHolder::clearVDFSelectedVars() { VDFSelectedVars.clear(); vdfSettingsChanged = true; } int DataHolder::createReader() { if (reader==NULL){ if (fileType == "ROMS") reader = new DCReaderROMS(dataFiles); else if (fileType == "CAM") reader = new DCReaderROMS(dataFiles); else if (fileType == "GRIB") reader = new DCReaderGRIB(dataFiles); else if (fileType == "WRF") reader = new DCReaderWRF(dataFiles); else reader = new DCReaderMOM(dataFiles); if (MyBase::GetErrCode()!=0) return 1; std::stringstream strstream; strstream << reader->GetNumTimeSteps(); strstream >> VDFnumTS; setPDnumTS(VDFnumTS); ncdfVars = reader->GetVariableNames(); std::sort(ncdfVars.begin(),ncdfVars.end()); if (MyBase::GetErrCode()!=0) return 1; } return 0; } void DataHolder::findPopDataVars() { VDFIOBase *vdfio = NULL; WaveCodecIO *wcwriter = NULL; MetadataVDC metadata(getPDinputVDFfile()); wcwriter = new WaveCodecIO(metadata,1); vdfio = wcwriter; vector<string> emptyVars; vector<string> outVars; launcher2VDF.GetVariables(vdfio, reader, emptyVars, outVars); std::sort(outVars.begin(),outVars.end()); setPDDisplayedVars(outVars); delete wcwriter; } string DataHolder::getCreateVDFcmd() { vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("romsvdfcreate"); else if (getFileType() == "CAM") argv.push_back("camvdfcreate"); else if (getFileType() == "WRF") argv.push_back("wrfvdfcreate"); else if (getFileType() == "GRIB") argv.push_back("gribvdfcreate"); else argv.push_back("momvdfcreate"); argv.push_back("-quiet"); if (getFileType()=="WRF") argv.push_back("-vdc2"); if (VDFSBFactor != "") { argv.push_back("-bs"); argv.push_back(VDFSBFactor); } if (VDFcomment != "") { argv.push_back("-comment"); argv.push_back(VDFcomment); } if (VDFcrList != "") { argv.push_back("-cratios"); argv.push_back(VDFcrList); } if (VDFPeriodicity != "") { argv.push_back("-periodic"); argv.push_back(VDFPeriodicity); } if (VDFSelectedVars.size() != 0) { argv.push_back("-vars"); string stringVars; for(vector<string>::iterator it = VDFSelectedVars.begin(); it != VDFSelectedVars.end(); ++it) { if(it != VDFSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); } if (VDFfileName != "") { argv.push_back(VDFfileName); } std::ostringstream imploded; const char* const delim = " "; std::copy(argv.begin(), argv.end(),std::ostream_iterator<string>(imploded,delim)); return imploded.str(); } string DataHolder::getPopDataCmd() { vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); } if (getFileType() != "GRIB") { argv.push_back("-numts"); argv.push_back(PDnumTS); argv.push_back("-startts"); argv.push_back(PDstartTime); } if (PDSelectedVars.size() != 0) { argv.push_back("-vars"); if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = PDSelectedVars.begin(); it != PDSelectedVars.end(); ++it) { if(it != PDSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); } if (getFileType()=="WRF"){ argv.push_back(PDinputVDFfile); } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); } if (getFileType() != "WRF"){ argv.push_back(PDinputVDFfile); } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } std::ostringstream imploded; const char* const delim = " "; std::copy(argv.begin(), argv.end(), std::ostream_iterator<string>(imploded,delim)); return imploded.str(); } int DataHolder::VDFCreate() { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("romsvdfcreate"); else if (getFileType() == "CAM") argv.push_back("camvdfcreate"); else if (getFileType() == "GRIB") argv.push_back("gribvdfcreate"); else if (getFileType() == "WRF") argv.push_back("wrfvdfcreate"); else argv.push_back("momvdfcreate"); argv.push_back("-quiet"); if (getFileType() == "WRF") { argv.push_back("-vdc2"); argc++; } if (VDFSBFactor != "") { argv.push_back("-bs"); argv.push_back(VDFSBFactor); argc+=2; } if (VDFcomment != "") { argv.push_back("-comment"); argv.push_back(VDFcomment); argc+=2; } if (VDFcrList != "") { argv.push_back("-cratios"); argv.push_back(VDFcrList); argc+=2; } if (VDFPeriodicity != "") { argv.push_back("-periodic"); argv.push_back(VDFPeriodicity); argc+=2; } if (VDFSelectedVars.size() != 0) { argv.push_back("-vars"); argc++; if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = VDFSelectedVars.begin(); it != VDFSelectedVars.end(); ++it) { if(it != VDFSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } if (VDFfileName != "") { argv.push_back(VDFfileName); argc++; } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } if (getFileType()=="WRF") { wrfvdfcreate launcherWrfVdfCreate; int rc = launcherWrfVdfCreate.launchVdfCreate(argc,args); return rc; } else return launcherVdfCreate.launchVdfCreate(argc,args,getFileType()); } int DataHolder::run2VDFcomplete() { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); argc+=2; } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); argc+=2; } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); argc+=2; } if (getFileType() != "GRIB") { if (PDnumTS != "") { argv.push_back("-numts"); argv.push_back(PDnumTS); argc+=2; } if (PDstartTime != "") { argv.push_back("-startts"); argv.push_back(PDstartTime); argc+=2; } } if (PDSelectedVars.size() != 0) { argv.push_back("-vars"); argc++; if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = PDSelectedVars.begin(); it != PDSelectedVars.end(); ++it) { if(it != PDSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } argv.push_back(PDinputVDFfile); argc++; char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } return launcher2VDF.launch2vdf(argc, args, getFileType(), reader); } int DataHolder::run2VDFincremental(string start, string var) { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); argc+=2; } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); argc+=2; } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); argc+=2; } if (getFileType() != "GRIB") { argv.push_back("-numts"); argv.push_back("1"); argc+=2; argv.push_back("-startts"); argv.push_back(start); argc+=2; } argv.push_back("-vars"); argc++; argv.push_back(var); argc++; if (getFileType()=="WRF"){ argv.push_back(PDinputVDFfile); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } if (getFileType() != "WRF"){ argv.push_back(PDinputVDFfile); argc++; } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } int rc; if (getFileType()=="WRF") { rc = w2v.launchWrf2Vdf(argc, args, (DCReaderWRF*) reader); } else { rc = launcher2VDF.launch2vdf(argc, args, getFileType(), reader); } if (args) delete [] args; return rc; } void DataHolder::purgeObjects() { launcher2VDF.deleteObjects(); w2v.deleteObjects(); }
#include <stdlib.h> #include <stdio.h> #include <sstream> #include <iterator> #include <cstdio> #include <QDebug> #include <QString> #include <vapor/WrfVDFcreator.h> #include <vapor/vdfcreate.h> #include <vapor/Copy2VDF.h> #include <vapor/MetadataVDC.h> #include <vapor/WaveCodecIO.h> #include <vapor/DCReader.h> #include <vapor/DCReaderGRIB.h> #include <vapor/DCReaderMOM.h> #include <vapor/DCReaderROMS.h> #include <vapor/DCReaderWRF.h> #include <vapor/WrfVDCcreator.h> #include "dataholder.h" using namespace VAPoR; vector<const char*> errors; void ErrMsgCBHandler(const char* error, int){ errors.push_back(error); } vector<const char*> DataHolder::getErrors() { return errors; } void DataHolder::clearErrors() { errors.clear(); } DataHolder::DataHolder(){ MyBase::SetErrMsgCB(ErrMsgCBHandler); VDFstartTime = "0"; PDstartTime = "0"; reader = NULL; ncdfFilesChanged = true; vdfSettingsChanged = true; vdcSettingsChanged = true; } DataHolder::~DataHolder(){ } void DataHolder::deleteReader() { if (reader) delete reader; reader = NULL; } void DataHolder::getExtents(){ reader->GetLatLonExtents(0,lonExtents,latExtents); for (size_t i=1;i<atoi(VDFnumTS.c_str());i++){ double lonBuffer[2]; double latBuffer[2]; reader->GetLatLonExtents(i,lonBuffer,latBuffer); if (latBuffer[0]<latExtents[0]) latExtents[0]=latBuffer[0]; if (latBuffer[1]>latExtents[1]) latExtents[1]=latBuffer[1]; if (lonBuffer[0]<lonExtents[0]) lonExtents[0]=lonBuffer[0]; if (lonBuffer[1]>lonExtents[1]) lonExtents[1]=lonBuffer[1]; } } void DataHolder::setVDFstartTime(string startTime) { VDFstartTime = startTime; vdfSettingsChanged = true; } void DataHolder::setVDFnumTS(string numTS) { VDFnumTS = numTS; vdfSettingsChanged = true; } void DataHolder::setVDFDisplayedVars(vector<string> selectedVars) { VDFDisplayedVars = selectedVars; vdfSettingsChanged = true; } void DataHolder::setVDFSelectedVars(vector<string> selectedVars) { if (VDFSelectedVars != selectedVars) vdfSettingsChanged = true; VDFSelectedVars = selectedVars; } void DataHolder::addVDFDisplayedVar(string var) { VDFDisplayedVars.push_back(var); vdfSettingsChanged = true; } void DataHolder::addVDFSelectedVar(string var) { VDFSelectedVars.push_back(var); vdfSettingsChanged = true; } void DataHolder::deleteVDFSelectedVar(string var) { for (int i=0;i<VDFSelectedVars.size();i++) { if (VDFSelectedVars[i] == var) VDFSelectedVars.erase(VDFSelectedVars.begin()+i); } vdfSettingsChanged = true; } void DataHolder::clearVDFSelectedVars() { VDFSelectedVars.clear(); vdfSettingsChanged = true; } int DataHolder::createReader() { if (reader==NULL){ if (fileType == "ROMS") reader = new DCReaderROMS(dataFiles); else if (fileType == "CAM") reader = new DCReaderROMS(dataFiles); else if (fileType == "GRIB") reader = new DCReaderGRIB(dataFiles); else if (fileType == "WRF") reader = new DCReaderWRF(dataFiles); else reader = new DCReaderMOM(dataFiles); if (MyBase::GetErrCode()!=0) return 1; std::stringstream strstream; strstream << reader->GetNumTimeSteps(); strstream >> VDFnumTS; setPDnumTS(VDFnumTS); ncdfVars = reader->GetVariableNames(); std::sort(ncdfVars.begin(),ncdfVars.end()); if (MyBase::GetErrCode()!=0) return 1; } return 0; } void DataHolder::findPopDataVars() { VDFIOBase *vdfio = NULL; WaveCodecIO *wcwriter = NULL; MetadataVDC metadata(getPDinputVDFfile()); wcwriter = new WaveCodecIO(metadata,1); vdfio = wcwriter; vector<string> emptyVars; vector<string> outVars; launcher2VDF.GetVariables(vdfio, reader, emptyVars, outVars); std::sort(outVars.begin(),outVars.end()); setPDDisplayedVars(outVars); delete wcwriter; } string DataHolder::getCreateVDFcmd() { vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("romsvdfcreate"); else if (getFileType() == "CAM") argv.push_back("camvdfcreate"); else if (getFileType() == "WRF") argv.push_back("wrfvdfcreate"); else if (getFileType() == "GRIB") argv.push_back("gribvdfcreate"); else argv.push_back("momvdfcreate"); argv.push_back("-quiet"); if (getFileTyp
string DataHolder::getPopDataCmd() { vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); } if (getFileType() != "GRIB") { argv.push_back("-numts"); argv.push_back(PDnumTS); argv.push_back("-startts"); argv.push_back(PDstartTime); } if (PDSelectedVars.size() != 0) { argv.push_back("-vars"); if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = PDSelectedVars.begin(); it != PDSelectedVars.end(); ++it) { if(it != PDSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); } if (getFileType()=="WRF"){ argv.push_back(PDinputVDFfile); } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); } if (getFileType() != "WRF"){ argv.push_back(PDinputVDFfile); } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } std::ostringstream imploded; const char* const delim = " "; std::copy(argv.begin(), argv.end(), std::ostream_iterator<string>(imploded,delim)); return imploded.str(); } int DataHolder::VDFCreate() { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("romsvdfcreate"); else if (getFileType() == "CAM") argv.push_back("camvdfcreate"); else if (getFileType() == "GRIB") argv.push_back("gribvdfcreate"); else if (getFileType() == "WRF") argv.push_back("wrfvdfcreate"); else argv.push_back("momvdfcreate"); argv.push_back("-quiet"); if (getFileType() == "WRF") { argv.push_back("-vdc2"); argc++; } if (VDFSBFactor != "") { argv.push_back("-bs"); argv.push_back(VDFSBFactor); argc+=2; } if (VDFcomment != "") { argv.push_back("-comment"); argv.push_back(VDFcomment); argc+=2; } if (VDFcrList != "") { argv.push_back("-cratios"); argv.push_back(VDFcrList); argc+=2; } if (VDFPeriodicity != "") { argv.push_back("-periodic"); argv.push_back(VDFPeriodicity); argc+=2; } if (VDFSelectedVars.size() != 0) { argv.push_back("-vars"); argc++; if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = VDFSelectedVars.begin(); it != VDFSelectedVars.end(); ++it) { if(it != VDFSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } if (VDFfileName != "") { argv.push_back(VDFfileName); argc++; } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } if (getFileType()=="WRF") { wrfvdfcreate launcherWrfVdfCreate; int rc = launcherWrfVdfCreate.launchVdfCreate(argc,args); return rc; } else return launcherVdfCreate.launchVdfCreate(argc,args,getFileType()); } int DataHolder::run2VDFcomplete() { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); argc+=2; } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); argc+=2; } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); argc+=2; } if (getFileType() != "GRIB") { if (PDnumTS != "") { argv.push_back("-numts"); argv.push_back(PDnumTS); argc+=2; } if (PDstartTime != "") { argv.push_back("-startts"); argv.push_back(PDstartTime); argc+=2; } } if (PDSelectedVars.size() != 0) { argv.push_back("-vars"); argc++; if (getFileType()!="MOM"){ if (std::find(PDSelectedVars.begin(), PDSelectedVars.end(), "ELEVATION") == PDSelectedVars.end()) { PDSelectedVars.push_back("ELEVATION"); } } string stringVars; for(vector<string>::iterator it = PDSelectedVars.begin(); it != PDSelectedVars.end(); ++it) { if(it != PDSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } argv.push_back(PDinputVDFfile); argc++; char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } return launcher2VDF.launch2vdf(argc, args, getFileType(), reader); } int DataHolder::run2VDFincremental(string start, string var) { int argc = 2; vector<std::string> argv; if (getFileType() == "ROMS") argv.push_back("roms2vdf"); else if (getFileType() == "CAM") argv.push_back("cam2vdf"); else if (getFileType() == "GRIB") argv.push_back("grib2vdf"); else if (getFileType() == "WRF") argv.push_back("wrf2vdf"); else argv.push_back("mom2vdf"); argv.push_back("-quiet"); if (PDrefinement != "") { argv.push_back("-level"); argv.push_back(PDrefinement); argc+=2; } if (PDcompression != "") { argv.push_back("-lod"); argv.push_back(PDcompression); argc+=2; } if (PDnumThreads != "") { argv.push_back("-nthreads"); argv.push_back(PDnumThreads); argc+=2; } if (getFileType() != "GRIB") { argv.push_back("-numts"); argv.push_back("1"); argc+=2; argv.push_back("-startts"); argv.push_back(start); argc+=2; } argv.push_back("-vars"); argc++; argv.push_back(var); argc++; if (getFileType()=="WRF"){ argv.push_back(PDinputVDFfile); argc++; } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); argc++; } if (getFileType() != "WRF"){ argv.push_back(PDinputVDFfile); argc++; } char** args = new char*[ argv.size() + 1 ]; for(size_t a=0; a<argv.size(); a++) { args[a] = strdup(argv[a].c_str()); } int rc; if (getFileType()=="WRF") { rc = w2v.launchWrf2Vdf(argc, args, (DCReaderWRF*) reader); } else { rc = launcher2VDF.launch2vdf(argc, args, getFileType(), reader); } if (args) delete [] args; return rc; } void DataHolder::purgeObjects() { launcher2VDF.deleteObjects(); w2v.deleteObjects(); }
e()=="WRF") argv.push_back("-vdc2"); if (VDFSBFactor != "") { argv.push_back("-bs"); argv.push_back(VDFSBFactor); } if (VDFcomment != "") { argv.push_back("-comment"); argv.push_back(VDFcomment); } if (VDFcrList != "") { argv.push_back("-cratios"); argv.push_back(VDFcrList); } if (VDFPeriodicity != "") { argv.push_back("-periodic"); argv.push_back(VDFPeriodicity); } if (VDFSelectedVars.size() != 0) { argv.push_back("-vars"); string stringVars; for(vector<string>::iterator it = VDFSelectedVars.begin(); it != VDFSelectedVars.end(); ++it) { if(it != VDFSelectedVars.begin()) stringVars += ":"; stringVars += *it; } argv.push_back(stringVars); } for (int i=0;i<dataFiles.size();i++){ argv.push_back(dataFiles.at(i)); } if (VDFfileName != "") { argv.push_back(VDFfileName); } std::ostringstream imploded; const char* const delim = " "; std::copy(argv.begin(), argv.end(),std::ostream_iterator<string>(imploded,delim)); return imploded.str(); }
function_block-function_prefixed
[ { "content": " class DerivedVarElevation : public NetCDFCollection::DerivedVar {\n\n public:\n\n DerivedVarElevation(\n\n NetCDFCollection *ncdfcf, float grav\n\n );\n\n virtual ~DerivedVarElevation();\n\n\n\n virtual int Open(size_t ts);\n\n virtual int ReadSlice(float *slice, int );\n\n virtual int R...
C++
TinySTL/set.hpp
syn1w/TinySTL
04961c8fcec560d23cb99d049d44ff1b88113118
 #pragma once #include "rbtree.hpp" namespace tiny_stl { template <typename Key, typename Compare = tiny_stl::less<Key>, typename Alloc = tiny_stl::allocator<Key>> class set : public RBTree<Key, Compare, Alloc, false> { public: using allocator_type = Alloc; private: using Base = RBTree<Key, Compare, allocator_type, false>; using AlTraits = allocator_traits<allocator_type>; using AlNode = typename Base::AlNode; using AlNodeTraits = typename Base::AlNodeTraits; public: using key_type = Key; using value_type = Key; using size_type = typename Alloc::size_type; using difference_type = typename Alloc::difference_type; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AlTraits::pointer; using const_pointer = typename AlTraits::const_pointer; using iterator = typename Base::iterator; using const_iterator = typename Base::const_iterator; using reverse_iterator = typename Base::reverse_iterator; using const_reverse_iterator = typename Base::const_reverse_iterator; public: set() : set(Compare()) { } explicit set(const Compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { } explicit set(const Alloc& alloc) : Base(key_compare(), alloc) { } template <typename InIter> set(InIter first, InIter last, const key_compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_unique(first, last); } template <typename InIter> set(InIter first, InIter last, const Alloc& alloc) : Base(key_compare(), alloc) { this->insert_unique(first, last); } set(const set& rhs) : Base(rhs, AlTraits::select_on_container_copy_construction( rhs.get_allocator())) { } set(const set& rhs, const Alloc& alloc) : Base(rhs, alloc) { } set(set&& rhs) : Base(tiny_stl::move(rhs)) { } set(set&& rhs, const Alloc& alloc) : Base(tiny_stl::move(rhs), alloc) { } set(std::initializer_list<value_type> ilist, const Compare& cmp = Compare(), const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_unique(ilist.begin(), ilist.end()); } set(std::initializer_list<value_type> ilist, const Alloc& alloc) : set(ilist, Compare(), alloc) { } set& operator=(const set& rhs) { Base::operator=(rhs); return *this; } set& operator=(set&& rhs) { Base::operator=(tiny_stl::move(rhs)); return *this; } set& operator=(std::initializer_list<value_type> ilist) { set tmp(ilist); this->swap(tmp); return *this; } pair<iterator, bool> insert(const value_type& val) { return this->insert_unique(val); } pair<iterator, bool> insert(value_type&& val) { return this->insert_unique(tiny_stl::move(val)); } template <typename InIter> void insert(InIter first, InIter last) { this->insert_unique(first, last); } void insert(std::initializer_list<value_type> ilist) { this->insert_unique(ilist.begin(), ilist.end()); } template <typename... Args> pair<iterator, bool> emplace(Args&&... args) { return this->emplace_unique(tiny_stl::forward<Args>(args)...); } void swap(set& rhs) { Base::swap(rhs); } key_compare key_comp() const { return key_compare{}; } value_compare value_comp() const { return value_compare{}; } }; template <typename Key, typename Compare, typename Alloc> inline void swap(set<Key, Compare, Alloc>& lhs, set<Key, Compare, Alloc>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } template <typename Key, typename Compare = tiny_stl::less<Key>, typename Alloc = tiny_stl::allocator<Key>> class multiset : public RBTree<Key, Compare, Alloc, false> { public: using allocator_type = Alloc; private: using Base = RBTree<Key, Compare, allocator_type, false>; using AlTraits = allocator_traits<allocator_type>; using AlNode = typename Base::AlNode; using AlNodeTraits = typename Base::AlNodeTraits; public: using key_type = Key; using value_type = Key; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AlTraits::pointer; using const_pointer = typename AlTraits::const_pointer; using iterator = typename Base::iterator; using const_iterator = typename Base::const_iterator; using reverse_iterator = typename Base::reverse_iterator; using const_reverse_iterator = typename Base::const_reverse_iterator; public: multiset() : multiset(Compare()) { } explicit multiset(const Compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { } explicit multiset(const Alloc& alloc) : Base(key_compare(), alloc) { } template <typename InIter> multiset(InIter first, InIter last, const key_compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_equal(first, last); } template <typename InIter> multiset(InIter first, InIter last, const Alloc& alloc) : Base(key_compare(), alloc) { this->insert_equal(first, last); } multiset(const multiset& rhs) : Base(rhs, AlTraits::select_on_container_copy_construction( rhs.get_allocator())) { } multiset(const multiset& rhs, const Alloc& alloc) : Base(rhs, alloc) { } multiset(multiset&& rhs) : Base(tiny_stl::move(rhs)) { } multiset(multiset&& rhs, const Alloc& alloc) : Base(tiny_stl::move(rhs), alloc) { } multiset(std::initializer_list<value_type> ilist, const Compare& cmp = Compare(), const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_equal(ilist.begin(), ilist.end()); } multiset(std::initializer_list<value_type> ilist, const Alloc& alloc) : multiset(ilist, Compare(), alloc) { } multiset& operator=(const multiset& rhs) { Base::operator=(rhs); return *this; } multiset& operator=(multiset&& rhs) { Base::operator=(tiny_stl::move(rhs)); return *this; } multiset& operator=(std::initializer_list<value_type> ilist) { multiset tmp(ilist); this->swap(tmp); return *this; } iterator insert(const value_type& val) { return this->insert_equal(val); } iterator insert(value_type&& val) { return this->insert_equal(tiny_stl::move(val)); } template <typename InIter> void insert(InIter first, InIter last) { this->insert_equal(first, last); } void insert(std::initializer_list<value_type> ilist) { this->insert_equal(ilist.begin(), ilist.end()); } template <typename... Args> iterator emplace(Args&&... args) { return this->insert_equal(tiny_stl::forward<Args>(args)...); } void swap(multiset& rhs) { Base::swap(rhs); } key_compare key_comp() const { return key_compare{}; } value_compare value_comp() const { return value_compare{}; } }; template <typename Key, typename Compare, typename Alloc> inline void swap(multiset<Key, Compare, Alloc>& lhs, multiset<Key, Compare, Alloc>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } }
 #pragma once #include "rbtree.hpp" namespace tiny_stl { template <typename Key, typename Compare = tiny_stl::less<Key>, typename Alloc = tiny_stl::allocator<Key>> class set : public RBTree<Key, Compare, Alloc, false> { public: using allocator_type = Alloc; private: using Base = RBTree<Key, Compare, allocator_type, false>; using AlTraits = allocator_traits<allocator_type>; using AlNode = typename Base::AlNode; using AlNodeTraits = typename Base::AlNodeTraits; public: using key_type = Key; using value_type = Key; using size_type = typename Alloc::size_type; using difference_type = typename Alloc::difference_type; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AlTraits::pointer; using const_pointer = typename AlTraits::const_pointer; using iterator = typename Base::iterator; using const_iterator = typename Base::const_iterator; using reverse_iterator = typename Base::reverse_iterator; using const_reverse_iterator = typename Base::const_reverse_iterator; public: set() : set(Compare()) { } explicit set(const Compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { } explicit set(const Alloc& alloc) : Base(key_compare(), alloc) { } template <typename InIter> set(InIter first, InIter last, const key_compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_unique(first, last); } template <typename InIter> set(InIter first, InIter last, const Alloc& alloc) : Base(key_compare(), alloc) { this->insert_unique(first, last); } set(const set& rhs) : Base(rhs, AlTraits::select_on_container_copy_construction( rhs.get_allocator())) { } set(const set& rhs, const Alloc& alloc) : Base(rhs, alloc) { } set(set&& rhs) : Base(tiny_stl::move(rhs)) { } set(set&& rhs, const Alloc& alloc) : Base(tiny_stl::move(rhs), alloc) { } set(std::initializer_list<value_type> ilist, const Compare& cmp = Compare(), const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_unique(ilist.begin(), ilist.end()); } set(std::initializer_list<value_type> ilist, const Alloc& alloc) : set(ilist, Compare(), alloc) { } set& operator=(const set& rhs) { Base::operator=(rhs); return *this; } set& operator=(set&& rhs) { Base::operator=(tiny_stl::move(rhs)); return *this; } set& operator=(std::initializer_list<value_type> ilist) { set tmp(ilist); this->swap(tmp); return *this; } pair<iterator, bool> insert(const value_type& val) { return this->insert_unique(val); } pair<iterator, bool> insert(value_type&& val) { return this->insert_unique(tiny_stl::move(val)); } template <typename InIter> void insert(InIter first, InIter last) { this->insert_unique(first, last); } void insert(std::initializer_list<value_type> ilist) { this->insert_unique(ilist.begin(), ilist.end()); } template <typename... Args> pair<iterator, bool> emplace(Args&&... args) { return this->emplace_unique(tiny_stl::forward<Args>(args)...); } void swap(set& rhs) { Base::swap(rhs); } key_compare key_comp() const { return key_compare{}; } value_compare value_comp() const { return value_compare{}; } }; template <typename Key, typename Compare, typename Alloc> inline void swap(set<Key, Compare, Alloc>& lhs, set<Key, Compare, Alloc>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } template <typename Key, typename Compare = tiny_stl::less<Key>, typename Alloc = tiny_st
ltiset<Key, Compare, Alloc>& rhs) noexcept(noexcept(lhs.swap(rhs))) { lhs.swap(rhs); } }
l::allocator<Key>> class multiset : public RBTree<Key, Compare, Alloc, false> { public: using allocator_type = Alloc; private: using Base = RBTree<Key, Compare, allocator_type, false>; using AlTraits = allocator_traits<allocator_type>; using AlNode = typename Base::AlNode; using AlNodeTraits = typename Base::AlNodeTraits; public: using key_type = Key; using value_type = Key; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using key_compare = Compare; using value_compare = Compare; using reference = value_type&; using const_reference = const value_type&; using pointer = typename AlTraits::pointer; using const_pointer = typename AlTraits::const_pointer; using iterator = typename Base::iterator; using const_iterator = typename Base::const_iterator; using reverse_iterator = typename Base::reverse_iterator; using const_reverse_iterator = typename Base::const_reverse_iterator; public: multiset() : multiset(Compare()) { } explicit multiset(const Compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { } explicit multiset(const Alloc& alloc) : Base(key_compare(), alloc) { } template <typename InIter> multiset(InIter first, InIter last, const key_compare& cmp, const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_equal(first, last); } template <typename InIter> multiset(InIter first, InIter last, const Alloc& alloc) : Base(key_compare(), alloc) { this->insert_equal(first, last); } multiset(const multiset& rhs) : Base(rhs, AlTraits::select_on_container_copy_construction( rhs.get_allocator())) { } multiset(const multiset& rhs, const Alloc& alloc) : Base(rhs, alloc) { } multiset(multiset&& rhs) : Base(tiny_stl::move(rhs)) { } multiset(multiset&& rhs, const Alloc& alloc) : Base(tiny_stl::move(rhs), alloc) { } multiset(std::initializer_list<value_type> ilist, const Compare& cmp = Compare(), const Alloc& alloc = Alloc()) : Base(cmp, alloc) { this->insert_equal(ilist.begin(), ilist.end()); } multiset(std::initializer_list<value_type> ilist, const Alloc& alloc) : multiset(ilist, Compare(), alloc) { } multiset& operator=(const multiset& rhs) { Base::operator=(rhs); return *this; } multiset& operator=(multiset&& rhs) { Base::operator=(tiny_stl::move(rhs)); return *this; } multiset& operator=(std::initializer_list<value_type> ilist) { multiset tmp(ilist); this->swap(tmp); return *this; } iterator insert(const value_type& val) { return this->insert_equal(val); } iterator insert(value_type&& val) { return this->insert_equal(tiny_stl::move(val)); } template <typename InIter> void insert(InIter first, InIter last) { this->insert_equal(first, last); } void insert(std::initializer_list<value_type> ilist) { this->insert_equal(ilist.begin(), ilist.end()); } template <typename... Args> iterator emplace(Args&&... args) { return this->insert_equal(tiny_stl::forward<Args>(args)...); } void swap(multiset& rhs) { Base::swap(rhs); } key_compare key_comp() const { return key_compare{}; } value_compare value_comp() const { return value_compare{}; } }; template <typename Key, typename Compare, typename Alloc> inline void swap(multiset<Key, Compare, Alloc>& lhs, mu
random
[ { "content": "class unordered_set : public HashTable<Key, Hash, KeyEqual, Alloc, false> {\n\npublic:\n\n using allocator_type = Alloc;\n\nprivate:\n\n using Base = HashTable<Key, Hash, KeyEqual, Alloc, false>;\n\n using AlTraits = allocator_traits<allocator_type>;\n\n\n\npublic:\n\n using key_type =...
C++
parallel/SolverConfiguration.cc
jiriklepl/glucose-syrup-4.1
3a444d2cde0fbb1538e7965410db67db27940c09
#include "glucose/parallel/MultiSolvers.h" #include "glucose/core/Solver.h" #include "glucose/parallel/SolverConfiguration.h" using namespace Glucose; void SolverConfiguration::configure(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) { ms->solvers[i]->randomizeFirstDescent = true; ms->solvers[i]->adaptStrategies = (i%2==0); ms->solvers[i]->forceUnsatOnNewDescent = (i%4==0); } if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT15Adapt(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) { ms->solvers[i]->randomizeFirstDescent = true; ms->solvers[i]->adaptStrategies = (i%2==0); } if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT15Default(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) ms->solvers[i]->randomizeFirstDescent = true; if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT14(MultiSolvers *ms, int nbsolvers) { if (nbsolvers < 2 ) return; ms->solvers[1]->var_decay = 0.94; ms->solvers[1]->max_var_decay = 0.96; ms->solvers[1]->firstReduceDB=600; if (nbsolvers < 3 ) return; ms->solvers[2]->var_decay = 0.90; ms->solvers[2]->max_var_decay = 0.97; ms->solvers[2]->firstReduceDB=500; if (nbsolvers < 4 ) return; ms->solvers[3]->var_decay = 0.85; ms->solvers[3]->max_var_decay = 0.93; ms->solvers[3]->firstReduceDB=400; if (nbsolvers < 5 ) return; ms->solvers[4]->var_decay = 0.95; ms->solvers[4]->max_var_decay = 0.95; ms->solvers[4]->firstReduceDB=4000; ms->solvers[4]->lbdQueue.growTo(100); ms->solvers[4]->sizeLBDQueue = 100; ms->solvers[4]->K = 0.7; ms->solvers[4]->incReduceDB = 500; if (nbsolvers < 6 ) return; ms->solvers[5]->var_decay = 0.93; ms->solvers[5]->max_var_decay = 0.96; ms->solvers[5]->firstReduceDB=100; ms->solvers[5]->incReduceDB = 500; if (nbsolvers < 7 ) return; ms->solvers[6]->var_decay = 0.75; ms->solvers[6]->max_var_decay = 0.94; ms->solvers[6]->firstReduceDB=2000; if (nbsolvers < 8 ) return; ms->solvers[7]->var_decay = 0.94; ms->solvers[7]->max_var_decay = 0.96; ms->solvers[7]->firstReduceDB=800; if (nbsolvers < 9) return; if (nbsolvers < 10 ) return; if (nbsolvers < 11 ) return; double noisevar_decay = 0.005; int noiseReduceDB = 50; for (int i=10;i<nbsolvers;i++) { ms->solvers[i]-> var_decay = ms->solvers[i%8]->var_decay; ms->solvers[i]-> max_var_decay = ms->solvers[i%8]->max_var_decay; ms->solvers[i]-> firstReduceDB= ms->solvers[i%8]->firstReduceDB; ms->solvers[i]->var_decay += noisevar_decay; ms->solvers[i]->firstReduceDB+=noiseReduceDB; if ((i+1) % 8 == 0) { noisevar_decay += 0.006; noiseReduceDB += 25; } } }
#include "glucose/parallel/MultiSolvers.h" #include "glucose/core/Solver.h" #include "glucose/parallel/SolverConfiguration.h" using namespace Glucose; void SolverConfiguration::configure(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) { ms->solvers[i]->randomizeFirstDescent = true; ms->solvers[i]->adaptStrategies = (i%2==0); ms->solvers[i]->forceUnsatOnNewDescent = (i%4==0); } if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT15Adapt(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) { ms->solvers[i]->randomizeFirstDescent = true; ms->solvers[i]->adaptStrategies = (i%2==0); } if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT15Default(MultiSolvers *ms, int nbsolvers) { for(int i = 1;i<nbsolvers;i++) ms->solvers[i]->randomizeFirstDescent = true; if (nbsolvers > 8) { for(int i=0;i<nbsolvers;i++) { ms->solvers[i]->goodlimitlbd = 5; ms->solvers[i]->goodlimitsize = 15; } } } void SolverConfiguration::configureSAT14(MultiSolvers *ms, int nbsolvers) { if (nbsolvers < 2 ) return; ms->solvers[1]->var_decay = 0.94; ms->solvers[1]->max_var_decay = 0.96; ms->solvers[1]->firstReduceDB=600; if (nbsolvers < 3 ) return; ms->solvers[2]->var_decay = 0.90; ms->solvers[2]->max_var_decay = 0.97; ms->solvers[2]->firstReduceDB=500; if (nbsolvers < 4 ) return; ms->solvers[3]->var_decay = 0.85; ms->solvers[3]->max_var_decay = 0.93; ms->solvers[3]->firstReduceDB=400; if (nbsolvers < 5 ) return; ms->solvers[4]->var_decay = 0.95; ms->solvers[4]->max_var_decay = 0.95; ms->solvers[4]->firstReduceDB=4000; ms->solvers[4]->lbdQueue.growTo(100); ms->solvers[4]->sizeLBDQueue = 100; ms->solvers[4]->K = 0.7; ms->solvers[4]->incReduceDB = 500; if (nbsolvers < 6 ) return; ms->solvers[5]->var_decay = 0.93; ms->solvers[5]->max_var_decay = 0.96; ms->solvers[5]->firstReduceDB=100; ms->solvers[5]->incReduceDB = 500; if (nbsolvers < 7 ) return; ms->solvers[6]->var_decay = 0.75; ms->solvers[6]->max_var_decay = 0.94; ms->solvers[6]->firstReduceDB=2000; if (nbsolvers < 8 ) return; ms->solvers[7]->var_decay = 0.94; ms->solvers[7]->max_var_decay = 0.96; ms->solvers[7]->firstReduceDB=800; if (nbsolvers < 9) return; if (nbsolvers < 10 ) return;
if (nbsolvers < 11 ) return; double noisevar_decay = 0.005; int noiseReduceDB = 50; for (int i=10;i<nbsolvers;i++) { ms->solvers[i]-> var_decay = ms->solvers[i%8]->var_decay; ms->solvers[i]-> max_var_decay = ms->solvers[i%8]->max_var_decay; ms->solvers[i]-> firstReduceDB= ms->solvers[i%8]->firstReduceDB; ms->solvers[i]->var_decay += noisevar_decay; ms->solvers[i]->firstReduceDB+=noiseReduceDB; if ((i+1) % 8 == 0) { noisevar_decay += 0.006; noiseReduceDB += 25; } } }
function_block-function_prefix_line
[ { "content": "struct IntRange {\n\n int begin;\n\n int end;\n\n IntRange(int b, int e) : begin(b), end(e) {}\n\n};\n\n\n", "file_path": "utils/Options.h", "rank": 0, "score": 30383.65854647451 }, { "content": "class IntOption : public Option\n\n{\n\n protected:\n\n IntRange range...
C++
aesxx/utils/encrypt_block.cpp
egor-tensin/aesni
76ae97ff1434941dcf0c6bf1679146dcb28718aa
#include "block_cmd_parser.hpp" #include "block_dumper.hpp" #include "block_input.hpp" #include <aesxx/all.hpp> #include <boost/program_options.hpp> #include <exception> #include <iostream> #include <stdexcept> #include <string> namespace { template <aes::Algorithm algorithm, aes::Mode mode> void encrypt_with_mode( const Input& input, bool verbose = false) { typename aes::Types<algorithm>::Block iv; if (aes::ModeRequiresInitVector<mode>::value) { aes::from_string<algorithm>(iv, input.iv); if (verbose) dump_iv<algorithm>(iv); } typename aes::Types<algorithm>::Key key; aes::from_string<algorithm>(key, input.key); if (verbose) dump_key<algorithm>(key); aes::EncryptWrapper<algorithm, mode> encrypt{key, iv}; if (verbose) dump_wrapper<algorithm, mode>(encrypt); for (const auto& input_block_string : input.blocks) { typename aes::Types<algorithm>::Block plaintext, ciphertext; aes::from_string<algorithm>(plaintext, input_block_string); encrypt.encrypt_block(plaintext, ciphertext); if (verbose) { dump_plaintext<algorithm>(plaintext); dump_ciphertext<algorithm>(ciphertext); dump_next_iv<algorithm, mode>(encrypt); } else { std::cout << aes::to_string<algorithm>(ciphertext) << '\n'; } } } template <aes::Algorithm algorithm> void encrypt_with_algorithm( aes::Mode mode, const Input& input, bool verbose = false) { switch (mode) { case AES_ECB: encrypt_with_mode<algorithm, AES_ECB>(input, verbose); break; case AES_CBC: encrypt_with_mode<algorithm, AES_CBC>(input, verbose); break; case AES_CFB: encrypt_with_mode<algorithm, AES_CFB>(input, verbose); break; case AES_OFB: encrypt_with_mode<algorithm, AES_OFB>(input, verbose); break; case AES_CTR: encrypt_with_mode<algorithm, AES_CTR>(input, verbose); break; default: throw std::runtime_error("the selected mode of operation is not implemented"); break; } } void encrypt_using_cxx_api( aes::Algorithm algorithm, aes::Mode mode, const Input& input, bool verbose = false) { switch (algorithm) { case AES_AES128: encrypt_with_algorithm<AES_AES128>(mode, input, verbose); break; case AES_AES192: encrypt_with_algorithm<AES_AES192>(mode, input, verbose); break; case AES_AES256: encrypt_with_algorithm<AES_AES256>(mode, input, verbose); break; default: throw std::runtime_error("the selected algorithm is not implemented"); break; } } void encrypt_using_particular_box( aes::Box& box, const std::vector<std::string>& input_block_strings) { for (const auto& input_block_string : input_block_strings) { aes::Box::Block plaintext; box.parse_block(plaintext, input_block_string); aes::Box::Block ciphertext; box.encrypt_block(plaintext, ciphertext); std::cout << box.format_block(ciphertext) << '\n'; } } void encrypt_using_boxes( aes::Algorithm algorithm, aes::Mode mode, const Input& input) { aes::Box::Key key; aes::Box::parse_key(key, algorithm, input.key); if (aes::mode_requires_init_vector(mode)) { aes::Box::Block iv; aes::Box::parse_block(iv, algorithm, input.iv); aes::Box box{algorithm, key, mode, iv}; encrypt_using_particular_box(box, input.blocks); } else { aes::Box box{algorithm, key}; encrypt_using_particular_box(box, input.blocks); } } } int main(int argc, char** argv) { try { BlockSettings settings{argv[0]}; try { settings.parse(argc, argv); } catch (const boost::program_options::error& e) { settings.usage_error(e); return 1; } if (settings.exit_with_usage) { settings.usage(); return 0; } for (const auto& input : settings.inputs) { if (settings.use_boxes) { encrypt_using_boxes( settings.algorithm, settings.mode, input); } else { encrypt_using_cxx_api( settings.algorithm, settings.mode, input, settings.verbose); } } } catch (const aes::Error& e) { std::cerr << e; return 1; } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return 1; } return 0; }
#include "block_cmd_parser.hpp" #include "block_dumper.hpp" #include "block_input.hpp" #include <aesxx/all.hpp> #include <boost/program_options.hpp> #include <exception> #include <iostream> #include <stdexcept> #include <string> namespace { template <aes::Algorithm algorithm, aes::Mode mode> void encrypt_with_mode( const Input& input, bool verbose = false) { typename aes::Types<algorithm>::Block iv; if (aes::ModeRequiresInitVector<mode>::value) { aes::from_string<algorithm>(iv, input.iv); if (verbose) dump_iv<algorithm>(iv); } typename aes::Types<algorithm>::Key key; aes::from_string<algorithm>(key, input.key); if (verbose) dump_key<algorithm>(key); aes::EncryptWrapper<algorithm, mode> encrypt{key, iv}; if (verbose) dump_wrapper<algorithm, mode>(encrypt); for (const auto& input_block_string : input.blocks) { typename aes::Types<algorithm>::Block plaintext, ciphertext; aes::from_string<algorithm>(plaintext, input_block_string); encrypt.encrypt_block(plaintext, ciphertext); if (verbose) { dump_plaintext<algorithm>(plaintext); dump_ciphertext<algorithm>(ciphertext); dump_next_iv<algorithm, mode>(encrypt); } else { std::cout << aes::to_string<algorithm>(ciphertext) << '\n'; } } } template <aes::Algorithm algorithm> void encrypt_with_algorithm( aes::Mode mode, const Input& input, bool verbose = false) { switch (mode) { case AES_ECB: encrypt_with_mode<algorithm, AES_ECB>(input, verbose); break; case AES_CBC: encrypt_with_mode<algorithm, AES_CBC>(input, verbose); break; case AES_CFB: encrypt_with_mode<algorithm, AES_CFB>(input, verbose); break; case AES_OFB: encrypt_with_mode<algorithm, AES_OFB>(input, verbose); break; case AES_CTR: encrypt_with_mode<algorithm, AES_CTR>(input, verbose); break; default: throw std::runtime_error("the selected mode of operation is not implemented"); break; } } void encrypt_using_cxx_api( aes::Algorithm algorithm, aes::Mode mode, const Input& input, bool verbose = false) { switch (algorithm) { case AES_AES128: encrypt_with_algorithm<AES_AES128>(mode, input, verbose); break; case AES_AES192: encrypt_with_algorithm<AES_AES192>(mode, input, verbose); break; case AES_AES256: encrypt_with_algorithm<AES_AES256>(mode, input, verbose); break; default: throw std::runtime_error("the selected algorithm is not implemented"); break; } } void encrypt_using_particular_box( aes::Box& box, const std::vector<std::string>& input_block_strings) { for (const auto& input_block_string : input_block_strings) { aes::Box::Block plaintext; box.parse_block(plaintext, input_block_string); aes::Box::Block ciphertext; box.encrypt_block(plaintext, ciphertext); std::cout << box.format_block(ciphertext) << '\n'; } } void encrypt_using_boxes( aes::Algorithm algorithm, aes::Mode mode, const Input& input) { aes::Box::Key key; aes::Box::parse_key(key, algorithm, input.key); if (aes::mode_requires_init_vector(mode)) { aes::Box::Block iv; aes::Box::parse_block(iv, algorithm, input.iv); aes::Box box{algorithm, key, mode, iv}; encrypt_using_particular_box(box, input.blocks); } else { aes::Box box{algorithm, key}; encrypt_using_particular_box(box, input.blocks); } } } int main(int argc, char** argv) { try { BlockSettings settings{argv[0]}; try { settings.parse(argc, argv); } catch (const boost::program_options::error& e) { settings.usage_error(e); return 1; } if (settings.exit_with_usage) { settings.usage(); return 0; } for (const auto& input : settings.inputs) {
} } catch (const aes::Error& e) { std::cerr << e; return 1; } catch (const std::exception& e) { std::cerr << e.what() << "\n"; return 1; } return 0; }
if (settings.use_boxes) { encrypt_using_boxes( settings.algorithm, settings.mode, input); } else { encrypt_using_cxx_api( settings.algorithm, settings.mode, input, settings.verbose); }
if_condition
[ { "content": " AES_BoxBlock iv;\n", "file_path": "aes/include/aes/box_data.h", "rank": 0, "score": 107986.0012956743 }, { "content": " const AES_BoxAlgorithmInterface* algorithm;\n", "file_path": "aes/include/aes/box_data.h", "rank": 1, "score": 107862.82410899692 }, { ...
C++
src/particle_filter.cpp
siva1729/CarND-Kidnapped-Vehicle-T2P3
3021d48321f7c907a0aace54f23ff892e1eea3db
#include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; #define NUM_PARTICLES 50 #define EPS 0.001 void dbg_pp (Particle &particle) { cout << "Sample: " << particle.id << " " << particle.x <<" " << particle.y << " " << particle.theta << endl; } void dbg_po (LandmarkObs &obs) { cout << "Observation: " << obs.id << " " << obs.x <<" " << obs.y << endl; } void ParticleFilter::init(double x, double y, double theta, double std[]) { num_particles = NUM_PARTICLES; weights.resize(num_particles); particles.resize(num_particles); random_device rd; default_random_engine gen(rd()); normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); for (int i = 0; i < particles.size(); ++i) { particles[i].id = i; particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); particles[i].weight = 1.0; } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { random_device rd; default_random_engine gen(rd()); double velocity_dt = velocity * delta_t; double yaw_rate_dt = yaw_rate * delta_t; for (int i = 0; i < particles.size(); ++i) { if (fabs(yaw_rate) < EPS) { particles[i].x += velocity_dt * cos(particles[i].theta); particles[i].y += velocity_dt * sin(particles[i].theta); } else { double velocity_yaw_rate = velocity/yaw_rate; double theta_dt = particles[i].theta + yaw_rate_dt; particles[i].x += velocity_yaw_rate * (sin(theta_dt) - sin(particles[i].theta)); particles[i].y += velocity_yaw_rate * (cos(particles[i].theta) - cos(theta_dt)); particles[i].theta = theta_dt; } normal_distribution<double> dist_x(particles[i].x, std_pos[0]); normal_distribution<double> dist_y(particles[i].y, std_pos[1]); normal_distribution<double> dist_theta(particles[i].theta, std_pos[2]); particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { for (int i = 0; i < observations.size(); i++) { double dist_min = numeric_limits<double>::max(); int associated_landmark_id = -1; double obx = observations[i].x; double oby = observations[i].y; for (int j = 0; j < predicted.size(); j++) { double dist_landmark = dist(obx, oby, predicted[j].x, predicted[j].y); if (dist_landmark < dist_min) { associated_landmark_id = predicted[j].id; dist_min = dist_landmark; observations[i].x = fabs(obx - predicted[j].x); observations[i].y = fabs(oby - predicted[j].y); } } if (associated_landmark_id == -1) { cout << "Error: No associated landmark found" << endl; } observations[i].id = associated_landmark_id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { double weight_sum = 0.0; for (int i = 0; i < particles.size(); i++) { double par_x = particles[i].x; double par_y = particles[i].y; double par_t = particles[i].theta; vector<LandmarkObs> within_range_landmarks; for (int j = 0; j < map_landmarks.landmark_list.size(); j++) { double mx = map_landmarks.landmark_list[j].x_f; double my = map_landmarks.landmark_list[j].y_f; if ( dist(par_x, par_y, mx, my) <= sensor_range ) { within_range_landmarks.push_back(LandmarkObs{map_landmarks.landmark_list[j].id_i, mx, my}); } } vector<LandmarkObs> mapped_observations; for (int j = 0; j < observations.size(); j++) { double mapx = cos(par_t) * observations[j].x - sin(par_t) * observations[j].y + par_x; double mapy = sin(par_t) * observations[j].x + cos(par_t) * observations[j].y + par_y; mapped_observations.push_back(LandmarkObs{observations[j].id, mapx, mapy}); } dataAssociation(within_range_landmarks, mapped_observations); particles[i].weight = 1.0; for (int j = 0; j < mapped_observations.size(); j++) { double mvg_prob; double diffX = mapped_observations[j].x; double diffY = mapped_observations[j].y; if (mapped_observations[j].id != -1) { double mvg_prob = (1/(2*M_PI*std_landmark[0]*std_landmark[1])) * exp(-((diffX*diffX)/(2*std_landmark[0]*std_landmark[0]) + (diffY*diffY)/(2*std_landmark[1]*std_landmark[1]))); if (mvg_prob < EPS) { mvg_prob = EPS; } particles[i].weight *= mvg_prob; } } weight_sum += particles[i].weight; } for (int i = 0; i < particles.size(); i++) { particles[i].weight /= weight_sum; weights[i] = particles[i].weight; } } void ParticleFilter::resample() { random_device rd; default_random_engine gen(rd()); vector<Particle> resampled_particles; resampled_particles.resize(particles.size()); discrete_distribution<int> dist_resample(weights.begin(), weights.end()); for (int i = 0; i < particles.size(); i++) { resampled_particles[i] = particles[dist_resample(gen)]; } particles = resampled_particles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; }
#include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; #define NUM_PARTICLES 50 #define EPS 0.001 void dbg_pp (Particle &particle) { cout << "Sample: " << particle.id << " " << particle.x <<" " << particle.y << " " << particle.theta << endl; } void dbg_po (LandmarkObs &obs) { cout << "Observation: " << obs.id << " " << obs.x <<" " << obs.y << endl; } void ParticleFilter::init(double x, double y, double theta, double std[]) { num_particles = NUM_PARTICLES; weights.resize(num_particles); particles.resize(num_particles); random_device rd; default_random_engine gen(rd()); normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); for (int i = 0; i < particles.size(); ++i) { particles[i].id = i; particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); particles[i].weight = 1.0; } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { random_device rd; default_random_engine gen(rd()); double velocity_dt = velocity * delta_t; double yaw_rate_dt = yaw_rate * delta_t; for (int i = 0; i < particles.size(); ++i) { if (fabs(yaw_rate) < EPS) { particles[i].x += velocity_dt * cos(particles[i].theta); particles[i].y += velocity_dt * sin(particles[i].theta); } else { double velocity_yaw_rate = velocity/yaw_rate; double theta_dt = particles[i].theta + yaw_rate_dt; particles[i].x += velocity_yaw_rate * (sin(theta_dt) - sin(particles[i].theta)); particles[i].y += velocity_yaw_rate * (cos(particles[i].theta) - cos(theta_dt)); particles[i].theta = theta_dt; } normal_distribution<double> dist_x(particles[i].x, std_pos[0]); normal_distribution<double> dist_y(particles[i].y, std_pos[1]); normal_distribution<double> dist_theta(particles[i].theta, std_pos[2]); particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { for (int i = 0; i < observations.size(); i++) { double dist_min = numeric_limits<double>::max(); int associated_landmark_id = -1; double obx = observations[i].x; double oby = observations[i].y; for (int j = 0; j < predicted.size(); j++) { double dist_landmark = dist(obx, oby, predicted[j].x, predicted[j].y); if (dist_landmark < dist_min) { associated_landmark_id = predicted[j].id; dist_min = dist_landmark; observations[i].x = fabs(obx - predicted[j].x); observations[i].y = fabs(oby - predicted[j].y); } } if (associated_landmark_id == -1) { cout << "Error: No associated landmark found" << endl; } observations[i].id = associated_landmark_id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { double weight_sum = 0.0; for (int i = 0; i < particles.size(); i++) { double par_x = particles[i].x; double par_y = particles[i].y; double par_t = particles[i].theta; vector<LandmarkObs> within_range_landmarks; for (int j = 0; j < map_landmarks.landmark_list.size(); j++) { double mx = map_landmarks.landmark_list[j].x_f; double my = map_landmarks.landmark_list[j].y_f; if ( dist(par_x, par_y, mx, my) <= sensor_range ) { within_range_landmarks.push_back(LandmarkObs{map_landmarks.landmark_list[j].i
void ParticleFilter::resample() { random_device rd; default_random_engine gen(rd()); vector<Particle> resampled_particles; resampled_particles.resize(particles.size()); discrete_distribution<int> dist_resample(weights.begin(), weights.end()); for (int i = 0; i < particles.size(); i++) { resampled_particles[i] = particles[dist_resample(gen)]; } particles = resampled_particles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); return s; }
d_i, mx, my}); } } vector<LandmarkObs> mapped_observations; for (int j = 0; j < observations.size(); j++) { double mapx = cos(par_t) * observations[j].x - sin(par_t) * observations[j].y + par_x; double mapy = sin(par_t) * observations[j].x + cos(par_t) * observations[j].y + par_y; mapped_observations.push_back(LandmarkObs{observations[j].id, mapx, mapy}); } dataAssociation(within_range_landmarks, mapped_observations); particles[i].weight = 1.0; for (int j = 0; j < mapped_observations.size(); j++) { double mvg_prob; double diffX = mapped_observations[j].x; double diffY = mapped_observations[j].y; if (mapped_observations[j].id != -1) { double mvg_prob = (1/(2*M_PI*std_landmark[0]*std_landmark[1])) * exp(-((diffX*diffX)/(2*std_landmark[0]*std_landmark[0]) + (diffY*diffY)/(2*std_landmark[1]*std_landmark[1]))); if (mvg_prob < EPS) { mvg_prob = EPS; } particles[i].weight *= mvg_prob; } } weight_sum += particles[i].weight; } for (int i = 0; i < particles.size(); i++) { particles[i].weight /= weight_sum; weights[i] = particles[i].weight; } }
function_block-function_prefixed
[ { "content": " class iter_impl : public std::iterator<std::random_access_iterator_tag, U>\n\n {\n\n /// allow basic_json to access private members\n\n friend class basic_json;\n\n\n\n // make sure U is basic_json or const basic_json\n\n static_assert(std::is_same<U, basic_json>...
C++
source/grid/setup_grid_NG_MPI.cpp
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
#include "defines/functionality_flags.h" #include "defines/testing_flags.h" #include "tools/reporting.h" #include "tools/command_line_interface.h" #include "raytracing/raytracer_SC.h" #include "grid/setup_grid_NG_MPI.h" #include "grid/uniform_grid.h" #include "grid/uniform_grid_pllel.h" #include "spatial_solvers/solver_eqn_hydro_adi.h" #include "spatial_solvers/solver_eqn_mhd_adi.h" #include "microphysics/microphysics_base.h" #include "microphysics/mp_only_cooling.h" #include "microphysics/MPv3.h" #include "microphysics/MPv5.h" #include "microphysics/MPv6.h" #include "microphysics/MPv7.h" #include "microphysics/MPv8.h" #ifdef FITS #include "dataIO/dataio_fits_MPI.h" #endif #ifndef EXCLUDE_HD_MODULE #include "microphysics/MPv9.h" #endif #ifdef CODE_EXT_HHE #include "future/mpv9_HHe.h" #endif #include <iostream> #include <sstream> #include <fstream> #include <string> #include <sys/time.h> #include <time.h> #include <climits> using namespace std; setup_grid_NG_MPI::setup_grid_NG_MPI() { #ifdef TESTING cout <<"setup_grid_NG_MPI constructor called.\n"; #endif return; } setup_grid_NG_MPI::~setup_grid_NG_MPI() { #ifdef TESTING cout <<"setup_grid_NG_MPI destructor called.\n"; #endif return; } void setup_grid_NG_MPI::setup_NG_grid_levels( class SimParams &SimPM ) { int err=0; setup_NG_grid::setup_NG_grid_levels(SimPM); int myrank=-1, nproc=-1; COMM->get_rank_nproc(&myrank,&nproc); for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].MCMD.set_myrank(myrank); SimPM.levels[l].MCMD.set_nproc(nproc); err = SimPM.levels[l].MCMD.decomposeDomain(SimPM, SimPM.levels[l]); rep.errorTest("PLLEL Init():Decompose Domain!",0,err); SimPM.levels[l].MCMD.ReadSingleFile = true; } for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].MCMD.set_NG_hierarchy(SimPM,l); } return; } int setup_grid_NG_MPI::setup_grid( vector<class GridBaseClass *> &grid, class SimParams &SimPM ) { cout <<"(pion) Setting up MPI NG grid\n"; if (SimPM.ndim <1 || SimPM.ndim>3) rep.error("Only know 1D,2D,3D methods!",SimPM.ndim); #ifdef TESTING cout <<"Setting number of boundary cells == spatial OOA: "; cout <<SimPM.spOOA<<"\n"; #endif if (SimPM.spOOA==OA2) {SimPM.Nbc = 6; SimPM.Nbc_DD = 4;} else if (SimPM.spOOA==OA1) {SimPM.Nbc = 4; SimPM.Nbc_DD = 2;} else rep.error("unhandles spatial order of accuracy",SimPM.spOOA); setup_cell_extra_data(SimPM); double dx=(SimPM.Xmax[XX]-SimPM.Xmin[XX])/SimPM.NG[XX]; CI.set_nlevels(dx,SimPM.grid_nlevels); CI.set_ndim(SimPM.ndim); CI.set_nvar(SimPM.nvar); CI.set_xmin(SimPM.Xmin); #ifdef TESTING cout <<"(setup_grid_NG_MPI::setup_grid) Setting up grid...\n"; #endif for (int l=0; l<SimPM.grid_nlevels; l++) { #ifdef TESTING cout <<"Init: level="<< l <<", &grid="<< &(grid[l]); cout <<", and grid="<< grid[l] <<"\n"; #endif if (grid[l]) rep.error("Grid already set up!",grid[l]); if (SimPM.coord_sys==COORD_CRT) grid[l] = new UniformGridParallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_CYL) grid[l] = new uniform_grid_cyl_parallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_SPH) grid[l] = new uniform_grid_sph_parallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else rep.error("Bad Geometry in setup_grid()",SimPM.coord_sys); if (grid[l]==0) rep.error("(setup_grid_NG_MPI::setup_grid)", grid[l]); #ifdef TESTING cout <<"(setup_grid_NG_MPI::setup_grid) Done. &grid="; cout << &(grid[l])<<", and grid="<<grid[l]<<"\n"; cout <<"DX = "<<(grid[l])->DX()<<"\n"; #endif } for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].grid = grid[l]; if (l==0) { SimPM.levels[l].parent = 0; if (SimPM.grid_nlevels>1) SimPM.levels[l].child = grid[l+1]; } else if (l==SimPM.grid_nlevels-1) { if (SimPM.grid_nlevels>1) SimPM.levels[l].parent = grid[l-1]; SimPM.levels[l].child = 0; } else { SimPM.levels[l].parent = grid[l-1]; SimPM.levels[l].child = grid[l+1]; } } set_leaf_cells(grid,SimPM); setup_flux_vectors(SimPM.grid_nlevels); for (int l=0;l<SimPM.grid_nlevels;l++) { if (l!=0) setup_flux_send(SimPM,grid[l],l-1); if (l!=SimPM.grid_nlevels-1) setup_flux_recv(SimPM,grid[l],l+1); } return(0); } int setup_grid_NG_MPI::setup_raytracing( class SimParams &SimPM, vector<class GridBaseClass *> &grid ) { if (!SimPM.EP.raytracing) { return 0; } int err = 0; for (int l=0;l<SimPM.grid_nlevels;l++) { #ifdef TESTING cout <<"setting up raytracing for grid level "<<l<<"\n"; #endif err += setup_fixed_grid_pllel::setup_raytracing(SimPM,grid[l]); rep.errorTest("setup_grid_NG_MPI::setup_raytracing()",0,err); } #ifdef TESTING cout <<"NG-MPI setting up evolving RT sources from setup_raytracing.\n"; #endif err += setup_evolving_RT_sources(SimPM); rep.errorTest("setup_grid_NG_MPI::setup_evolving_RT_sources()",0,err); for (int l=0;l<SimPM.grid_nlevels;l++) { #ifdef TESTING cout <<"NG-MPI l="<<l<<": updating evolving RT sources from setup_raytracing.\n"; #endif err += update_evolving_RT_sources(SimPM,SimPM.levels[l].simtime,grid[l]->RT); rep.errorTest("setup_grid_NG_MPI::update_evolving_RT_sources()",0,err); } return 0; } int setup_grid_NG_MPI::boundary_conditions( class SimParams &par, vector<class GridBaseClass *> &grid ) { #ifdef TESTING cout <<"Setting up BCs in MPI-NG Grid with Nbc="<<par.Nbc<<"\n"; #endif int err = setup_NG_grid::boundary_conditions(par,grid); rep.errorTest("setup_grid_NG_MPI::boundary_conditions",0,err); #ifdef TESTING cout <<"(setup_grid_NG_MPI::boundary_conditions) Done.\n"; #endif return 0; } int setup_grid_NG_MPI::setup_boundary_structs( class SimParams &par, class GridBaseClass *grid, const int l ) { #ifdef TESTING cout <<"Set BC types...\n"; #endif int err = 0; #ifdef TESTING cout <<"setting up serial boundary structs\n"; #endif err = setup_fixed_grid::setup_boundary_structs(par,grid,l); rep.errorTest("png::setup_boundary_structs fixed grid",0,err); #ifdef SKIP_C2F_BC if (1==0) { #endif if (l>0) { #ifdef TESTING cout <<"replacing external BCs with C2F as needed\n"; #endif for (int i=0; i<par.ndim; i++) { if (!pconst.equalD(par.levels[l-1].Xmin[i], par.levels[l].Xmin[i]) && pconst.equalD(par.levels[l].Xmin[i], grid->Xmin(static_cast<axes>(i))) ) { #ifdef TESTING cout <<"reassigning neg. bc for axis "<<i<<" to COARSE_TO_FINE\n"; #endif grid->BC_bd[2*i]->itype = COARSE_TO_FINE_RECV; grid->BC_bd[2*i]->type = "COARSE_TO_FINE_RECV"; } if (!pconst.equalD(par.levels[l-1].Xmax[i], par.levels[l].Xmax[i]) && pconst.equalD(par.levels[l].Xmax[i], grid->Xmax(static_cast<axes>(i))) ) { #ifdef TESTING cout <<"reassigning pos. bc for axis "<<i<<" to COARSE_TO_FINE\n"; #endif grid->BC_bd[2*i+1]->itype = COARSE_TO_FINE_RECV; grid->BC_bd[2*i+1]->type = "COARSE_TO_FINE_RECV"; } } } #ifdef SKIP_C2F_BC } #endif if (l < par.grid_nlevels-1) { #ifdef SKIP_F2C_BC if (1==0) { #endif #ifdef TESTING cout <<"Adding FINE_TO_COARSE_RECV boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd = new boundary_data; bd->itype = FINE_TO_COARSE_RECV; bd->type = "FINE_TO_COARSE_RECV"; bd->dir = NO; bd->ondir = NO; bd->refval=0; grid->BC_bd.push_back(bd); #ifdef SKIP_F2C_BC } #endif #ifdef SKIP_C2F_BC if (1==0) { #endif #ifdef TESTING cout <<"Adding COARSE_TO_FINE_SEND boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd2 = new boundary_data; bd2->itype = COARSE_TO_FINE_SEND; bd2->type = "COARSE_TO_FINE_SEND"; bd2->dir = NO; bd2->ondir = NO; bd2->refval=0; grid->BC_bd.push_back(bd2); #ifdef SKIP_C2F_BC } #endif } #ifdef SKIP_F2C_BC if (1==0) { #endif if (l>0) { #ifdef TESTING cout <<"Adding FINE_TO_COARSE_SEND boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd = new boundary_data; bd->itype = FINE_TO_COARSE_SEND; bd->type = "FINE_TO_COARSE_SEND"; bd->dir = NO; bd->ondir = NO; bd->refval=0; grid->BC_bd.push_back(bd); } #ifdef SKIP_F2C_BC } #endif #ifdef TESTING cout <<"BC structs set up.\n"; for (unsigned int v=0; v<grid->BC_bd.size(); v++) { cout<<"i="<<v<<", BC type= "<<grid->BC_bd[v]->type; cout <<", BC itype= "<<grid->BC_bd[v]->itype<<"\n"; } #endif #ifdef TESTING cout <<"calling pll fixed grid setup function.\n"; #endif err = setup_fixed_grid_pllel::setup_boundary_structs(par,grid,l); rep.errorTest("png::setup_boundary_structs pll fixed grid",0,err); #ifdef TESTING cout <<"BC structs set up.\n"; for (unsigned int v=0; v<grid->BC_bd.size(); v++) { cout<<"i="<<v<<", BC type= "<<grid->BC_bd[v]->type<<"\n"; } #endif return 0; } void setup_grid_NG_MPI::setup_dataio_class( class SimParams &par, const int typeOfFile ) { switch (typeOfFile) { #ifdef SILO case 5: dataio = new dataio_silo_utility (par, "DOUBLE", &(par.levels[0].MCMD)); break; #endif default: rep.error("sim_control_NG_MPI::Init unhandled filetype",typeOfFile); } return; }
#include "defines/functionality_flags.h" #include "defines/testing_flags.h" #include "tools/reporting.h" #include "tools/command_line_interface.h" #include "raytracing/raytracer_SC.h" #include "grid/setup_grid_NG_MPI.h" #include "grid/uniform_grid.h" #include "grid/uniform_grid_pllel.h" #include "spatial_solvers/solver_eqn_hydro_adi.h" #include "spatial_solvers/solver_eqn_mhd_adi.h" #include "microphysics/microphysics_base.h" #include "microphysics/mp_only_cooling.h" #include "microphysics/MPv3.h" #include "microphysics/MPv5.h" #include "microphysics/MPv6.h" #include "microphysics/MPv7.h" #include "microphysics/MPv8.h" #ifdef FITS #include "dataIO/dataio_fits_MPI.h" #endif #ifndef EXCLUDE_HD_MODULE #include "microphysics/MPv9.h" #endif #ifdef CODE_EXT_HHE #include "future/mpv9_HHe.h" #endif #include <iostream> #include <sstream> #include <fstream> #include <string> #include <sys/time.h> #include <time.h> #include <climits> using namespace std; setup_grid_NG_MPI::setup_grid_NG_MPI() { #ifdef TESTING cout <<"setup_grid_NG_MPI constructor called.\n"; #endif return; } setup_grid_NG_MPI::~setup_grid_NG_MPI() { #ifdef TESTING cout <<"setup_grid_NG_MPI destructor called.\n"; #endif return; } void setup_grid_NG_MPI::setup_NG_grid_levels( class SimParams &SimPM ) { int err=0; setup_NG_grid::setup_NG_grid_levels(SimPM); int myrank=-1, nproc=-1; COMM->get_rank_nproc(&myrank,&nproc); for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].MCMD.set_myrank(myrank); SimPM.levels[l].MCMD.set_nproc(nproc); err = SimPM.levels[l].MCMD.decomposeDomain(SimPM, SimPM.levels[l]); rep.errorTest("PLLEL Init():Decompose Domain!",0,err); SimPM.levels[l].MCMD.ReadSingleFile = true; } for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].MCMD.set_NG_hierarchy(SimPM,l); } return; } int setup_grid_NG_MPI::setup_grid( vector<class GridBaseClass *> &grid, class SimParams &SimPM ) { cout <<"(pion) Setting up MPI NG grid\n"; if (SimPM.ndim <1 || SimPM.ndim>3) rep.error("Only know 1D,2D,3D methods!",SimPM.ndim); #ifdef TESTING cout <<"Setting number of boundary cells == spatial OOA: "; cout <<SimPM.spOOA<<"\n"; #endif
setup_cell_extra_data(SimPM); double dx=(SimPM.Xmax[XX]-SimPM.Xmin[XX])/SimPM.NG[XX]; CI.set_nlevels(dx,SimPM.grid_nlevels); CI.set_ndim(SimPM.ndim); CI.set_nvar(SimPM.nvar); CI.set_xmin(SimPM.Xmin); #ifdef TESTING cout <<"(setup_grid_NG_MPI::setup_grid) Setting up grid...\n"; #endif for (int l=0; l<SimPM.grid_nlevels; l++) { #ifdef TESTING cout <<"Init: level="<< l <<", &grid="<< &(grid[l]); cout <<", and grid="<< grid[l] <<"\n"; #endif if (grid[l]) rep.error("Grid already set up!",grid[l]); if (SimPM.coord_sys==COORD_CRT) grid[l] = new UniformGridParallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_CYL) grid[l] = new uniform_grid_cyl_parallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else if (SimPM.coord_sys==COORD_SPH) grid[l] = new uniform_grid_sph_parallel ( SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Nbc, SimPM.levels[l].MCMD.LocalXmin, SimPM.levels[l].MCMD.LocalXmax, SimPM.levels[l].MCMD.LocalNG, SimPM.levels[l].Xmin, SimPM.levels[l].Xmax, SimPM.Xmin, SimPM.Xmax); else rep.error("Bad Geometry in setup_grid()",SimPM.coord_sys); if (grid[l]==0) rep.error("(setup_grid_NG_MPI::setup_grid)", grid[l]); #ifdef TESTING cout <<"(setup_grid_NG_MPI::setup_grid) Done. &grid="; cout << &(grid[l])<<", and grid="<<grid[l]<<"\n"; cout <<"DX = "<<(grid[l])->DX()<<"\n"; #endif } for (int l=0;l<SimPM.grid_nlevels;l++) { SimPM.levels[l].grid = grid[l]; if (l==0) { SimPM.levels[l].parent = 0; if (SimPM.grid_nlevels>1) SimPM.levels[l].child = grid[l+1]; } else if (l==SimPM.grid_nlevels-1) { if (SimPM.grid_nlevels>1) SimPM.levels[l].parent = grid[l-1]; SimPM.levels[l].child = 0; } else { SimPM.levels[l].parent = grid[l-1]; SimPM.levels[l].child = grid[l+1]; } } set_leaf_cells(grid,SimPM); setup_flux_vectors(SimPM.grid_nlevels); for (int l=0;l<SimPM.grid_nlevels;l++) { if (l!=0) setup_flux_send(SimPM,grid[l],l-1); if (l!=SimPM.grid_nlevels-1) setup_flux_recv(SimPM,grid[l],l+1); } return(0); } int setup_grid_NG_MPI::setup_raytracing( class SimParams &SimPM, vector<class GridBaseClass *> &grid ) { if (!SimPM.EP.raytracing) { return 0; } int err = 0; for (int l=0;l<SimPM.grid_nlevels;l++) { #ifdef TESTING cout <<"setting up raytracing for grid level "<<l<<"\n"; #endif err += setup_fixed_grid_pllel::setup_raytracing(SimPM,grid[l]); rep.errorTest("setup_grid_NG_MPI::setup_raytracing()",0,err); } #ifdef TESTING cout <<"NG-MPI setting up evolving RT sources from setup_raytracing.\n"; #endif err += setup_evolving_RT_sources(SimPM); rep.errorTest("setup_grid_NG_MPI::setup_evolving_RT_sources()",0,err); for (int l=0;l<SimPM.grid_nlevels;l++) { #ifdef TESTING cout <<"NG-MPI l="<<l<<": updating evolving RT sources from setup_raytracing.\n"; #endif err += update_evolving_RT_sources(SimPM,SimPM.levels[l].simtime,grid[l]->RT); rep.errorTest("setup_grid_NG_MPI::update_evolving_RT_sources()",0,err); } return 0; } int setup_grid_NG_MPI::boundary_conditions( class SimParams &par, vector<class GridBaseClass *> &grid ) { #ifdef TESTING cout <<"Setting up BCs in MPI-NG Grid with Nbc="<<par.Nbc<<"\n"; #endif int err = setup_NG_grid::boundary_conditions(par,grid); rep.errorTest("setup_grid_NG_MPI::boundary_conditions",0,err); #ifdef TESTING cout <<"(setup_grid_NG_MPI::boundary_conditions) Done.\n"; #endif return 0; } int setup_grid_NG_MPI::setup_boundary_structs( class SimParams &par, class GridBaseClass *grid, const int l ) { #ifdef TESTING cout <<"Set BC types...\n"; #endif int err = 0; #ifdef TESTING cout <<"setting up serial boundary structs\n"; #endif err = setup_fixed_grid::setup_boundary_structs(par,grid,l); rep.errorTest("png::setup_boundary_structs fixed grid",0,err); #ifdef SKIP_C2F_BC if (1==0) { #endif if (l>0) { #ifdef TESTING cout <<"replacing external BCs with C2F as needed\n"; #endif for (int i=0; i<par.ndim; i++) { if (!pconst.equalD(par.levels[l-1].Xmin[i], par.levels[l].Xmin[i]) && pconst.equalD(par.levels[l].Xmin[i], grid->Xmin(static_cast<axes>(i))) ) { #ifdef TESTING cout <<"reassigning neg. bc for axis "<<i<<" to COARSE_TO_FINE\n"; #endif grid->BC_bd[2*i]->itype = COARSE_TO_FINE_RECV; grid->BC_bd[2*i]->type = "COARSE_TO_FINE_RECV"; } if (!pconst.equalD(par.levels[l-1].Xmax[i], par.levels[l].Xmax[i]) && pconst.equalD(par.levels[l].Xmax[i], grid->Xmax(static_cast<axes>(i))) ) { #ifdef TESTING cout <<"reassigning pos. bc for axis "<<i<<" to COARSE_TO_FINE\n"; #endif grid->BC_bd[2*i+1]->itype = COARSE_TO_FINE_RECV; grid->BC_bd[2*i+1]->type = "COARSE_TO_FINE_RECV"; } } } #ifdef SKIP_C2F_BC } #endif if (l < par.grid_nlevels-1) { #ifdef SKIP_F2C_BC if (1==0) { #endif #ifdef TESTING cout <<"Adding FINE_TO_COARSE_RECV boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd = new boundary_data; bd->itype = FINE_TO_COARSE_RECV; bd->type = "FINE_TO_COARSE_RECV"; bd->dir = NO; bd->ondir = NO; bd->refval=0; grid->BC_bd.push_back(bd); #ifdef SKIP_F2C_BC } #endif #ifdef SKIP_C2F_BC if (1==0) { #endif #ifdef TESTING cout <<"Adding COARSE_TO_FINE_SEND boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd2 = new boundary_data; bd2->itype = COARSE_TO_FINE_SEND; bd2->type = "COARSE_TO_FINE_SEND"; bd2->dir = NO; bd2->ondir = NO; bd2->refval=0; grid->BC_bd.push_back(bd2); #ifdef SKIP_C2F_BC } #endif } #ifdef SKIP_F2C_BC if (1==0) { #endif if (l>0) { #ifdef TESTING cout <<"Adding FINE_TO_COARSE_SEND boundary for level "; cout <<l<<", current # boundaries: "<<grid->BC_bd.size() <<"\n"; #endif struct boundary_data *bd = new boundary_data; bd->itype = FINE_TO_COARSE_SEND; bd->type = "FINE_TO_COARSE_SEND"; bd->dir = NO; bd->ondir = NO; bd->refval=0; grid->BC_bd.push_back(bd); } #ifdef SKIP_F2C_BC } #endif #ifdef TESTING cout <<"BC structs set up.\n"; for (unsigned int v=0; v<grid->BC_bd.size(); v++) { cout<<"i="<<v<<", BC type= "<<grid->BC_bd[v]->type; cout <<", BC itype= "<<grid->BC_bd[v]->itype<<"\n"; } #endif #ifdef TESTING cout <<"calling pll fixed grid setup function.\n"; #endif err = setup_fixed_grid_pllel::setup_boundary_structs(par,grid,l); rep.errorTest("png::setup_boundary_structs pll fixed grid",0,err); #ifdef TESTING cout <<"BC structs set up.\n"; for (unsigned int v=0; v<grid->BC_bd.size(); v++) { cout<<"i="<<v<<", BC type= "<<grid->BC_bd[v]->type<<"\n"; } #endif return 0; } void setup_grid_NG_MPI::setup_dataio_class( class SimParams &par, const int typeOfFile ) { switch (typeOfFile) { #ifdef SILO case 5: dataio = new dataio_silo_utility (par, "DOUBLE", &(par.levels[0].MCMD)); break; #endif default: rep.error("sim_control_NG_MPI::Init unhandled filetype",typeOfFile); } return; }
if (SimPM.spOOA==OA2) {SimPM.Nbc = 6; SimPM.Nbc_DD = 4;} else if (SimPM.spOOA==OA1) {SimPM.Nbc = 4; SimPM.Nbc_DD = 2;} else rep.error("unhandles spatial order of accuracy",SimPM.spOOA);
if_condition
[ { "content": " // Else, make a vector of structs with a list of cells contained\n\n // in each coarse cell (2,4,or 8) of the parent grid. This grid\n\n // is (by design) entirely contained within the parent.\n\n class GridBaseClass *grid = par.levels[l].grid;\n\n int nc=1; // number of fine cel...
C++
milk/supervised/_lasso.cpp
aflaxman/milk
252806fd081dc1b3c7fe34b14f9e7a4b646e0b49
#include <iostream> #include <memory> #include <cmath> #include <random> #include <cassert> #include <queue> #include <eigen3/Eigen/Dense> using namespace Eigen; extern "C" { #include <Python.h> #include <numpy/ndarrayobject.h> } namespace { template <typename T> int random_int(T& random, const int max) { std::uniform_int_distribution<int> dist(0, max - 1); return dist(random); } inline float soft(const float val, const float lam) { return std::copysign(std::fdim(std::fabs(val), lam), val); } typedef Map<Matrix<float, Dynamic, Dynamic, RowMajor>, Aligned> MapXAf; bool has_nans(const MapXAf& X) { for (int i = 0; i != X.rows(); ++i) { for (int j = 0; j != X.cols(); ++j) { if (std::isnan(X(i,j))) return true; } } return false; } struct lasso_solver { lasso_solver(const MapXAf& X, const MapXAf& Y, const MapXAf& W, MapXAf& B, const int max_iter, const float lam, const float eps) :X(X) ,Y(Y) ,W(W) ,B(B) ,max_iter(max_iter) ,lam(lam) ,eps(eps) { } void next_coords(int& i, int& j) { ++j; if (j == B.cols()) { j = 0; ++i; if (i == B.rows()) { i = 0; } } } int solve() { Matrix<float, Dynamic, Dynamic, RowMajor> residuals; int i = 0; int j = -1; bool sweep = false; bool changed = false; assert(!has_nans(X)); assert(!has_nans(Y)); assert(!has_nans(B)); for (int it = 0; it != max_iter; ++it) { this->next_coords(i, j); if (i == 0 && j == 0) { if (sweep && !changed) { return it; } if (!changed) { sweep = true; residuals = Y - B*X; } else { sweep = false; } changed = false; } if (!sweep && B(i,j) == 0.0) continue; const float prev = B(i,j); assert(Y.cols() == W.cols()); assert(Y.cols() == X.cols()); assert(Y.cols() == residuals.cols()); const float x2 = (W.row(i).array()*X.row(j).array() * X.row(j).array()).sum(); const float xy = (W.row(i).array()*X.row(j).array() * residuals.row(i).array()).sum(); const float raw_step = (x2 == 0.0 ? 0.0 : xy/x2); const float best = soft(prev + raw_step, lam); const float step = best - prev; if (std::fabs(step) > eps) { assert(!std::isnan(best)); B(i,j) = best; residuals.row(i) -= step*X.row(j); changed = true; } } return max_iter; } std::mt19937 r; const MapXAf& X; const MapXAf& Y; const MapXAf& W; MapXAf& B; const int max_iter; const float lam; const float eps; }; MapXAf as_eigen(PyArrayObject* arr) { assert(PyArray_EquivTypenums(PyArray_TYPE(arr), NPY_FLOAT32)); assert(PyArray_ISCARRAY_RO(arr)); return MapXAf( static_cast<float*>(PyArray_DATA(arr)), PyArray_DIM(arr, 0), PyArray_DIM(arr, 1)); } const char* errmsg = "INTERNAL ERROR"; PyObject* py_lasso(PyObject* self, PyObject* args) { PyArrayObject* X; PyArrayObject* Y; PyArrayObject* W; PyArrayObject* B; int max_iter; float lam; float eps; if (!PyArg_ParseTuple(args, "OOOOiff", &X, &Y, &W, &B, &max_iter, &lam, &eps)) return NULL; if (!PyArray_Check(X) || !PyArray_ISCARRAY_RO(X) || !PyArray_Check(Y) || !PyArray_ISCARRAY_RO(Y) || !PyArray_Check(W) || !PyArray_ISCARRAY_RO(W) || !PyArray_Check(B) || !PyArray_ISCARRAY(B) || !PyArray_EquivTypenums(PyArray_TYPE(X), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(Y), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(W), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(B), NPY_FLOAT32)) { PyErr_SetString(PyExc_RuntimeError,errmsg); return 0; } MapXAf mX = as_eigen(X); MapXAf mY = as_eigen(Y); MapXAf mW = as_eigen(W); MapXAf mB = as_eigen(B); max_iter *= mB.size(); lasso_solver solver(mX, mY, mW, mB, max_iter, lam, eps); const int iters = solver.solve(); return Py_BuildValue("i", iters); } PyMethodDef methods[] = { {"lasso", py_lasso, METH_VARARGS , "Do NOT call directly.\n" }, {NULL, NULL,0,NULL}, }; const char * module_doc = "Internal Module.\n" "\n" "Do NOT use directly!\n"; } extern "C" void init_lasso() { import_array(); (void)Py_InitModule3("_lasso", methods, module_doc); }
#include <iostream> #include <memory> #include <cmath> #include <random> #include <cassert> #include <queue> #include <eigen3/Eigen/Dense> using namespace Eigen; extern "C" { #include <Python.h> #include <numpy/ndarrayobject.h> } namespace { template <typename T> int random_int(T& random, const int max) { std::uniform_int_distribution<int> dist(0, max - 1); return dist(random); } inline float soft(const float val, const float lam) { return std::copysign(std::fdim(std::fabs(val), lam), val); } typedef Map<Matrix<float, Dynamic, Dynamic, RowMajor>, Aligned> MapXAf; bool has_nans(const MapXAf& X) { for (int i = 0; i != X.rows(); ++i) { for (int j = 0; j != X.cols(); ++j) { if (std::isnan(X(i,j))) return true; } } return false; } struct lasso_solver { lasso_solver(const MapXAf& X, const MapXAf& Y, const MapXAf& W, MapXAf& B, const int max_iter, const float lam, const float eps) :X(X) ,Y(Y) ,W(W) ,B(B) ,max_iter(max_iter) ,lam(lam) ,eps(eps) { } void next_coords(int& i, int& j) { ++j; if (j == B.cols()) { j = 0; ++i; if (i == B.rows()) { i = 0; } } } int solve() { Matrix<float, Dynamic, Dynamic, RowMajor> residuals; int i = 0; int j = -1; bool
- B*X; } else { sweep = false; } changed = false; } if (!sweep && B(i,j) == 0.0) continue; const float prev = B(i,j); assert(Y.cols() == W.cols()); assert(Y.cols() == X.cols()); assert(Y.cols() == residuals.cols()); const float x2 = (W.row(i).array()*X.row(j).array() * X.row(j).array()).sum(); const float xy = (W.row(i).array()*X.row(j).array() * residuals.row(i).array()).sum(); const float raw_step = (x2 == 0.0 ? 0.0 : xy/x2); const float best = soft(prev + raw_step, lam); const float step = best - prev; if (std::fabs(step) > eps) { assert(!std::isnan(best)); B(i,j) = best; residuals.row(i) -= step*X.row(j); changed = true; } } return max_iter; } std::mt19937 r; const MapXAf& X; const MapXAf& Y; const MapXAf& W; MapXAf& B; const int max_iter; const float lam; const float eps; }; MapXAf as_eigen(PyArrayObject* arr) { assert(PyArray_EquivTypenums(PyArray_TYPE(arr), NPY_FLOAT32)); assert(PyArray_ISCARRAY_RO(arr)); return MapXAf( static_cast<float*>(PyArray_DATA(arr)), PyArray_DIM(arr, 0), PyArray_DIM(arr, 1)); } const char* errmsg = "INTERNAL ERROR"; PyObject* py_lasso(PyObject* self, PyObject* args) { PyArrayObject* X; PyArrayObject* Y; PyArrayObject* W; PyArrayObject* B; int max_iter; float lam; float eps; if (!PyArg_ParseTuple(args, "OOOOiff", &X, &Y, &W, &B, &max_iter, &lam, &eps)) return NULL; if (!PyArray_Check(X) || !PyArray_ISCARRAY_RO(X) || !PyArray_Check(Y) || !PyArray_ISCARRAY_RO(Y) || !PyArray_Check(W) || !PyArray_ISCARRAY_RO(W) || !PyArray_Check(B) || !PyArray_ISCARRAY(B) || !PyArray_EquivTypenums(PyArray_TYPE(X), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(Y), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(W), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(B), NPY_FLOAT32)) { PyErr_SetString(PyExc_RuntimeError,errmsg); return 0; } MapXAf mX = as_eigen(X); MapXAf mY = as_eigen(Y); MapXAf mW = as_eigen(W); MapXAf mB = as_eigen(B); max_iter *= mB.size(); lasso_solver solver(mX, mY, mW, mB, max_iter, lam, eps); const int iters = solver.solve(); return Py_BuildValue("i", iters); } PyMethodDef methods[] = { {"lasso", py_lasso, METH_VARARGS , "Do NOT call directly.\n" }, {NULL, NULL,0,NULL}, }; const char * module_doc = "Internal Module.\n" "\n" "Do NOT use directly!\n"; } extern "C" void init_lasso() { import_array(); (void)Py_InitModule3("_lasso", methods, module_doc); }
sweep = false; bool changed = false; assert(!has_nans(X)); assert(!has_nans(Y)); assert(!has_nans(B)); for (int it = 0; it != max_iter; ++it) { this->next_coords(i, j); if (i == 0 && j == 0) { if (sweep && !changed) { return it; } if (!changed) { sweep = true; residuals = Y
random
[ { "content": "struct Kmeans_Exception {\n\n Kmeans_Exception(const char* msg): msg(msg) { }\n\n const char* msg;\n\n\n\n};\n\nvoid assert_type_contiguous(PyArrayObject* array,int type) { \n\n if (!PyArray_Check(array) ||\n\n PyArray_TYPE(array) != type ||\n\n !PyArray_ISCONTIGUOUS(array))...
C++
MsgParser.cpp
fri000/MsgParser
edbc48e664416f144e00712d879a45298d8728d2
#include <avr/pgmspace.h> #include <inttypes.h> #include <string.h> #include <stdlib.h> #include "MsgParser.h" MsgParser::MsgParser() { m_BufferWriteIndex = 0; m_pRead = m_pInputBuffer; m_pMsgParserCommand = NULL; m_msgStartByte = '/'; m_msgEndByte = '\r'; m_useStartByte = false; m_state = WAITING_FOR_START_BYTE; m_pFuncTable = NULL; m_funcTableLength = 0; m_pCmdNotFoundFunc = NULL; memset(m_pInputBuffer, NULL, MSGPARSER_INPUT_BUFFER_SIZE); memset(m_pDescBuf, NULL, MSGPARSER_DESCRIPTION_SIZE); useStartByteSet(m_useStartByte); } void MsgParser::setTable(const FuncEntry_t* newFunctTable, uint8_t newFunctTableLength) { if(newFunctTable != NULL) { m_pFuncTable = (FuncEntry_t*)newFunctTable; m_funcTableLength = newFunctTableLength; } } void MsgParser::useStartByteSet(bool newStatus) { m_useStartByte = newStatus; if( (m_state == WAITING_FOR_START_BYTE) && (m_useStartByte == false) ) { m_state = READING_MESSAGE; } else { } } void MsgParser::setHandlerForCmdNotFound(cmdNotFoundHandler_t pNewHandlerFunc) { m_pCmdNotFoundFunc = pNewHandlerFunc; } void MsgParser::processByte(uint8_t newByte) { switch (m_state) { case WAITING_FOR_START_BYTE: if( newByte == m_msgStartByte ) { m_state = READING_MESSAGE; } else { } break; case READING_MESSAGE: if( newByte == m_msgEndByte ) { if(m_useStartByte == true) m_state = WAITING_FOR_START_BYTE; bool msgFound = false; char *ptr = m_pRead; char *rest; memcpy(m_pOrigMsg, m_pInputBuffer, m_BufferWriteIndex); m_pMsgParserCommand = strtok_r(ptr, " ", &rest); m_pRead = rest; uint8_t i = 0; while( (msgFound == false) && (i < m_funcTableLength) ) { memcpy_P( &m_bufStruct, &(m_pFuncTable[i]), sizeof(m_bufStruct) ); if ( strcmp_P( m_pMsgParserCommand, m_bufStruct.pCmdString ) == 0) { msgFound = true; } else { ++i; } } if(i < m_funcTableLength) { (*m_bufStruct.pFunc)(); } else { if(m_pCmdNotFoundFunc != NULL) { (*m_pCmdNotFoundFunc)((uint8_t*)m_pOrigMsg, m_BufferWriteIndex); } else { } } clearTheBuffer(); } else { m_pInputBuffer[m_BufferWriteIndex] = newByte; m_BufferWriteIndex++; if(m_BufferWriteIndex == MSGPARSER_INPUT_BUFFER_SIZE) { clearTheBuffer(); if(m_useStartByte == true) { m_state = WAITING_FOR_START_BYTE; } else { m_state = READING_MESSAGE; } } else { } } break; default: break; } } void MsgParser::setEndByte(uint8_t newEndByte) { m_msgEndByte = newEndByte; } long MsgParser::getLong() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atol(numPtr) ); } int MsgParser::getInt() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atoi(numPtr) ); } float MsgParser::getFloat() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atof(numPtr) ); } void MsgParser::clearTheBuffer() { m_BufferWriteIndex = 0; m_pRead = m_pInputBuffer; memset(m_pInputBuffer, NULL, MSGPARSER_INPUT_BUFFER_SIZE); } uint8_t MsgParser::numCmds() { return m_funcTableLength; } char* MsgParser::cmdString(uint8_t cmdIndex) { if(cmdIndex >= numCmds()) { return NULL; } memcpy_P( &m_bufStruct, &(m_pFuncTable[cmdIndex]), sizeof(m_bufStruct) ); memcpy_P( m_pDescBuf, m_bufStruct.pCmdString, MSGPARSER_DESCRIPTION_SIZE); return m_pDescBuf; } char* MsgParser::cmdDesc(uint8_t cmdIndex) { if(cmdIndex >= numCmds()) { return NULL; } memcpy_P( &m_bufStruct, &(m_pFuncTable[cmdIndex]), sizeof(m_bufStruct) ); if(m_bufStruct.pDescString != NULL) { memcpy_P( m_pDescBuf, m_bufStruct.pDescString, MSGPARSER_DESCRIPTION_SIZE); return m_pDescBuf; } else { return NULL; } } uint8_t MsgParser::version() { return 0x05; }
#include <avr/pgmspace.h> #include <inttypes.h> #include <string.h> #include <stdlib.h> #include "MsgParser.h" MsgParser::MsgParser() { m_BufferWriteIndex = 0; m_pRead = m_pInputBuffer; m_pMsgParserCommand = NULL; m_msgStartByte = '/'; m_msgEndByte = '\r'; m_useStartByte = false; m_state = WAITING_FOR_START_BYTE; m_pFuncTable = NULL; m_funcTableLength = 0; m_pCmdNotFoundFunc = NULL; memset(m_pInputBuffer, NULL, MSGPARSER_INPUT_BUFFER_SIZE); memset(m_pDescBuf, NULL, MSGPARSER_DESCRIPTION_SIZE); useStartByteSet(m_useStartByte); } void MsgParser::setTable(const FuncEntry_t* newFunctTable, uint8_t newFunctTableLength) { if(newFunctTable != NULL) { m_pFuncTable = (FuncEntry_t*)newFunctTable; m_funcTableLength = newFunctTableLength; } } void MsgParser::useStartByteSet(bool newStatus) { m_useStartByte = newStatus; if( (m_state == WAITING_FOR_START_BYTE) && (m_useStartByte == false) ) { m_state = READING_MESSAGE; } else { } } void MsgParser::setHandlerForCmdNotFound(cmdNotFoundHandler_t pNewHandlerFunc) { m_pCmdNotFoundFunc = pNewHandlerFunc; } void MsgParser::processByte(uint8_t newByte) { switch (m_state) { case WAITING_FOR_START_BYTE: if( newByte == m_msgStartByte ) { m_state = READING_MESSAGE; } else { } break; case READING_MESSAGE: if( newByte == m_msgEndByte ) { if(m_useStartByte == true) m_state = WAITING_FOR_START_BYTE; bool msgFound = false; char *ptr = m_pRead; char *rest; memcpy(m_pOrigMsg, m_pInputBuffer, m_BufferWriteIndex); m_pMsgParserCommand = strtok_r(ptr, " ", &rest); m_pRead = rest; uint8_t i = 0; while( (msgFound == false) && (i < m_funcTableLength) ) { memcpy_P( &m_bufStruct, &(m_pFuncTable[i]), sizeof(m_bufStruct) ); if ( strcmp_P( m_pMsgParserCommand, m_bufStruct.pCmdString ) == 0) { msgFound = true; } else { ++i; } } if(i < m_funcTableLength) { (*m_bufStruct.pFunc)(); } else { if(m_pCmdNotFoundFunc != NULL) { (*m_pCmdNotFoundFunc)((uint8_t*)m_pOrigMsg, m_BufferWriteIndex); } else {
e == true) { m_state = WAITING_FOR_START_BYTE; } else { m_state = READING_MESSAGE; } } else { } } break; default: break; } } void MsgParser::setEndByte(uint8_t newEndByte) { m_msgEndByte = newEndByte; } long MsgParser::getLong() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atol(numPtr) ); } int MsgParser::getInt() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atoi(numPtr) ); } float MsgParser::getFloat() { char *numPtr; char *ptr = m_pRead; char *rest; numPtr = strtok_r(ptr, " ", &rest); m_pRead = rest; return( atof(numPtr) ); } void MsgParser::clearTheBuffer() { m_BufferWriteIndex = 0; m_pRead = m_pInputBuffer; memset(m_pInputBuffer, NULL, MSGPARSER_INPUT_BUFFER_SIZE); } uint8_t MsgParser::numCmds() { return m_funcTableLength; } char* MsgParser::cmdString(uint8_t cmdIndex) { if(cmdIndex >= numCmds()) { return NULL; } memcpy_P( &m_bufStruct, &(m_pFuncTable[cmdIndex]), sizeof(m_bufStruct) ); memcpy_P( m_pDescBuf, m_bufStruct.pCmdString, MSGPARSER_DESCRIPTION_SIZE); return m_pDescBuf; } char* MsgParser::cmdDesc(uint8_t cmdIndex) { if(cmdIndex >= numCmds()) { return NULL; } memcpy_P( &m_bufStruct, &(m_pFuncTable[cmdIndex]), sizeof(m_bufStruct) ); if(m_bufStruct.pDescString != NULL) { memcpy_P( m_pDescBuf, m_bufStruct.pDescString, MSGPARSER_DESCRIPTION_SIZE); return m_pDescBuf; } else { return NULL; } } uint8_t MsgParser::version() { return 0x05; }
} } clearTheBuffer(); } else { m_pInputBuffer[m_BufferWriteIndex] = newByte; m_BufferWriteIndex++; if(m_BufferWriteIndex == MSGPARSER_INPUT_BUFFER_SIZE) { clearTheBuffer(); if(m_useStartByt
random
[ { "content": " const char* pCmdString; //pointer to a null terminated char array\n\n const char* pDescString; //Short help text about this command. Pointer to a null terminated char array\n\n FuncPtr_t pFunc; //pointer to a function\n\n\n\n}FuncEntry_t;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "file_...
C++
ModelsAPI/DependentValues.cpp
FlowsheetSimulation/Dyssol-open
557d57d959800868e1b3fd161b26cad16481382b
#include "DependentValues.h" #include "ContainerFunctions.h" #include "StringFunctions.h" #include <ostream> #include <sstream> #include <numeric> CDependentValues::CDependentValues(const std::vector<double>& _params, const std::vector<double>& _values) { SetValues(_params, _values); } bool CDependentValues::IsEmpty() const { return m_values.empty(); } size_t CDependentValues::Size() const { return m_values.size(); } double CDependentValues::GetValue(double _param) const { if (m_values.empty()) return 0; if (m_values.size() == 1) return m_values.front(); return Interpolate(_param); } void CDependentValues::SetValue(double _param, double _value) { const auto pos = std::lower_bound(m_params.begin(), m_params.end(), _param); if (pos == m_params.end()) { m_values.emplace_back(_value); m_params.emplace_back(_param); } else if (std::abs(*pos - _param) <= m_eps) { m_values[std::distance(m_params.begin(), pos)] = _value; *pos = _param; } else { m_values.insert(m_values.begin() + std::distance(m_params.begin(), pos), _value); m_params.insert(pos, _param); } } void CDependentValues::SetValues(const std::vector<double>& _params, const std::vector<double>& _values) { if (m_params.size() != m_values.size()) return; if (IsEmpty()) { m_params = _params; m_values = _values; } else for (size_t i = 0; i < _params.size(); ++i) SetValue(_params[i], _values[i]); } void CDependentValues::RemoveValue(double _param) { const auto pos = std::lower_bound(m_params.begin(), m_params.end(), _param); if (pos != m_params.end() && std::abs(*pos - _param) <= m_eps) { m_values.erase(m_values.begin() + std::distance(m_params.begin(), pos)); m_params.erase(pos); } } double CDependentValues::GetParamAt(size_t _index) const { if (_index >= m_params.size()) return {}; return m_params[_index]; } double CDependentValues::GetValueAt(size_t _index) const { if (_index >= m_values.size()) return {}; return m_values[_index]; } std::pair<double, double> CDependentValues::GetPairAt(size_t _index) const { if (_index >= m_values.size()) return {}; return { m_params[_index], m_values[_index] }; } void CDependentValues::RemovePairAt(size_t _index) { if (_index >= m_values.size()) return; m_params.erase(m_params.begin() + _index); m_values.erase(m_values.begin() + _index); } std::vector<double> CDependentValues::GetParamsList() const { return m_params; } std::vector<double> CDependentValues::GetValuesList() const { return m_values; } void CDependentValues::SetParamsList(const std::vector<double>& _params) { if (_params.size() == m_params.size()) m_params = VectorSort(_params); } void CDependentValues::SetValuesList(const std::vector<double>& _values) { if (_values.size() == m_values.size()) m_values = _values; } bool CDependentValues::HasParam(double _param) const { return VectorContainsSorted(m_params, _param); } bool CDependentValues::IsConst() const { if (m_values.empty()) return true; return std::adjacent_find(m_values.begin(), m_values.end(), std::not_equal_to<>()) == m_values.end(); } void CDependentValues::Clear() { m_params.clear(); m_values.clear(); } bool CDependentValues::operator==(const CDependentValues& _v) const { return m_params == _v.m_params && m_values == _v.m_values; } double CDependentValues::Interpolate(double _param) const { const auto upper = std::upper_bound(m_params.begin(), m_params.end(), _param); if (upper == m_params.end()) return m_values.back(); if (upper == m_params.begin()) return m_values.front(); auto lower = upper; --lower; const double upar = *upper; const double lpar = *lower; const double uval = m_values[std::distance(m_params.begin(), upper)]; const double lval = m_values[std::distance(m_params.begin(), lower)]; if (std::abs(upar - _param) <= m_eps) return uval; if (std::abs(lpar - _param) <= m_eps) return lval; return (uval - lval) / (upar - lpar) * (_param - lpar) + lval; } std::ostream& operator<<(std::ostream& _s, const CDependentValues& _obj) { for (size_t i = 0; i < _obj.Size(); ++i) _s << " " << _obj.GetParamAt(i) << " " << _obj.GetValueAt(i); return _s; } std::istream& operator>>(std::istream& _s, CDependentValues& _obj) { _obj.Clear(); const auto timeOrValue = StringFunctions::GetValueFromStream<double>(_s); if (_s.eof()) _obj.SetValue(0.0, timeOrValue); else { _obj.SetValue(timeOrValue, StringFunctions::GetValueFromStream<double>(_s)); while (!_s.eof()) { const auto param = StringFunctions::GetValueFromStream<double>(_s); const auto value = StringFunctions::GetValueFromStream<double>(_s); _obj.SetValue(param, value); } } return _s; }
#include "DependentValues.h" #include "ContainerFunctions.h" #include "StringFunctions.h" #include <ostream> #include <sstream> #include <numeric> CDependentValues::CDependentValues(const std::vector<double>& _params, const std::vector<double>& _values) { SetValues(_params, _values); } bool CDependentValues::IsEmpty() const { return m_values.empty(); } size_t CDependentValues::Size() const { return m_values.size(); } double CDependentValues::GetValue(double _param) const { if (m_values.empty()) return 0; if (m_values.size() == 1) return m_values.front(); return Interpolate(_param); } void CDependentValues::SetValue(double _param, double _value) { const auto pos = std::lower_bound(m_params.begin(), m_params.end(), _param); if (pos == m_params.end()) { m_values.emplace_back(_value); m_params.emplace_back(_param); } else if (std::abs(*pos - _param) <= m_eps) { m_values[std::distance(m_params.begin(), pos)] = _value; *pos = _param; } else { m_values.insert(m_values.begin() + std::distance(m_params.begin(), pos), _value); m_params.insert(pos, _param); } } void CDependentValues::SetValues(const std::vector<double>& _params, const std::vector<double>& _values) { if (m_params.size() != m_values.size()) return; if (IsEmpty()) { m_params = _params; m_values = _values; } else for (size_t i = 0; i < _params.size(); ++i) SetValue(_params[i], _values[i]); } void CDependentValues::RemoveValue(double _param) { const auto pos = std::lower_bound(m_params.begin(), m_params.end(), _param); if (pos != m_params.end() && std::abs(*pos - _param) <= m_eps) { m_values.erase(m_values.be
irAt(size_t _index) { if (_index >= m_values.size()) return; m_params.erase(m_params.begin() + _index); m_values.erase(m_values.begin() + _index); } std::vector<double> CDependentValues::GetParamsList() const { return m_params; } std::vector<double> CDependentValues::GetValuesList() const { return m_values; } void CDependentValues::SetParamsList(const std::vector<double>& _params) { if (_params.size() == m_params.size()) m_params = VectorSort(_params); } void CDependentValues::SetValuesList(const std::vector<double>& _values) { if (_values.size() == m_values.size()) m_values = _values; } bool CDependentValues::HasParam(double _param) const { return VectorContainsSorted(m_params, _param); } bool CDependentValues::IsConst() const { if (m_values.empty()) return true; return std::adjacent_find(m_values.begin(), m_values.end(), std::not_equal_to<>()) == m_values.end(); } void CDependentValues::Clear() { m_params.clear(); m_values.clear(); } bool CDependentValues::operator==(const CDependentValues& _v) const { return m_params == _v.m_params && m_values == _v.m_values; } double CDependentValues::Interpolate(double _param) const { const auto upper = std::upper_bound(m_params.begin(), m_params.end(), _param); if (upper == m_params.end()) return m_values.back(); if (upper == m_params.begin()) return m_values.front(); auto lower = upper; --lower; const double upar = *upper; const double lpar = *lower; const double uval = m_values[std::distance(m_params.begin(), upper)]; const double lval = m_values[std::distance(m_params.begin(), lower)]; if (std::abs(upar - _param) <= m_eps) return uval; if (std::abs(lpar - _param) <= m_eps) return lval; return (uval - lval) / (upar - lpar) * (_param - lpar) + lval; } std::ostream& operator<<(std::ostream& _s, const CDependentValues& _obj) { for (size_t i = 0; i < _obj.Size(); ++i) _s << " " << _obj.GetParamAt(i) << " " << _obj.GetValueAt(i); return _s; } std::istream& operator>>(std::istream& _s, CDependentValues& _obj) { _obj.Clear(); const auto timeOrValue = StringFunctions::GetValueFromStream<double>(_s); if (_s.eof()) _obj.SetValue(0.0, timeOrValue); else { _obj.SetValue(timeOrValue, StringFunctions::GetValueFromStream<double>(_s)); while (!_s.eof()) { const auto param = StringFunctions::GetValueFromStream<double>(_s); const auto value = StringFunctions::GetValueFromStream<double>(_s); _obj.SetValue(param, value); } } return _s; }
gin() + std::distance(m_params.begin(), pos)); m_params.erase(pos); } } double CDependentValues::GetParamAt(size_t _index) const { if (_index >= m_params.size()) return {}; return m_params[_index]; } double CDependentValues::GetValueAt(size_t _index) const { if (_index >= m_values.size()) return {}; return m_values[_index]; } std::pair<double, double> CDependentValues::GetPairAt(size_t _index) const { if (_index >= m_values.size()) return {}; return { m_params[_index], m_values[_index] }; } void CDependentValues::RemovePa
random
[ { "content": "// Description of a constant property of a pure compound.\n\nclass CConstProperty : public CBaseProperty\n\n{\n\n\tdouble m_defaultValue;\t// Default value.\n\n\tdouble m_dValue;\t\t// Current value of the constant property.\n\n\n\npublic:\n\n\tCConstProperty(unsigned _nProperty, const std::string...
C++
frameworks/base/media/agifencoder/jni/agifencoder_jni.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
#include <jni.h> #include <utils/Log.h> #include <stdio.h> #include <stdlib.h> #include "SkBitmap.h" #include "GraphicsJNI.h" #include "SkPixelRef.h" #include <cutils/xlog.h> #define LOG_TAG "AGIF_ENCODER_JNI" #if 0 #include "SkMovie.h" #include "SkStream.h" #include "GraphicsJNI.h" #include "SkTemplates.h" #include "SkUtils.h" #endif #include "AGifEncoder.h" #include <androidfw/Asset.h> #include <androidfw/ResourceTypes.h> #include <netinet/in.h> #include "utils/Log.h" static jmethodID gOutputStream_writeMethodID; static jmethodID gOutputStream_flushMethodID; #define RETURN_NULL_IF_NULL(value) \ do { if (!(value)) { SkASSERT(0); return NULL; } } while (false) class GifSkJavaOutputStream : public SkWStream { public: GifSkJavaOutputStream(JNIEnv* env, jobject stream, jbyteArray storage) : fEnv(env), fJavaOutputStream(stream), fJavaByteArray(storage) { fCapacity = env->GetArrayLength(storage); } virtual bool write(const void* buffer, size_t size) { JNIEnv* env = fEnv; jbyteArray storage = fJavaByteArray; while (size > 0) { size_t requested = size; if (requested > fCapacity) { requested = fCapacity; } env->SetByteArrayRegion(storage, 0, requested, reinterpret_cast<const jbyte*>(buffer)); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); SkDebugf("--- write:SetByteArrayElements threw an exception\n"); return false; } fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_writeMethodID, storage, 0, requested); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); SkDebugf("------- write threw an exception\n"); return false; } buffer = (void*)((char*)buffer + requested); size -= requested; } return true; } virtual void flush() { fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_flushMethodID); } private: JNIEnv* fEnv; jobject fJavaOutputStream; jbyteArray fJavaByteArray; size_t fCapacity; }; SkWStream* GifCreateJavaOutputStreamAdaptor(JNIEnv* env, jobject stream, jbyteArray storage) { static bool gInited; if (!gInited) { XLOGI("AGIFE::GifCreateJavaOutputStreamAdaptor Init %d, go L:%d!!\n",gInited, __LINE__); jclass outputStream_Clazz = env->FindClass("java/io/OutputStream"); RETURN_NULL_IF_NULL(outputStream_Clazz); gOutputStream_writeMethodID = env->GetMethodID(outputStream_Clazz, "write", "([BII)V"); RETURN_NULL_IF_NULL(gOutputStream_writeMethodID); gOutputStream_flushMethodID = env->GetMethodID(outputStream_Clazz, "flush", "()V"); RETURN_NULL_IF_NULL(gOutputStream_flushMethodID); gInited = true; } return new GifSkJavaOutputStream(env, stream, storage); } static jclass gAGifEncoder_class; static jmethodID gAGifEncoder_constructorMethodID; static jfieldID gAGifEncoder_nativeInstanceID; jobject create_jmovie(JNIEnv* env, AGifEncoder* encoder, int width, int height) { if (NULL == encoder) { XLOGI("AGIFE::create_jmovie create fail, go L:%d!!\n", __LINE__); return NULL; } #if 1 jobject obj = env->AllocObject(gAGifEncoder_class); if (obj) { env->CallVoidMethod(obj, gAGifEncoder_constructorMethodID, (jint)encoder, (jint)width, (jint)height ); } return obj; #else return env->NewObject(gAGifEncoder_class, gAGifEncoder_constructorMethodID, static_cast<jint>(reinterpret_cast<uintptr_t>(encoder))); #endif } static AGifEncoder* J2AGifEncoder(JNIEnv* env, jobject movie) { SkASSERT(env); SkASSERT(movie); SkASSERT(env->IsInstanceOf(movie, gAGifEncoder_class)); AGifEncoder* m = (AGifEncoder*)env->GetIntField(movie, gAGifEncoder_nativeInstanceID); SkASSERT(m); XLOGI("AGIFE::J2AGifEncoder get encoder %x->%x, go L:%d!!\n", (unsigned int)movie, (unsigned int)m,__LINE__); return m; } static int agifenc_width(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_width, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->width(); else return 0 ; } static int agifenc_height(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_height, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->height(); else return 0 ; } static int agifenc_duration(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_duration, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->duration(); else return 0 ; } static jboolean agifenc_setDuration(JNIEnv* env, jobject movie, AGifEncoder* enc, int ms) { XLOGI("AGIFE::agifenc_setDuration, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc!=NULL) return enc->setFrameDuration(ms); else return false ; } static jboolean agifenc_setWidth(JNIEnv* env, jobject movie, int width) { XLOGI("AGIFE::agifenc_setWidth, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->setWidth(width); } static jboolean agifenc_setHeight(JNIEnv* env, jobject movie, int height) { XLOGI("AGIFE::agifenc_setHeight, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->setHeight(height); } static jboolean agifenc_gifFrameBitmap(JNIEnv* env, jobject movie, AGifEncoder* enc, jintArray pixelArray, jobject jstream, jbyteArray jstorage) { bool ret = false ; jint* dst = env->GetIntArrayElements(pixelArray, NULL); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if(dst == NULL){ XLOGI("AGIFE::agifenc_gifFrameBitmap NULL bitmap, go L:%d!!\n",__LINE__); return false; } if(strm != NULL){ XLOGI("AGIFE::agifenc_gifFrameBitmap %x, go L:%d!!\n", dst,__LINE__); ret = enc->encodeBitmap((unsigned char *)dst, strm); env->ReleaseIntArrayElements(pixelArray, dst, 0); delete strm; } return ret ; } static jobject agifenc_CreateAGifEncoder(JNIEnv* env, jobject movie, int width, int height, jobject jstream, jbyteArray jstorage) { jobject obj ; XLOGI("AGIFE::agifenc_CreateAGifEncoder, go L:%d!!\n", __LINE__); AGifEncoder* encoder = new AGifEncoder(); encoder->setWidth(width); encoder->setHeight(height); encoder->setFrameDuration(100); obj = create_jmovie(env, encoder, width, height); { #if 0 NPE_CHECK_RETURN_ZERO(env, obj); XLOGI("AGIFE::create_jmovie check encoder, go L:%d!!\n", __LINE__); AGifEncoder* m = J2AGifEncoder(env, obj); XLOGI("AGIFE::create_jmovie check encoder %x, go L:%d!!\n", (unsigned int)m,__LINE__); #endif } XLOGI("AGIFE::create_jmovie check obj %x, go L:%d!!\n", (unsigned int)obj,__LINE__); return obj ; } static jobject agifenc_CreateEncoder(JNIEnv* env, jobject movie, int width, int height, jobject jstream, jbyteArray jstorage) { jobject obj ; AGifEncoder* encoder = new AGifEncoder(); XLOGI("AGIFE::create_jmovie encoder %x, go L:%d!!\n", encoder,__LINE__); encoder->setWidth(width); encoder->setHeight(height); encoder->setFrameDuration(100); obj = create_jmovie(env, encoder, width,height); #if 0 { NPE_CHECK_RETURN_ZERO(env, obj); XLOGI("AGIFE::create_jmovie check encoder, go L:%d!!\n", __LINE__); AGifEncoder* m = J2AGifEncoder(env, obj); XLOGI("AGIFE::create_jmovie check encoder %x, go L:%d!!\n", (unsigned int)m,__LINE__); } #endif return obj ; } static jboolean agifenc_setOutputStream(JNIEnv* env, jobject movie, AGifEncoder* enc, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_setOutputStream obj %x, enc %x, go L:%d!!\n",movie, enc,__LINE__); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if (NULL != strm) { XLOGI("AGIFE::setOutputStream encoder %x, go L:%d!!\n", (unsigned int)enc,__LINE__); enc->setEncodeStream(strm); delete strm; return true ; } return true ; } static int agifenc_encodeFrameCount(JNIEnv* env, jobject movie) { XLOGI("AGIFE::agifenc_encodeFrameCount, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->getGifTotalFrameCount(); } static void agifenc_closeGif(JNIEnv* env, jobject movie, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_closeGif, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_VOID(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if (NULL != strm) { m->setEncodeStream(strm); m->closeGif(); delete strm; delete m; } } static void agifenc_closeStream(JNIEnv* env, jobject movie, AGifEncoder* enc, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_closeStream, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_VOID(env, movie); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if(enc != NULL){ XLOGI("AGIFE::agifenc_closeStream stream %x, go L:%d!!\n", (unsigned int)enc,__LINE__); enc->setEncodeStream(strm); enc->closeGif(); delete enc; } if (NULL != strm){ delete strm; } env->SetIntField(movie,gAGifEncoder_nativeInstanceID,0); } static void agifenc_destructor(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_destructor, go L:%d!!\n", __LINE__); if(enc != NULL){ XLOGI("AGIFE::agifenc_destructor delete encoder %x, go L:%d!!\n", (unsigned int)enc,__LINE__); delete enc; } env->SetIntField(movie,gAGifEncoder_nativeInstanceID,0); } #include <android_runtime/AndroidRuntime.h> static JNINativeMethod gMethods[] = { { "nativeWidth" , "(I)I", (void*)agifenc_width }, { "nativeHeight" , "(I)I", (void*)agifenc_height }, { "nativeDuration" , "(I)I", (void*)agifenc_duration }, { "nativeSetDuration" , "(II)Z", (void*)agifenc_setDuration }, { "nativeEncodeFrameCount" , "()I", (void*)agifenc_encodeFrameCount }, { "nativeEncodeBitmap" , "(I[ILjava/io/OutputStream;[B)Z", (void*)agifenc_gifFrameBitmap }, { "nativeCloseStream" , "(ILjava/io/OutputStream;[B)Z" , (void*)agifenc_closeStream }, { "nativeCloseGif" , "(Ljava/io/OutputStream;[B)Z" , (void*)agifenc_closeGif }, { "nativeDestructor" , "(I)V", (void*)agifenc_destructor }, { "nativeSetOutputStream" , "(ILjava/io/OutputStream;[B)Z", (void*)agifenc_setOutputStream }, { "nativeCreateEncoder" , "(IILjava/io/OutputStream;[B)Lcom/mediatek/agifencoder/AGifEncoder;", (void*)agifenc_CreateEncoder }, { "nativeCreateAGifEncoder" , "(II)Lcom/mediatek/agifencoder/AGifEncoder;", (void*)agifenc_CreateAGifEncoder }, }; static const char *kClassPathName = "com/mediatek/agifencoder/AGifEncoder"; #define RETURN_ERR_IF_NULL(value) do { if (!(value)) { assert(0); return -1; } } while (false) static int registerNativeMethods(JNIEnv* env, const char* className, JNINativeMethod* gMethods, int numMethods) { jclass clazz; XLOGI("JNI_register, go L:%d!!\n", __LINE__); clazz = env->FindClass(className); if (clazz == NULL) { XLOGE("Native registration unable to find class '%s'", className); return JNI_FALSE; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { XLOGE("RegisterNatives failed for '%s'", className); return JNI_FALSE; } return JNI_TRUE; } int register_android_graphics_AGifEncoder(JNIEnv* env); int register_android_graphics_AGifEncoder(JNIEnv* env) { XLOGI("JNI_register, go L:%d!!\n", __LINE__); gAGifEncoder_class = env->FindClass(kClassPathName); RETURN_ERR_IF_NULL(gAGifEncoder_class); gAGifEncoder_class = (jclass)env->NewGlobalRef(gAGifEncoder_class); gAGifEncoder_constructorMethodID = env->GetMethodID(gAGifEncoder_class, "<init>", "(III)V"); RETURN_ERR_IF_NULL(gAGifEncoder_constructorMethodID); gAGifEncoder_nativeInstanceID = env->GetFieldID(gAGifEncoder_class, "mNativeAGifEncoder", "I"); RETURN_ERR_IF_NULL(gAGifEncoder_nativeInstanceID); if (!registerNativeMethods(env, kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0])) ) { return JNI_FALSE; } XLOGI("JNI_register, go L:%d!!\n", __LINE__); return JNI_TRUE ; } typedef union { JNIEnv* env; void* venv; } UnionJNIEnvToVoid; jint JNI_OnLoad(JavaVM* vm, void* reserved) { UnionJNIEnvToVoid uenv; uenv.venv = NULL; jint result = -1; JNIEnv* env = NULL; XLOGI("JNI_OnLoad"); if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) { XLOGE("ERROR: GetEnv failed"); goto bail; } env = uenv.env; if (register_android_graphics_AGifEncoder(env) != JNI_TRUE) { XLOGE("ERROR: registerNatives failed"); goto bail; } result = JNI_VERSION_1_4; bail: return result; }
#include <jni.h> #include <utils/Log.h> #include <stdio.h> #include <stdlib.h> #include "SkBitmap.h" #include "GraphicsJNI.h" #include "SkPixelRef.h" #include <cutils/xlog.h> #define LOG_TAG "AGIF_ENCODER_JNI" #if 0 #include "SkMovie.h" #include "SkStream.h" #include "GraphicsJNI.h" #include "SkTemplates.h" #include "SkUtils.h" #endif #include "AGifEncoder.h" #include <androidfw/Asset.h> #include <androidfw/ResourceTypes.h> #include <netinet/in.h> #include "utils/Log.h" static jmethodID gOutputStream_writeMethodID; static jmethodID gOutputStream_flushMethodID; #define RETURN_NULL_IF_NULL(value) \ do { if (!(value)) { SkASSERT(0); return NULL; } } while (false) class GifSkJavaOutputStream : public SkWStream { public: GifSkJavaOutputStream(JNIEnv* env, jobject stream, jbyteArray storage) : fEnv(env), fJavaOutputStream(stream), fJavaByteArray(storage) { fCapacity = env->GetArrayLength(storage); } virtual bool write(const void* buffer, size_t size) { JNIEnv* env = fEnv; jbyteArray storage = fJavaByteArray; while (size > 0) { size_t requested = size; if (requested > fCapacity) { requested = fCapacity; } env->SetByteArrayRegion(storage, 0, requested, reinterpret_cast<const jbyte*>(buffer)); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->Ex
m; return true ; } return true ; } static int agifenc_encodeFrameCount(JNIEnv* env, jobject movie) { XLOGI("AGIFE::agifenc_encodeFrameCount, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->getGifTotalFrameCount(); } static void agifenc_closeGif(JNIEnv* env, jobject movie, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_closeGif, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_VOID(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if (NULL != strm) { m->setEncodeStream(strm); m->closeGif(); delete strm; delete m; } } static void agifenc_closeStream(JNIEnv* env, jobject movie, AGifEncoder* enc, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_closeStream, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_VOID(env, movie); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if(enc != NULL){ XLOGI("AGIFE::agifenc_closeStream stream %x, go L:%d!!\n", (unsigned int)enc,__LINE__); enc->setEncodeStream(strm); enc->closeGif(); delete enc; } if (NULL != strm){ delete strm; } env->SetIntField(movie,gAGifEncoder_nativeInstanceID,0); } static void agifenc_destructor(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_destructor, go L:%d!!\n", __LINE__); if(enc != NULL){ XLOGI("AGIFE::agifenc_destructor delete encoder %x, go L:%d!!\n", (unsigned int)enc,__LINE__); delete enc; } env->SetIntField(movie,gAGifEncoder_nativeInstanceID,0); } #include <android_runtime/AndroidRuntime.h> static JNINativeMethod gMethods[] = { { "nativeWidth" , "(I)I", (void*)agifenc_width }, { "nativeHeight" , "(I)I", (void*)agifenc_height }, { "nativeDuration" , "(I)I", (void*)agifenc_duration }, { "nativeSetDuration" , "(II)Z", (void*)agifenc_setDuration }, { "nativeEncodeFrameCount" , "()I", (void*)agifenc_encodeFrameCount }, { "nativeEncodeBitmap" , "(I[ILjava/io/OutputStream;[B)Z", (void*)agifenc_gifFrameBitmap }, { "nativeCloseStream" , "(ILjava/io/OutputStream;[B)Z" , (void*)agifenc_closeStream }, { "nativeCloseGif" , "(Ljava/io/OutputStream;[B)Z" , (void*)agifenc_closeGif }, { "nativeDestructor" , "(I)V", (void*)agifenc_destructor }, { "nativeSetOutputStream" , "(ILjava/io/OutputStream;[B)Z", (void*)agifenc_setOutputStream }, { "nativeCreateEncoder" , "(IILjava/io/OutputStream;[B)Lcom/mediatek/agifencoder/AGifEncoder;", (void*)agifenc_CreateEncoder }, { "nativeCreateAGifEncoder" , "(II)Lcom/mediatek/agifencoder/AGifEncoder;", (void*)agifenc_CreateAGifEncoder }, }; static const char *kClassPathName = "com/mediatek/agifencoder/AGifEncoder"; #define RETURN_ERR_IF_NULL(value) do { if (!(value)) { assert(0); return -1; } } while (false) static int registerNativeMethods(JNIEnv* env, const char* className, JNINativeMethod* gMethods, int numMethods) { jclass clazz; XLOGI("JNI_register, go L:%d!!\n", __LINE__); clazz = env->FindClass(className); if (clazz == NULL) { XLOGE("Native registration unable to find class '%s'", className); return JNI_FALSE; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { XLOGE("RegisterNatives failed for '%s'", className); return JNI_FALSE; } return JNI_TRUE; } int register_android_graphics_AGifEncoder(JNIEnv* env); int register_android_graphics_AGifEncoder(JNIEnv* env) { XLOGI("JNI_register, go L:%d!!\n", __LINE__); gAGifEncoder_class = env->FindClass(kClassPathName); RETURN_ERR_IF_NULL(gAGifEncoder_class); gAGifEncoder_class = (jclass)env->NewGlobalRef(gAGifEncoder_class); gAGifEncoder_constructorMethodID = env->GetMethodID(gAGifEncoder_class, "<init>", "(III)V"); RETURN_ERR_IF_NULL(gAGifEncoder_constructorMethodID); gAGifEncoder_nativeInstanceID = env->GetFieldID(gAGifEncoder_class, "mNativeAGifEncoder", "I"); RETURN_ERR_IF_NULL(gAGifEncoder_nativeInstanceID); if (!registerNativeMethods(env, kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0])) ) { return JNI_FALSE; } XLOGI("JNI_register, go L:%d!!\n", __LINE__); return JNI_TRUE ; } typedef union { JNIEnv* env; void* venv; } UnionJNIEnvToVoid; jint JNI_OnLoad(JavaVM* vm, void* reserved) { UnionJNIEnvToVoid uenv; uenv.venv = NULL; jint result = -1; JNIEnv* env = NULL; XLOGI("JNI_OnLoad"); if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) { XLOGE("ERROR: GetEnv failed"); goto bail; } env = uenv.env; if (register_android_graphics_AGifEncoder(env) != JNI_TRUE) { XLOGE("ERROR: registerNatives failed"); goto bail; } result = JNI_VERSION_1_4; bail: return result; }
ceptionClear(); SkDebugf("--- write:SetByteArrayElements threw an exception\n"); return false; } fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_writeMethodID, storage, 0, requested); if (env->ExceptionCheck()) { env->ExceptionDescribe(); env->ExceptionClear(); SkDebugf("------- write threw an exception\n"); return false; } buffer = (void*)((char*)buffer + requested); size -= requested; } return true; } virtual void flush() { fEnv->CallVoidMethod(fJavaOutputStream, gOutputStream_flushMethodID); } private: JNIEnv* fEnv; jobject fJavaOutputStream; jbyteArray fJavaByteArray; size_t fCapacity; }; SkWStream* GifCreateJavaOutputStreamAdaptor(JNIEnv* env, jobject stream, jbyteArray storage) { static bool gInited; if (!gInited) { XLOGI("AGIFE::GifCreateJavaOutputStreamAdaptor Init %d, go L:%d!!\n",gInited, __LINE__); jclass outputStream_Clazz = env->FindClass("java/io/OutputStream"); RETURN_NULL_IF_NULL(outputStream_Clazz); gOutputStream_writeMethodID = env->GetMethodID(outputStream_Clazz, "write", "([BII)V"); RETURN_NULL_IF_NULL(gOutputStream_writeMethodID); gOutputStream_flushMethodID = env->GetMethodID(outputStream_Clazz, "flush", "()V"); RETURN_NULL_IF_NULL(gOutputStream_flushMethodID); gInited = true; } return new GifSkJavaOutputStream(env, stream, storage); } static jclass gAGifEncoder_class; static jmethodID gAGifEncoder_constructorMethodID; static jfieldID gAGifEncoder_nativeInstanceID; jobject create_jmovie(JNIEnv* env, AGifEncoder* encoder, int width, int height) { if (NULL == encoder) { XLOGI("AGIFE::create_jmovie create fail, go L:%d!!\n", __LINE__); return NULL; } #if 1 jobject obj = env->AllocObject(gAGifEncoder_class); if (obj) { env->CallVoidMethod(obj, gAGifEncoder_constructorMethodID, (jint)encoder, (jint)width, (jint)height ); } return obj; #else return env->NewObject(gAGifEncoder_class, gAGifEncoder_constructorMethodID, static_cast<jint>(reinterpret_cast<uintptr_t>(encoder))); #endif } static AGifEncoder* J2AGifEncoder(JNIEnv* env, jobject movie) { SkASSERT(env); SkASSERT(movie); SkASSERT(env->IsInstanceOf(movie, gAGifEncoder_class)); AGifEncoder* m = (AGifEncoder*)env->GetIntField(movie, gAGifEncoder_nativeInstanceID); SkASSERT(m); XLOGI("AGIFE::J2AGifEncoder get encoder %x->%x, go L:%d!!\n", (unsigned int)movie, (unsigned int)m,__LINE__); return m; } static int agifenc_width(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_width, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->width(); else return 0 ; } static int agifenc_height(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_height, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->height(); else return 0 ; } static int agifenc_duration(JNIEnv* env, jobject movie, AGifEncoder* enc) { XLOGI("AGIFE::agifenc_duration, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc != NULL) return enc->duration(); else return 0 ; } static jboolean agifenc_setDuration(JNIEnv* env, jobject movie, AGifEncoder* enc, int ms) { XLOGI("AGIFE::agifenc_setDuration, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); if(enc!=NULL) return enc->setFrameDuration(ms); else return false ; } static jboolean agifenc_setWidth(JNIEnv* env, jobject movie, int width) { XLOGI("AGIFE::agifenc_setWidth, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->setWidth(width); } static jboolean agifenc_setHeight(JNIEnv* env, jobject movie, int height) { XLOGI("AGIFE::agifenc_setHeight, go L:%d!!\n", __LINE__); NPE_CHECK_RETURN_ZERO(env, movie); AGifEncoder* m = J2AGifEncoder(env, movie); return m->setHeight(height); } static jboolean agifenc_gifFrameBitmap(JNIEnv* env, jobject movie, AGifEncoder* enc, jintArray pixelArray, jobject jstream, jbyteArray jstorage) { bool ret = false ; jint* dst = env->GetIntArrayElements(pixelArray, NULL); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if(dst == NULL){ XLOGI("AGIFE::agifenc_gifFrameBitmap NULL bitmap, go L:%d!!\n",__LINE__); return false; } if(strm != NULL){ XLOGI("AGIFE::agifenc_gifFrameBitmap %x, go L:%d!!\n", dst,__LINE__); ret = enc->encodeBitmap((unsigned char *)dst, strm); env->ReleaseIntArrayElements(pixelArray, dst, 0); delete strm; } return ret ; } static jobject agifenc_CreateAGifEncoder(JNIEnv* env, jobject movie, int width, int height, jobject jstream, jbyteArray jstorage) { jobject obj ; XLOGI("AGIFE::agifenc_CreateAGifEncoder, go L:%d!!\n", __LINE__); AGifEncoder* encoder = new AGifEncoder(); encoder->setWidth(width); encoder->setHeight(height); encoder->setFrameDuration(100); obj = create_jmovie(env, encoder, width, height); { #if 0 NPE_CHECK_RETURN_ZERO(env, obj); XLOGI("AGIFE::create_jmovie check encoder, go L:%d!!\n", __LINE__); AGifEncoder* m = J2AGifEncoder(env, obj); XLOGI("AGIFE::create_jmovie check encoder %x, go L:%d!!\n", (unsigned int)m,__LINE__); #endif } XLOGI("AGIFE::create_jmovie check obj %x, go L:%d!!\n", (unsigned int)obj,__LINE__); return obj ; } static jobject agifenc_CreateEncoder(JNIEnv* env, jobject movie, int width, int height, jobject jstream, jbyteArray jstorage) { jobject obj ; AGifEncoder* encoder = new AGifEncoder(); XLOGI("AGIFE::create_jmovie encoder %x, go L:%d!!\n", encoder,__LINE__); encoder->setWidth(width); encoder->setHeight(height); encoder->setFrameDuration(100); obj = create_jmovie(env, encoder, width,height); #if 0 { NPE_CHECK_RETURN_ZERO(env, obj); XLOGI("AGIFE::create_jmovie check encoder, go L:%d!!\n", __LINE__); AGifEncoder* m = J2AGifEncoder(env, obj); XLOGI("AGIFE::create_jmovie check encoder %x, go L:%d!!\n", (unsigned int)m,__LINE__); } #endif return obj ; } static jboolean agifenc_setOutputStream(JNIEnv* env, jobject movie, AGifEncoder* enc, jobject jstream, jbyteArray jstorage) { XLOGI("AGIFE::agifenc_setOutputStream obj %x, enc %x, go L:%d!!\n",movie, enc,__LINE__); SkWStream* strm = GifCreateJavaOutputStreamAdaptor(env, jstream, jstorage); if (NULL != strm) { XLOGI("AGIFE::setOutputStream encoder %x, go L:%d!!\n", (unsigned int)enc,__LINE__); enc->setEncodeStream(strm); delete str
random
[]
C++
src/network-container.cc
imonlius/interactive-neurons
da8cbdad8cf5595a2be1b48125ecad5e6c802f2c
#include "neurons/network-container.h" #include "neurons/utilities.h" namespace neurons { NetworkContainer::NetworkContainer(NodeDeque& nodes, const std::deque<Link>& links) : links_(links) { if (!utilities::NodesAndLinksConsistent(nodes, links)) { throw std::invalid_argument("Passed nodes and links are inconsistent."); } if (utilities::CountConnectedComponents(nodes, links) != 1) { throw std::invalid_argument("Graph does not consist of 1 component."); } if (utilities::ContainsDirectedCycle(nodes, links)) { throw std::invalid_argument("Graph contains a directed cycle."); } if (!utilities::AreNodeInputsSatisfied(nodes, links)) { throw std::invalid_argument("Graph node inputs are not satisfied."); } if (!utilities::AreNodeOutputsSatisfied(nodes, links)) { throw std::invalid_argument("Graph node outputs are not satisfied."); } NodeDeque sorted = utilities::TopologicalSort(nodes, links); data_node_id_ = sorted.front()->GetId(); sorted.pop_front(); loss_node_id_ = sorted.back()->GetId(); sorted.pop_back(); for (auto& node : sorted) { auto module_node = std::dynamic_pointer_cast<ModuleNode>(node); add(module_node); } } std::vector<fl::Variable> Add(const std::vector<fl::Variable>& lhs, const std::vector<fl::Variable>& rhs) { if (lhs.size() != rhs.size()) { throw std::invalid_argument("Vector sizes do not match!"); } std::vector<fl::Variable> result; for (size_t i = 0; i < lhs.size(); ++i) { result.push_back(lhs.at(i) + rhs.at(i)); } return result; } std::vector<fl::Variable> NetworkContainer::forward( const std::vector<fl::Variable>& input) { if (input.size() != 1) { throw std::invalid_argument("Network expects only one input"); } auto output_maps = std::map<fl::ModulePtr, std::vector<fl::Variable>>(); for (const auto& module : modules_) { std::vector<fl::Variable> module_input; for (const auto& link : links_) { if (std::dynamic_pointer_cast<void>(link.output_) != std::dynamic_pointer_cast<void>(module)) { continue; } std::vector<fl::Variable> link_input; if (link.input_->GetId() == data_node_id_) { link_input = input; } else { auto module_ptr = std::dynamic_pointer_cast<fl::Module>(link.input_); if (module_ptr == nullptr) { throw std::runtime_error("Network links are invalid."); } link_input = output_maps.at(module_ptr); } module_input = module_input.empty() ? link_input : Add(module_input, link_input); } auto module_output = module->forward(module_input); output_maps.insert({module, module_output}); } std::vector<fl::Variable> output; for (const auto& link : links_) { if (link.output_->GetId() == loss_node_id_) { auto module_ptr = std::dynamic_pointer_cast<fl::Module>(link.input_); if (module_ptr == nullptr) { throw std::runtime_error("Network container modules are invalid."); } auto link_output = output_maps.at(module_ptr); output = output.empty() ? link_output : Add(output, link_output); } } if (input.size() != output.size()) { throw std::runtime_error("Unexpected container output size."); } return output; } fl::Variable NetworkContainer::forward(const fl::Variable& input) { std::vector<fl::Variable> output = {input}; output = forward(output); return output.front(); } fl::Variable NetworkContainer::operator()(const fl::Variable& input) { return forward(input); } std::string NetworkContainer::prettyString() const { std::ostringstream output; output << "Network:" << std::endl; output << "["; bool first_link = true; for (const auto& link : links_) { if (!first_link) { output << ", "; } else { first_link = false; } if (link.input_->GetId() == data_node_id_) { output << "input"; } else { output << "(" << link.input_->GetId() << ")"; } output << " -> "; if (link.output_->GetId() == loss_node_id_) { output << "output"; } else { output << "(" << link.output_->GetId() << ")"; } } output << "]" << std::endl; for (const auto& module : modules_) { output << "(" << std::dynamic_pointer_cast<ModuleNode>(module)->GetId() << "): "; output << module->prettyString() << std::endl; } return output.str(); } }
#include "neurons/network-container.h" #include "neurons/utilities.h" namespace neurons { NetworkContainer::NetworkContainer(NodeDeque& nodes, const std::deque<Link>& links) : links_(links) { if (!utilities::NodesAndLinksConsistent(nodes, links)) { throw std::in
std::vector<fl::Variable> Add(const std::vector<fl::Variable>& lhs, const std::vector<fl::Variable>& rhs) { if (lhs.size() != rhs.size()) { throw std::invalid_argument("Vector sizes do not match!"); } std::vector<fl::Variable> result; for (size_t i = 0; i < lhs.size(); ++i) { result.push_back(lhs.at(i) + rhs.at(i)); } return result; } std::vector<fl::Variable> NetworkContainer::forward( const std::vector<fl::Variable>& input) { if (input.size() != 1) { throw std::invalid_argument("Network expects only one input"); } auto output_maps = std::map<fl::ModulePtr, std::vector<fl::Variable>>(); for (const auto& module : modules_) { std::vector<fl::Variable> module_input; for (const auto& link : links_) { if (std::dynamic_pointer_cast<void>(link.output_) != std::dynamic_pointer_cast<void>(module)) { continue; } std::vector<fl::Variable> link_input; if (link.input_->GetId() == data_node_id_) { link_input = input; } else { auto module_ptr = std::dynamic_pointer_cast<fl::Module>(link.input_); if (module_ptr == nullptr) { throw std::runtime_error("Network links are invalid."); } link_input = output_maps.at(module_ptr); } module_input = module_input.empty() ? link_input : Add(module_input, link_input); } auto module_output = module->forward(module_input); output_maps.insert({module, module_output}); } std::vector<fl::Variable> output; for (const auto& link : links_) { if (link.output_->GetId() == loss_node_id_) { auto module_ptr = std::dynamic_pointer_cast<fl::Module>(link.input_); if (module_ptr == nullptr) { throw std::runtime_error("Network container modules are invalid."); } auto link_output = output_maps.at(module_ptr); output = output.empty() ? link_output : Add(output, link_output); } } if (input.size() != output.size()) { throw std::runtime_error("Unexpected container output size."); } return output; } fl::Variable NetworkContainer::forward(const fl::Variable& input) { std::vector<fl::Variable> output = {input}; output = forward(output); return output.front(); } fl::Variable NetworkContainer::operator()(const fl::Variable& input) { return forward(input); } std::string NetworkContainer::prettyString() const { std::ostringstream output; output << "Network:" << std::endl; output << "["; bool first_link = true; for (const auto& link : links_) { if (!first_link) { output << ", "; } else { first_link = false; } if (link.input_->GetId() == data_node_id_) { output << "input"; } else { output << "(" << link.input_->GetId() << ")"; } output << " -> "; if (link.output_->GetId() == loss_node_id_) { output << "output"; } else { output << "(" << link.output_->GetId() << ")"; } } output << "]" << std::endl; for (const auto& module : modules_) { output << "(" << std::dynamic_pointer_cast<ModuleNode>(module)->GetId() << "): "; output << module->prettyString() << std::endl; } return output.str(); } }
valid_argument("Passed nodes and links are inconsistent."); } if (utilities::CountConnectedComponents(nodes, links) != 1) { throw std::invalid_argument("Graph does not consist of 1 component."); } if (utilities::ContainsDirectedCycle(nodes, links)) { throw std::invalid_argument("Graph contains a directed cycle."); } if (!utilities::AreNodeInputsSatisfied(nodes, links)) { throw std::invalid_argument("Graph node inputs are not satisfied."); } if (!utilities::AreNodeOutputsSatisfied(nodes, links)) { throw std::invalid_argument("Graph node outputs are not satisfied."); } NodeDeque sorted = utilities::TopologicalSort(nodes, links); data_node_id_ = sorted.front()->GetId(); sorted.pop_front(); loss_node_id_ = sorted.back()->GetId(); sorted.pop_back(); for (auto& node : sorted) { auto module_node = std::dynamic_pointer_cast<ModuleNode>(node); add(module_node); } }
function_block-function_prefixed
[ { "content": "class Link {\n\n\n\n public:\n\n\n\n // Public member variables.\n\n std::shared_ptr<Node> input_;\n\n std::shared_ptr<Node> output_;\n\n\n\n // Get link ID.\n\n [[nodiscard]] size_t GetId() const;\n\n\n\n // Public constructor. Pass shared_ptr by value as Links will share ownership.\n\n Li...
C++
src/elements/areas/AreaProduction.cpp
FlorianEith/rcll_status_board
2358ca07d72ad090408c0810071b95c03416b02c
#include <AreaProduction.h> rcll_draw::AreaProduction::AreaProduction(){ hp_header = HeaderPanel("LOGISTICS LEAGUE", rcll_draw::NO_TEAM); thp_team_header_cyan = TeamHeaderPanel(); thp_team_header_magenta = TeamHeaderPanel(); vsp_gameinfo = VStatusPanel(rcll_draw::NO_TEAM); pi_productinfo_cyan = ProductInfo(rcll_draw::CYAN, 3); pi_productinfo_magenta = ProductInfo(rcll_draw::MAGENTA, 3); mip_machineinfo_cyan = MachineInfoProduction(rcll_draw::CYAN); mip_machineinfo_magenta = MachineInfoProduction(rcll_draw::MAGENTA); ri_robotinfo_cyan = RobotInfo(rcll_draw::CYAN); ri_robotinfo_magenta = RobotInfo(rcll_draw::MAGENTA); gf_gamefield = GameField(); blbl_text.setContent("The task for the robots is to produce products with the help of the machines."); blbl_text.setAlignment(rcll_draw::Alignment::CenterCenter); blbl_text.setBackgroundColor(rcll_draw::C_WHITE); blbl_text.setBorderColor(rcll_draw::C_WHITE); blbl_text.setFontSize(1.0); mip_machineinfo_cyan.setShortDisplay(true); mip_machineinfo_magenta.setShortDisplay(true); gf_gamefield.setRefBoxView(false); } rcll_draw::AreaProduction::~AreaProduction(){ } void rcll_draw::AreaProduction::setGeometry(int x, int y, int w, int h){ this->x = x; this->y = y; this->w = w; this->h = h; int cur_y = y; hp_header.setGeometry(x + (w - hp_header.getW(1.0)) / 2, cur_y, 1.0); thp_team_header_cyan.setGeometry(x, cur_y, 1.0); thp_team_header_magenta.setGeometry(x + w - thp_team_header_magenta.getW(1.0), cur_y, 1.0); cur_y += hp_header.getH(1.0) + gapsize; vsp_gameinfo.setGeometry(x + (w - vsp_gameinfo.getW(0.71)) / 2, cur_y, 0.71); cur_y += vsp_gameinfo.getH(0.71); pi_productinfo_cyan.setGeometry(x, cur_y - pi_productinfo_cyan.getH(0.65), 0.65); pi_productinfo_magenta.setGeometry(x + w - pi_productinfo_magenta.getW(0.65), cur_y - pi_productinfo_magenta.getH(0.65), 0.65); ri_robotinfo_cyan.setGeometry(x, cur_y - ri_robotinfo_cyan.getH(1.0), 1.0); ri_robotinfo_magenta.setGeometry(x + w - ri_robotinfo_magenta.getW(1.0), cur_y - ri_robotinfo_magenta.getH(1.0), 1.0); cur_y += gapsize; mip_machineinfo_cyan.setGeometry(x + gapsize, cur_y, 0.80); mip_machineinfo_magenta.setGeometry(x + w - mip_machineinfo_magenta.getW(0.80) - gapsize, cur_y, 0.80); gf_gamefield.setGeometry(x + (w - gf_gamefield.getW(0.60)) / 2, cur_y, 0.60); cur_y += gf_gamefield.getH(0.60) + gapsize / 3; blbl_text.setSize(w, h * 0.05); blbl_text.setPos(x, cur_y); } void rcll_draw::AreaProduction::setGameInfo(rcll_vis_msgs::GameInfo &gameinfo){ vsp_gameinfo.setContent(gameinfo); gf_gamefield.setPhase((rcll_draw::GamePhase)gameinfo.game_phase); thp_team_header_cyan.setTeam(gameinfo.team_name_cyan, rcll_draw::CYAN); thp_team_header_magenta.setTeam(gameinfo.team_name_magenta, rcll_draw::MAGENTA); } void rcll_draw::AreaProduction::setMachines(std::vector<rcll_vis_msgs::Machine> &machines){ mip_machineinfo_cyan.setMachines(machines); mip_machineinfo_magenta.setMachines(machines); gf_gamefield.setMachines(machines); } void rcll_draw::AreaProduction::setRobots(std::vector<rcll_vis_msgs::Robot> &robots){ ri_robotinfo_cyan.setRobots(robots); ri_robotinfo_magenta.setRobots(robots); gf_gamefield.setRobots(robots); } void rcll_draw::AreaProduction::setGameField(rcll_vis_msgs::SetGameField &setgamefield){ gf_gamefield.setGameField(setgamefield); } void rcll_draw::AreaProduction::setRefBoxView(bool refbox_view){ gf_gamefield.setRefBoxView(refbox_view); } void rcll_draw::AreaProduction::setProducts(std::vector<rcll_vis_msgs::Product> &products){ pi_productinfo_cyan.setProducts(products); pi_productinfo_magenta.setProducts(products); } void rcll_draw::AreaProduction::setPaging(double paging_time, double paging_wait_time, int shift_increase){ this->paging_time = paging_time; pi_productinfo_cyan.setPaging(paging_wait_time, shift_increase); pi_productinfo_magenta.setPaging(paging_wait_time, shift_increase); last_paging = ros::Time::now(); } void rcll_draw::AreaProduction::draw(cv::Mat &mat, bool show_element_borders){ hp_header.draw(mat, show_element_borders); thp_team_header_cyan.draw(mat, show_element_borders); thp_team_header_magenta.draw(mat, show_element_borders); vsp_gameinfo.draw(mat, show_element_borders); bool allow_paging_by_move = true; if (paging_count % 2 == 0){ pi_productinfo_cyan.draw(mat, show_element_borders); pi_productinfo_magenta.draw(mat, show_element_borders); allow_paging_by_move &= !pi_productinfo_cyan.move(); allow_paging_by_move &= !pi_productinfo_magenta.move(); } else { allow_paging_by_move = true; ri_robotinfo_cyan.draw(mat, show_element_borders); ri_robotinfo_magenta.draw(mat, show_element_borders); } if (allow_paging_by_move && (ros::Time::now() - last_paging).toSec() >= paging_time){ paging_count++; last_paging = ros::Time::now(); } mip_machineinfo_cyan.draw(mat, show_element_borders); mip_machineinfo_magenta.draw(mat, show_element_borders); gf_gamefield.draw(mat, show_element_borders); blbl_text.draw(mat); }
#include <AreaProduction.h> rcll_draw::AreaProduction::AreaProduction(){ hp_header = HeaderPanel("LOGISTICS LEAGUE", rcll_draw::NO_TEAM); thp_team_header_cyan = TeamHeaderPanel(); thp_team_header_magenta = TeamHeaderPanel(); vsp_gameinfo = VStatusPanel(rcll_draw::NO_TEAM); pi_productinfo_cyan = ProductInfo(rcll_draw::CYAN, 3); pi_productinfo_magenta = ProductInfo(rcll_draw::MAGENTA, 3); mip_machineinfo_cyan = MachineInfoProduction(rcll_draw::CYAN); mip_machineinfo_magenta = MachineInfoProduction(rcll_draw::MAGENTA); ri_robotinfo_cyan = RobotInfo(rcll_draw::CYAN); ri_robotinfo_magenta = RobotInfo(rcll_draw::MAGENTA); gf_gamefield = GameField(); blbl_text.setContent("The task for the robots is to produce products with the help of the machines."); blbl_text.setAlignment(rcll_draw::Alignment::CenterCenter); blbl_text.setBackgroundColor(rcll_draw::C_WHITE); blbl_text.setBorderColor(rcll_draw::C_WHITE); blbl_text.setFontSize(1.0); mip_machineinfo_cyan.setShortDisplay(true); mip_machineinfo_magenta.setShortDisplay(true); gf_gamefield.setRefBoxView(false); } rcll_draw::AreaProduction::~AreaProduction(){ } void rcll_draw::AreaProduction::setGeometry(int x, int y, int w, int h){ this->x = x; this->y = y; this->w = w; this->h = h; int cur_y = y; hp_header.setGeometry(x + (w - hp_header.getW(1.0)) / 2, cur_y, 1.0); thp_team_header_cyan.setGeometry(x, cur_y, 1.0); thp_team_header_magenta.setGeometry(x + w - thp_team_header_magenta.getW(1.0), cur_y, 1.0); cur_y += hp_header.getH(1.0) + gapsize; vsp_gameinfo.setGeometry(x + (w - vsp_gameinfo.getW(0.71)) / 2, cur_y, 0.71); cur_y += vsp_gameinfo.getH(0.71); pi_productinfo_cyan.setGeometry(x, cur_y - pi_productinfo_cyan.getH(0.65), 0.65); pi_productinfo_magenta.setGeometry(x + w - pi_productinfo_magenta.getW(0.65), cur_y - pi_productinfo_magenta.getH(0.65), 0.65); ri_robotinfo_cyan.setGeometry(x, cur_y - ri_robotinfo_cyan.getH(1.0), 1.0); ri_robotinfo_magenta.setGeometry(x + w - ri_robotinfo_magenta.getW(1.0), cur_y - ri_robotinfo_magenta.getH(1.0), 1.0); cur_y += gapsize; mip_machineinfo_cyan.setGeometry(x + gapsize, cur_y, 0.80); mip_machineinfo_magenta.setGeometry(x + w - mip_machineinfo_magenta.getW(0.80) - gapsize, cur_y, 0.80); gf_gamefield.setGeometry(x + (w - gf_gamefield.getW(0.60)) / 2, cur_y, 0.60); cur_y += gf_gamefield.getH(0.60) + gapsize / 3; blbl_text.setSize(w, h * 0.05); blbl_text.setPos(x, cur_y); } void rcll_draw::AreaProduction::setGameInfo(rcll_vis_msgs::GameInfo &gameinfo){ vsp_gameinfo.setContent(gameinfo); gf_gamefield.setPhase((rcll_draw::GamePhase)gameinfo.game_phase); thp_team_header_cyan.setTeam(gameinfo.team_name_cyan, rcll_draw::CYAN); thp_team_header_magenta.setTeam(gameinfo.team_name_magenta, rcll_draw::MAGENTA); } void rcll_draw::AreaProduction::setMachines(std::vector<rcll_vis_msgs::Machine> &machines){ mip_machineinfo_cyan.setMachines(machines); mip_machineinfo_magenta.setMachines(machines); gf_gamefield.setMachines(machines); } void rcll_draw::AreaProduction::setRobots(std::vector<rcll_vis_msgs::Robot> &robots){ ri_robotinfo_cyan.setRobots(robots); ri_robotinfo_magenta.setRobots(robots); gf_gamefield.setRobots(robots); } void rcll_draw::AreaProduction::setGameField(rcll_vis_msgs::SetGameField &setgamefield){ gf_gamefield.setGameField(setgamefield); } void rcll_draw::AreaProduction::setRefBoxView(bool refbox_view){ gf_gamefield.setRefBoxView(refbox_view); } void rcll_draw::AreaProduction::setProducts(std::vector<rcll_vis_msgs::Product> &products){ pi_productinfo_cyan.setProducts(products); pi_productinfo_magenta.setProducts(products); } void rcll_draw::AreaProduction::setPaging(double paging_time, double paging_wait_time, int shift_increase){ this->paging_time = paging_time; pi_productinfo_cyan.setPaging(paging_wait_time, shift_increase); pi_productinfo_magenta.setPaging(paging_wait_time, shift_increase); last_paging = ros::Time::now(); } void rcll_draw::AreaProduction::draw(cv::Mat &mat, bool show_element_borders){ hp_header.draw(mat, show_element_borders); thp_team_header_cyan.draw(mat, show_element_borders); thp_team_header_magenta.draw(mat, show_element_borders); vsp_gameinfo.draw(mat, show_element_borders); bool allow_paging_by_move = true; if (paging_count % 2 == 0){ pi_productinfo_cyan.draw(mat, show_element_borders); pi_productinfo_magenta.draw(mat, show_element_borders
, show_element_borders); mip_machineinfo_magenta.draw(mat, show_element_borders); gf_gamefield.draw(mat, show_element_borders); blbl_text.draw(mat); }
); allow_paging_by_move &= !pi_productinfo_cyan.move(); allow_paging_by_move &= !pi_productinfo_magenta.move(); } else { allow_paging_by_move = true; ri_robotinfo_cyan.draw(mat, show_element_borders); ri_robotinfo_magenta.draw(mat, show_element_borders); } if (allow_paging_by_move && (ros::Time::now() - last_paging).toSec() >= paging_time){ paging_count++; last_paging = ros::Time::now(); } mip_machineinfo_cyan.draw(mat
function_block-random_span
[ { "content": " class MachineInfoProduction {\n\n public:\n\n MachineInfoProduction();\n\n MachineInfoProduction(Team team);\n\n ~MachineInfoProduction();\n\n\n\n void setShortDisplay(bool short_display);\n\n void setGeometry(int x, int y, double scale);\n\n\n\n in...
C++
WithComments/grid.cc
RootofalleviI/Reversi
e52bf7ead191568114504945b62c7b955a2074a5
#include <string> #include <sstream> #include "grid.h" using namespace std; void Grid::init(size_t n) { dim = n; if (td) delete td; td = new TextDisplay(n); theGrid.clear(); for (size_t i=0; i<dim; ++i) { theGrid.emplace_back(vector<Cell>()); for (size_t j=0; j<dim; ++j) { theGrid[i].emplace_back(Cell(i,j)); } } for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { initObservers(i, j); } } setObserver(td); size_t t = dim/2 - 1; setPiece(t, t, Colour::Black); setPiece(t+1, t+1, Colour::Black); setPiece(t, t+1, Colour::White); setPiece(t+1, t, Colour::White); } void Grid::initObservers(int r, int c) { int d = dim; if (((r-1) >= 0) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r-1][c-1]); if ((r-1) >= 0) theGrid[r][c].attach(&theGrid[r-1][c]); if (((r-1) >= 0) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r-1][c+1]); if ((c+1) <= d-1) theGrid[r][c].attach(&theGrid[r][c+1]); if (((r+1) <= d-1) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r+1][c+1]); if ((r+1) <= d-1) theGrid[r][c].attach(&theGrid[r+1][c]); if (((r+1) <= d-1) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r+1][c-1]); if ((c-1) >= 0) theGrid[r][c].attach(&theGrid[r][c-1]); } void Grid::setObserver(Observer<Info, State> *ob) { for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { theGrid[i][j].attach(ob); } } } void Grid::reset() { for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { theGrid[i][j].setPiece(Colour::NoColour); } } } void Grid::setPiece(size_t r, size_t c, Colour colour) { reset(); if ((r >= dim) || (c >= dim)) { #ifdef DEBUG cout << "Invalid Position: (" << r << ", " << c << ")" << std::endl; #endif throw ""; return; } theGrid[r][c].setPiece(colour); if (colour != Colour::NoColour) updateCounter(); #ifdef DEBUG print(); #endif } int count(string s, char c) { size_t x = 0, len = s.size(); for (size_t i=0; i<len; ++i) { if (s[i] == c) ++x; } return x; } void Grid::updateCounter() { stringstream ss; ss << *td; string s = ss.str(); black = count(s, 'B'); white = count(s, 'W'); } void Grid::toggle(size_t r, size_t c) { theGrid[r][c].toggle(); } bool Grid::isFull() const { return (white+black == dim*dim); } Grid::~Grid() { delete td; } Colour Grid::whoWon() const { if (white>black) return Colour::White; else if (black>white) return Colour::Black; else return Colour::NoColour; } std::ostream &operator<<(ostream &out, const Grid &g) { out << *(g.td); return out; }
#include <string> #include <sstream> #include "grid.h" using namespace std; void Grid::init(size_t n) { dim = n; if (td) delete td; td = new TextDisplay(n); theGrid.clear(); for (size_t i=0; i<dim; ++i) { theGrid.emplace_back(vector<Cell>()); for (size_t j=0; j<dim; ++j) { theGrid[i].emplace_back(Cell(i,j)); } } for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { initObservers(i, j); } } setObserver(td); size_t t = dim/2 - 1; setPiece(t, t, Colour::Black); setPiece(t+1, t+1, Colour::Black); setPiece(t, t+1, Colour::White); setPiece(t+1, t, Colour::White); } void Grid::initObservers(int r, int c) { int d = dim; if (((r-1) >= 0) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r-1][c-1]); if ((r-1) >= 0) theGrid[r][c].attach(&theGrid[r-1][c]); if (((r-1) >= 0) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r-1][c+1]); if ((c+1) <= d-1) theGrid[r][c].attach(&theGrid[r][c+1]); if (((r+1) <= d-1) && ((c+1) <= d-1)) theGrid[r][c].attach(&theGrid[r+1][c+1]); if ((r+1) <= d-1) theGrid[r][c].attach(&theGrid[r+1][c]); if (((r+1) <= d-1) && ((c-1) >= 0)) theGrid[r][c].attach(&theGrid[r+1][c-1]); if ((c-1) >= 0) theGrid[r][c].attach(&theGrid[r][c-1]); } void Grid::setObserver(Observer<Info, State> *ob) { for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { theGrid[i][j].attach(ob); } } } void Grid::reset() { for (size_t i=0; i<dim; ++i) { for (size_t j=0; j<dim; ++j) { theGrid[i][j].setPiece(Colour::NoColour); } } } void Grid::setPiece(size_t r, size_t c, Colour colour) { reset(); if ((r >= dim) || (c >= dim)) { #ifdef DEBUG cout << "Invalid Position: (" << r << ", " << c << ")" << std::endl; #endif throw ""; return; } theGrid[r][c].setPiece(colour); if (colour != Colour::NoColour) updateCounter(); #ifdef DEBUG print(); #endif }
void Grid::updateCounter() { stringstream ss; ss << *td; string s = ss.str(); black = count(s, 'B'); white = count(s, 'W'); } void Grid::toggle(size_t r, size_t c) { theGrid[r][c].toggle(); } bool Grid::isFull() const { return (white+black == dim*dim); } Grid::~Grid() { delete td; } Colour Grid::whoWon() const { if (white>black) return Colour::White; else if (black>white) return Colour::Black; else return Colour::NoColour; } std::ostream &operator<<(ostream &out, const Grid &g) { out << *(g.td); return out; }
int count(string s, char c) { size_t x = 0, len = s.size(); for (size_t i=0; i<len; ++i) { if (s[i] == c) ++x; } return x; }
function_block-full_function
[ { "content": " Colour colour; \n", "file_path": "state.h", "rank": 0, "score": 67877.03442930145 }, { "content": " Colour colour; \n", "file_path": "WithComments/state.h", "rank": 1, "score": 65354.836290758016 }, { "content": " Colour colour;\n", "file_path": ...
C++
src/control.hpp
Gypsophino-dev/Gypsophino
484325bd5db36d99cdc13048646695b94f656111
#pragma once #include "const.hpp" #include "shape.hpp" #include <array> #include <raylib.h> #include <string> #include <utility> #include <vector> namespace gyp { enum button_status { normal, hover, pressed }; template <class callback_type> class button : public rectangle { private: button_status status{}; std::array<Color, 3> color{}; std::array<Image, 3> image{}; std::array<Color, 3> tint{}; std::array<std::string, 3> text{}; std::array<callback_type, 4> call_back{}; float font_size{}; float spacing{}; Font font{}; public: button(); button(int pos_x, int pos_y, int width, int height); button(int pos_x, int pos_y, int width, int height, const std::string &text, float font_size = DEFAULT_FONT_SIZE); button(int pos_x, int pos_y, int width, int height, std::array<std::string, 3> text, float font_size = DEFAULT_FONT_SIZE); ~button() = default; void set_geometry(int pos_x, int pos_y, int width, int height); void set_color(std::array<Color, 3> background, std::array<Color, 3> foreground); void set_text(Font font, float font_size, float spacing, std::array<std::string, 3> &&text); void set_status(button_status stat); void set_call_back(std::array<callback_type, 4> call_back); button_status get_status(); void draw(); void draw(button_status status); callback_type interact(Vector2 mouse); }; template <class callback_type> button<callback_type>::button() : status(normal) { set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), DEFAULT_FONT_SIZE, DEFAULT_FONT_SPACING, std::array<std::string, 3>{"Text", "Text", "Text"}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height) : status(normal) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), DEFAULT_FONT_SIZE, DEFAULT_FONT_SPACING, std::array<std::string, 3>{"Text", "Text", "Text"}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height, const std::string &text, float font_size) : status(normal) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), font_size, DEFAULT_FONT_SPACING, std::array<std::string, 3>{text, text, text}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height, std::array<std::string, 3> text, float font_size) : status(normal), text(std::move(text)) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), font_size, DEFAULT_FONT_SPACING, std::move(text)); } template <class callback_type> void button<callback_type>::set_geometry(int pos_x, int pos_y, int width, int height) { x = pos_x; y = pos_y; this->width = width; this->height = height; } template <class callback_type> void button<callback_type>::set_color(std::array<Color, 3> background, std::array<Color, 3> foreground) { color = background; tint = foreground; } template <class callback_type> void button<callback_type>::set_text(Font font, float font_size, float spacing, std::array<std::string, 3> &&text) { this->font = font; this->font_size = font_size; this->spacing = spacing; this->text = std::move(text); } template <class callback_type> void button<callback_type>::set_status(button_status stat) { status = stat; } template <class callback_type> void button<callback_type>::set_call_back( std::array<callback_type, 4> call_back) { this->call_back = call_back; } template <class callback_type> button_status button<callback_type>::get_status() { return status; } template <class callback_type> void button<callback_type>::draw() { draw(status); } template <class callback_type> void button<callback_type>::draw(button_status stat) { DrawRectangle(x, y, width, height, color.at(stat)); Vector2 text_size = MeasureTextEx(font, text.at(stat).c_str(), font_size, spacing); text_size.x /= -2; text_size.y /= -2; text_size.x += x + width / 2; text_size.y += y + height / 2; DrawTextEx(font, text.at(stat).c_str(), text_size, font_size, spacing, tint.at(stat)); } template <class callback_type> callback_type button<callback_type>::interact(Vector2 mouse) { int mx = static_cast<int>(mouse.x); int my = static_cast<int>(mouse.y); if (mx > x && mx < x + width && my > y && my < y + height) { status = hover; for (int i = 0; i <= 2; i++) { if (IsMouseButtonReleased(i)) { status = pressed; draw(); return call_back[i + 1]; } if (IsMouseButtonDown(i)) { status = pressed; } } draw(); return call_back[0]; } status = normal; draw(); return call_back[0]; } template <class callback_type> class timer { private: int count_down{}; std::array<callback_type, 2> call_back; public: timer() = default; explicit timer(int count_down); ~timer() = default; void set_count_down(int count_down); void set_call_back(std::array<callback_type, 2> call_back); void draw(); callback_type interact(); }; template <class callback_type> timer<callback_type>::timer(int count_down) : count_down(count_down) {} template <class callback_type> void timer<callback_type>::set_count_down(int count_down) { this->count_down = count_down; } template <class callback_type> void timer<callback_type>::set_call_back(std::array<callback_type, 2> call_back) { this->call_back = call_back; } template <class callback_type> void timer<callback_type>::draw() { count_down--; } template <class callback_type> callback_type timer<callback_type>::interact() { count_down--; if (count_down <= 0) { return call_back[1]; } return call_back[0]; } }
#pragma once #include "const.hpp" #include "shape.hpp" #include <array> #include <raylib.h> #include <string> #include <utility> #include <vector> namespace gyp { enum button_status { normal, hover, pressed }; template <class callback_type> class button : public rectangle { private: button_status status{}; std::array<Color, 3> color{}; std::array<Image, 3> image{}; std::array<Color, 3> tint{}; std::array<std::string, 3> text{}; std::array<callback_type, 4> call_back{}; float font_size{}; float spacing{}; Font font{}; public: button(); button(int pos_x, int pos_y, int width, int height); button(int pos_x, int pos_y, int width, int height, const std::string &text, float font_size = DEFAULT_FONT_SIZE); button(int pos_x, int pos_y, int width, int height, std::array<std::string, 3> text, float font_size = DEFAULT_FONT_SIZE); ~button() = default; void set_geometry(int pos_x, int pos_y, int width, int height); void set_color(std::array<Color, 3> background, std::array<Color, 3> foreground); void set_text(Font font, float font_size, float spacing, std::array<std::string, 3> &&text); void set_status(button_status stat); void set_call_back(std::array<callback_type, 4> call_back); button_status get_status(); void draw(); void draw(button_status status); callback_type interact(Vector2 mouse); }; template <class callback_type> button<callback_type>::button() : status(normal) { set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), DEFAULT_FONT_SIZE, DEFAULT_FONT_SPACING, std::array<std::string, 3>{"Text", "Text", "Text"}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height) : status(normal) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), DEFAULT_FONT_SIZE, DEFAULT_FONT_SPACING, std::array<std::string, 3>{"Text", "Text", "Text"}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height, const std::string &text, float font_size) : status(normal) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), font_size, DEFAULT_FONT_SPACING, std::array<std::string, 3>{text, text, text}); } template <class callback_type> button<callback_type>::button(int pos_x, int pos_y, int width, int height, std::array<std::string, 3> text, float font_size) : status(normal), text(std::move(text)) { set_geometry(pos_x, pos_y, width, height); set_color(std::array<Color, 3>{BLACK, GRAY, BLUE}, std::array<Color, 3>{WHITE, WHITE, WHITE}); set_text(GetFontDefault(), font_size, DEFAULT_FONT_SPACING, std::move(text)); } template <class callback_type> void button<callback_type>::set_geometry(int pos_x, int pos_y, int width, int height) { x = pos_x; y = pos_y; this->width = width; this->height = height; } template <class callback_type> void button<callback_type>::set_color(std::array<Color, 3> background, std::array<Color, 3> foreground) { color = background; tint = foreground; } template <class callback_type> void button<callback_type>::set_text(Font font, float font_size, float spacing, std::array<std::string, 3> &&text) { this->font = font; this->font_size = font_size; this->spacing = spacing; this->text = std::move(text); } template <class callback_type> void button<callback_type>::set_status(button_status stat) { status = stat; } template <class callback_type> void button<callback_type>::set_call_back( std::array<callback_type, 4> call_back) { this->call_back = call_back; } template <class callback_type> button_status button<callback_type>::get_status() { return status; } template <class callback_type> void button<callback_type>::draw() { draw(status); } template <class callback_type>
template <class callback_type> callback_type button<callback_type>::interact(Vector2 mouse) { int mx = static_cast<int>(mouse.x); int my = static_cast<int>(mouse.y); if (mx > x && mx < x + width && my > y && my < y + height) { status = hover; for (int i = 0; i <= 2; i++) { if (IsMouseButtonReleased(i)) { status = pressed; draw(); return call_back[i + 1]; } if (IsMouseButtonDown(i)) { status = pressed; } } draw(); return call_back[0]; } status = normal; draw(); return call_back[0]; } template <class callback_type> class timer { private: int count_down{}; std::array<callback_type, 2> call_back; public: timer() = default; explicit timer(int count_down); ~timer() = default; void set_count_down(int count_down); void set_call_back(std::array<callback_type, 2> call_back); void draw(); callback_type interact(); }; template <class callback_type> timer<callback_type>::timer(int count_down) : count_down(count_down) {} template <class callback_type> void timer<callback_type>::set_count_down(int count_down) { this->count_down = count_down; } template <class callback_type> void timer<callback_type>::set_call_back(std::array<callback_type, 2> call_back) { this->call_back = call_back; } template <class callback_type> void timer<callback_type>::draw() { count_down--; } template <class callback_type> callback_type timer<callback_type>::interact() { count_down--; if (count_down <= 0) { return call_back[1]; } return call_back[0]; } }
void button<callback_type>::draw(button_status stat) { DrawRectangle(x, y, width, height, color.at(stat)); Vector2 text_size = MeasureTextEx(font, text.at(stat).c_str(), font_size, spacing); text_size.x /= -2; text_size.y /= -2; text_size.x += x + width / 2; text_size.y += y + height / 2; DrawTextEx(font, text.at(stat).c_str(), text_size, font_size, spacing, tint.at(stat)); }
function_block-full_function
[ { "content": "class playground : public std::vector<track>, public rectangle {\n\nprivate:\n\n // Geometry\n\n int track_number;\n\n\n\n // Playground style\n\n Color outline;\n\n int thick;\n\n\n\n int current_time;\n\n int speed;\n\n const song_map *song;\n\n Music music;\n\n playground_status statu...
C++
include/amtrs/.driver/win32-g3d-device-opengl.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
 #ifndef __libamtrs__g3d__device__win32__opengl__hpp #define __libamtrs__g3d__device__win32__opengl__hpp #pragma comment(lib, "user32.lib") #pragma comment(lib, "gdi32.lib") #pragma comment(lib, "opengl32.lib") #include ".api-windows.hpp" #include <GL/gl.h> #include <GL/glext.h> #include <GL/wglext.h> #include "opengl.inc/glext-value.hpp" #define AMTRS_USE_DYNAMIC_OPENGL_INIT 1 #include "../opengl/g3d-device.hpp" #define AMTRS_WIN32_OPENGL_NAMESPACE_BEGIN AMTRS_G3D_NAMESPACE_BEGIN namespace win32 { namespace opengl { #define AMTRS_WIN32_OPENGL_NAMESPACE_END } } AMTRS_G3D_NAMESPACE_END AMTRS_WIN32_OPENGL_NAMESPACE_BEGIN using namespace os::win32; class device : public g3d::opengl::device { public: virtual ~device() { wglDeleteContext(mGLRC); } virtual void active() override { wglMakeCurrent(mDC, mGLRC); } virtual void deactive() override { wglMakeCurrent(mDC, nullptr); } virtual bool is_context_enable() const override { return mGLRC != nullptr; } void initialize(HDC _hdc) { PIXELFORMATDESCRIPTOR pfd; std::memset(&pfd, 0, sizeof(pfd)); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 24; pfd.cStencilBits = 8; GLuint uPixelFormat = ChoosePixelFormat(_hdc, &pfd); if (!uPixelFormat) { throw std::system_error(make_last_error_code(), "ChoosePixelFormat()"); } if (!SetPixelFormat(_hdc, uPixelFormat, &pfd)) { throw std::system_error(make_last_error_code(), "SetPixelFormat()"); } mGLRC = wglCreateContext(_hdc); if (!mGLRC) { throw std::system_error(make_last_error_code(), "wglCreateContext()"); } wglMakeCurrent(_hdc, mGLRC); mDC = _hdc; auto wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if (wglCreateContextAttribsARB) { static const int attr[]= { WGL_CONTEXT_MAJOR_VERSION_ARB, 2, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, 0, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0, }; HGLRC hglrc = wglCreateContextAttribsARB(mDC, nullptr, attr); wglMakeCurrent(mDC, hglrc); wglDeleteContext(mGLRC); mGLRC = hglrc; #if AMTRS_USE_DYNAMIC_OPENGL_INIT #include "opengl.inc/glext-init.hpp" #endif mSupportExtAPI = true; } } protected: HDC mDC = nullptr; HGLRC mGLRC = nullptr; bool mSupportExtAPI = false; }; AMTRS_WIN32_OPENGL_NAMESPACE_END AMTRS_G3D_NAMESPACE_BEGIN template<class BitmapT> inline ref<device> device::create(BitmapT* _bitmap) { using namespace os::win32; class device : public win32::opengl::device { public: using _base_type = win32::opengl::device; device(BitmapT* _bmp) : mBitmap(_bmp) {} ~device() { if (mDC) { ReleaseDC(nullptr, mDC); } } virtual size_type size() const override { return mBitmap->size(); } virtual void present() override { glReadPixels(0, 0, size().width, size().height, GL_RGBA, GL_UNSIGNED_BYTE, mBitmap->pixels().data()); _base_type::present(); } void initialize() { mDC = GetDC(nullptr); if (!mDC) { throw std::system_error(make_last_error_code(), "GetDC()"); } _base_type::initialize(mDC); } BitmapT* mBitmap; }; ref<device> thiz = new device(_bitmap); thiz->initialize(); return thiz; } AMTRS_G3D_NAMESPACE_END #endif
 #ifndef __libamtrs__g3d__device__win32__opengl__hpp #define __libamtrs__g3d__device__win32__opengl__hpp #pragma comment(lib, "user32.lib") #pragma comment(lib, "gdi32.lib") #pragma comment(lib, "opengl32.lib") #include ".api-windows.hpp" #include <GL/gl.h> #include <GL/glext.h> #include <GL/wglext.h> #include "opengl.inc/glext-value.hpp" #define AMTRS_USE_DYNAMIC_OPENGL_INIT 1 #include "../opengl/g3d-device.hpp" #define AMTRS_WIN32_OPENGL_NAMESPACE_BEGIN AMTRS_G3D_NAMESPACE_BEGIN namespace win32 { namespace opengl { #define AMTRS_WIN32_OPENGL_NAMESPACE_END } } AMTRS_G3D_NAMESPACE_END AMTRS_WIN32_OPENGL_NAMESPACE_BEGIN using namespace os::win32; class device : public g3d::opengl::device { public: virtual ~device() { wglDeleteContext(mGLRC); } virtual void active() override { wglMakeCurrent(mDC, mGLRC); } virtual void deactive() override { wglMakeCurrent(mDC, nullptr); } virtual bool is_context_enable() const override { return mGLRC != nullptr; } void initialize(HDC _hdc) { PIXELFORMATDESCRIPTOR pfd; std::memset(&pfd, 0, sizeof(pfd)); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 24; pfd.cStencilBits = 8; GLuint uPixelFormat = ChoosePixelFormat(_hdc, &pfd); if (!uPixelFormat) { throw std::system_error(make_last_error_code(), "ChoosePixelFormat()"); } if (!SetPixelFormat(_hdc, uPixelFormat, &pfd)) { throw std::system_error(make_last_error_code(), "SetPixelFormat()"); } mGLRC = wglCreateContext(_hdc)
rtExtAPI = false; }; AMTRS_WIN32_OPENGL_NAMESPACE_END AMTRS_G3D_NAMESPACE_BEGIN template<class BitmapT> inline ref<device> device::create(BitmapT* _bitmap) { using namespace os::win32; class device : public win32::opengl::device { public: using _base_type = win32::opengl::device; device(BitmapT* _bmp) : mBitmap(_bmp) {} ~device() { if (mDC) { ReleaseDC(nullptr, mDC); } } virtual size_type size() const override { return mBitmap->size(); } virtual void present() override { glReadPixels(0, 0, size().width, size().height, GL_RGBA, GL_UNSIGNED_BYTE, mBitmap->pixels().data()); _base_type::present(); } void initialize() { mDC = GetDC(nullptr); if (!mDC) { throw std::system_error(make_last_error_code(), "GetDC()"); } _base_type::initialize(mDC); } BitmapT* mBitmap; }; ref<device> thiz = new device(_bitmap); thiz->initialize(); return thiz; } AMTRS_G3D_NAMESPACE_END #endif
; if (!mGLRC) { throw std::system_error(make_last_error_code(), "wglCreateContext()"); } wglMakeCurrent(_hdc, mGLRC); mDC = _hdc; auto wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if (wglCreateContextAttribsARB) { static const int attr[]= { WGL_CONTEXT_MAJOR_VERSION_ARB, 2, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, 0, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0, }; HGLRC hglrc = wglCreateContextAttribsARB(mDC, nullptr, attr); wglMakeCurrent(mDC, hglrc); wglDeleteContext(mGLRC); mGLRC = hglrc; #if AMTRS_USE_DYNAMIC_OPENGL_INIT #include "opengl.inc/glext-init.hpp" #endif mSupportExtAPI = true; } } protected: HDC mDC = nullptr; HGLRC mGLRC = nullptr; bool mSuppo
random
[ { "content": "// ============================================================================\n\n//! 標準ファイルシステムに対するインターフェース\n\n// ----------------------------------------------------------------------------\n\n//! std::filesystem を仮想化します。\n\n// -------------------------------------------------------------------...
C++
CrescentEngine/Models/Mesh.cpp
xRiveria/Crescent-Engine
b6512b6a8dab2d27cf542c562ccc28f21bf2345d
#include "CrescentPCH.h" #include "Mesh.h" #include "GL/glew.h" #include <glm/gtc/type_ptr.hpp> #include <algorithm> namespace Crescent { Mesh::Mesh() { } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<unsigned int> indices) { m_Positions = positions; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<glm::vec3> normals, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Normals = normals; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<glm::vec3> normals, std::vector<glm::vec3> tangents, std::vector<glm::vec3> bitangents, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Normals = normals; m_Tangents = tangents; m_Bitangents = bitangents; m_Indices = indices; } void Mesh::FinalizeMesh(bool interleaved) { if (!m_VertexArrayID) { glGenVertexArrays(1, &m_VertexArrayID); glGenBuffers(1, &m_VertexBufferID); glGenBuffers(1, &m_IndexBufferID); } std::vector<float> bufferData; if (interleaved) { for (int i = 0; i < m_Positions.size(); i++) { bufferData.push_back(m_Positions[i].x); bufferData.push_back(m_Positions[i].y); bufferData.push_back(m_Positions[i].z); if (m_UV.size() > 0) { bufferData.push_back(m_UV[i].x); bufferData.push_back(m_UV[i].y); } if (m_Normals.size() > 0) { bufferData.push_back(m_Normals[i].x); bufferData.push_back(m_Normals[i].y); bufferData.push_back(m_Normals[i].z); } if (m_Tangents.size() > 0) { bufferData.push_back(m_Tangents[i].x); bufferData.push_back(m_Tangents[i].y); bufferData.push_back(m_Tangents[i].z); } if (m_Bitangents.size() > 0) { bufferData.push_back(m_Bitangents[i].x); bufferData.push_back(m_Bitangents[i].y); bufferData.push_back(m_Bitangents[i].z); } } } else { for (int i = 0; i < m_Positions.size(); i++) { bufferData.push_back(m_Positions[i].x); bufferData.push_back(m_Positions[i].y); bufferData.push_back(m_Positions[i].z); } for (int i = 0; i < m_UV.size(); i++) { bufferData.push_back(m_UV[i].x); bufferData.push_back(m_UV[i].y); } for (int i = 0; i < m_Normals.size(); i++) { bufferData.push_back(m_Normals[i].x); bufferData.push_back(m_Normals[i].y); bufferData.push_back(m_Normals[i].z); } for (int i = 0; i < m_Tangents.size(); i++) { bufferData.push_back(m_Tangents[i].x); bufferData.push_back(m_Tangents[i].y); bufferData.push_back(m_Tangents[i].z); } for (int i = 0; i < m_Bitangents.size(); i++) { bufferData.push_back(m_Bitangents[i].x); bufferData.push_back(m_Bitangents[i].y); bufferData.push_back(m_Bitangents[i].z); } } glBindVertexArray(m_VertexArrayID); glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferID); glBufferData(GL_ARRAY_BUFFER, (bufferData.size() * sizeof(float) + (m_BoneIDs.size() * sizeof(int)) + (m_BoneWeights.size() * sizeof(float))), &bufferData[0], GL_STATIC_DRAW); if (m_Indices.size() > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_Indices.size() * sizeof(unsigned int), &m_Indices[0], GL_STATIC_DRAW); } if (interleaved) { size_t stride = 3 * sizeof(float); if (m_UV.size() > 0) stride += 2 * sizeof(float); if (m_Normals.size() > 0) stride += 3 * sizeof(float); if (m_Tangents.size() > 0) stride += 3 * sizeof(float); if (m_Bitangents.size() > 0) stride += 3 * sizeof(float); size_t offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); if (m_UV.size() > 0) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 2 * sizeof(float); } if (m_Normals.size() > 0) { glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } if (m_Tangents.size() > 0) { glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } if (m_Bitangents.size() > 0) { glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } } else { size_t offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Positions.size() * sizeof(float); if (m_UV.size() > 0) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_UV.size() * sizeof(float); } if (m_Normals.size() > 0) { glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Normals.size() * sizeof(float); } if (m_Tangents.size() > 0) { glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Tangents.size() * sizeof(float); } if (m_Bitangents.size() > 0) { glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Bitangents.size() * sizeof(float); } } glBindVertexArray(0); } Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<MeshTexture> textures) { this->vertices = vertices; this->indices = indices; this->textures = textures; SetupMesh(); } void Mesh::Draw(Shader& shader, bool renderShadowMap, unsigned int shadowMapTextureID) { unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; glBindVertexArray(vertexArrayObject); shader.UseShader(); if (!renderShadowMap) { for (unsigned int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); std::string number; std::string name = textures[i].type; if (name == "texture_diffuse") { number = std::to_string(diffuseNr++); } else if (name == "texture_specular") { number = std::to_string(specularNr++); } else if (name == "texture_normal") { number = std::to_string(normalNr++); } else if (name == "texture_height") { number = std::to_string(heightNr++); } shader.UseShader(); glUniform1i(glGetUniformLocation(shader.GetShaderID(), (name + number).c_str()), i); glBindTexture(GL_TEXTURE_2D, textures[i].id); } } glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); for (int i = 0; i < 32; i++) { if (i == 3) { continue; } glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } glBindVertexArray(0); } void Mesh::SetupMesh() { glGenVertexArrays(1, &vertexArrayObject); glGenBuffers(1, &vertexBufferObject); glGenBuffers(1, &indexBufferObject); glBindVertexArray(vertexArrayObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords)); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent)); glEnableVertexAttribArray(5); glVertexAttribIPointer(5, 4, GL_INT, sizeof(Vertex), (void*)(offsetof(Vertex, BoneIDs) + 0 * sizeof(int))); glEnableVertexAttribArray(6); glVertexAttribIPointer(6, 4, GL_INT, sizeof(Vertex), (void*)(offsetof(Vertex, BoneIDs) + 4 * sizeof(int))); glEnableVertexAttribArray(7); glVertexAttribPointer(7, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, BoneWeights) + 0 * sizeof(float))); glEnableVertexAttribArray(8); glVertexAttribPointer(8, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, BoneWeights) + 4 * sizeof(float))); glBindVertexArray(0); } void Mesh::RecursivelyUpdateBoneMatrices(int animationIndex, aiNode* node, glm::mat4 transform, double ticks) { static auto mat4_from_aimatrix4x4 = [](aiMatrix4x4 matrix) -> glm::mat4 { glm::mat4 res; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) res[j][i] = matrix[i][j]; return res; }; std::string node_name = node->mName.C_Str(); auto animation = m_Animations[animationIndex]->m_Animation; glm::mat4 current_transform; if (m_AnimationChannelMap.count(std::pair<uint32_t, std::string>(animationIndex, node_name))) { uint32_t channel_id = m_AnimationChannelMap[std::pair<uint32_t, std::string>(animationIndex, node_name)]; auto channel = animation->mChannels[channel_id]; glm::mat4 translation_matrix = InterpolateTranslationMatrix(channel->mPositionKeys, channel->mNumPositionKeys, ticks); glm::mat4 rotation_matrix = InterpolateRotationMatrix(channel->mRotationKeys, channel->mNumRotationKeys, ticks); glm::mat4 scaling_matrix = InterpolateScalingMatrix(channel->mScalingKeys, channel->mNumScalingKeys, ticks); current_transform = translation_matrix * rotation_matrix * scaling_matrix; } else { current_transform = mat4_from_aimatrix4x4(node->mTransformation); } if (m_BoneMapper.RetrieveBoneLibrary().count(node_name)) { uint32_t i = m_BoneMapper.RetrieveBoneLibrary()[node_name]; m_BoneMatrices[i] = transform * current_transform * m_BoneOffsets[i]; } for (int i = 0; i < node->mNumChildren; i++) { RecursivelyUpdateBoneMatrices(animationIndex, node->mChildren[i], transform * current_transform, ticks); } } glm::mat4 Mesh::InterpolateTranslationMatrix(aiVectorKey* keys, uint32_t n, double ticks) { static auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 { return glm::translate(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z)); }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aivector3d(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue); aiVectorKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; float factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); return mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor); } glm::mat4 Mesh::InterpolateRotationMatrix(aiQuatKey* keys, uint32_t n, double ticks) { static auto mat4_from_aiquaternion = [](aiQuaternion quaternion) -> glm::mat4 { auto rotation_matrix = quaternion.GetMatrix(); glm::mat4 res(1); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) res[j][i] = rotation_matrix[i][j]; return res; }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aiquaternion(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aiquaternion(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aiquaternion(keys[n - 1].mValue); aiQuatKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiQuatKey& a, const aiQuatKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; double factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); aiQuaternion out; aiQuaternion::Interpolate(out, left_ptr->mValue, right_ptr->mValue, factor); return mat4_from_aiquaternion(out); } glm::mat4 Mesh::InterpolateScalingMatrix(aiVectorKey* keys, uint32_t n, double ticks) { static auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 { return glm::scale(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z)); }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aivector3d(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue); aiVectorKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; float factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); return mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor); } }
#include "CrescentPCH.h" #include "Mesh.h" #include "GL/glew.h" #include <glm/gtc/type_ptr.hpp> #include <algorithm> namespace Crescent { Mesh::Mesh() { } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<unsigned int> indices) { m_Positions = positions; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<glm::vec3> normals, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Normals = normals; m_Indices = indices; } Mesh::Mesh(std::vector<glm::vec3> positions, std::vector<glm::vec2> uv, std::vector<glm::vec3> normals, std::vector<glm::vec3> tangents, std::vector<glm::vec3> bitangents, std::vector<unsigned int> indices) { m_Positions = positions; m_UV = uv; m_Normals = normals; m_Tangents = tangents; m_Bitangents = bitangents; m_Indices = indices; } void Mesh::FinalizeMesh(bool interleaved) { if (!m_VertexArrayID) { glGenVertexArrays(1, &m_VertexArrayID); glGenBuffers(1, &m_VertexBufferID); glGenBuffers(1, &m_IndexBufferID); } std::vector<float> bufferData; if (interleaved) { for (int i = 0; i < m_Positions.size(); i++) { bufferData.push_back(m_Positions[i].x); bufferData.push_back(m_Positions[i].y); bufferData.push_back(m_Positions[i].z); if (m_UV.size() > 0) { bufferData.push_back(m_UV[i].x); bufferData.push_back(m_UV[i].y); } if (m_Normals.size() > 0) { bufferData.push_back(m_Normals[i].x); bufferData.push_back(m_Normals[i].y); bufferData.push_back(m_Normals[i].z); } if (m_Tangents.size() > 0) { bufferData.push_back(m_Tangents[i].x); bufferData.push_back(m_Tangents[i].y); bufferData.push_back(m_Tangents[i].z); } if (m_Bitangents.size() > 0) { bufferData.push_back(m_Bitangents[i].x); bufferData.push_back(m_Bitangents[i].y); bufferData.push_back(m_Bitangents[i].z); } } } else { for (int i = 0; i < m_Positions.size(); i++) { bufferData.push_back(m_Positions[i].x); bufferData.push_back(m_Positions[i].y); bufferData.push_back(m_Positions[i].z); } for (int i = 0; i < m_UV.size(); i++) { bufferData.push_back(m_UV[i].x); bufferData.push_back(m_UV[i].y); } for (int i = 0; i < m_Normals.size(); i++) { bufferData.push_back(m_Normals[i].x); bufferData.push_back(m_Normals[i].y); bufferData.push_back(m_Normals[i].z); } for (int i = 0; i < m_Tangents.size(); i++) { bufferData.push_back(m_Tangents[i].x); bufferData.push_back(m_Tangents[i].y); bufferData.push_back(m_Tangents[i].z); } for (int i = 0; i < m_Bitangents.size(); i++) { bufferData.push_back(m_Bitangents[i].x); bufferData.push_back(m_Bitangents[i].y); bufferData.push_back(m_Bitangents[i].z); } } glBindVertexArray(m_VertexArrayID); glBindBuffer(GL_ARRAY_BUFFER, m_VertexBufferID); glBufferData(GL_ARRAY_BUFFER, (bufferData.size() * sizeof(float) + (m_BoneIDs.size() * sizeof(int)) + (m_BoneWeights.size() * sizeof(float))), &bufferData[0], GL_STATIC_DRAW); if (m_Indices.size() > 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_Indices.size() * sizeof(unsigned int), &m_Indices[0], GL_STATIC_DRAW); } if (interleaved) { size_t stride = 3 * sizeof(float); if (m_UV.size() > 0) stride += 2 * sizeof(float); if (m_Normals.size() > 0) stride += 3 * sizeof(float); if (m_Tangents.size() > 0) stride += 3 * sizeof(float); if (m_Bitangents.size() > 0) stride += 3 * sizeof(float); size_t offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); if (m_UV.size() > 0) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 2 * sizeof(float); } if (m_Normals.size() > 0) { glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } if (m_Tangents.size() > 0) { glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } if (m_Bitangents.size() > 0) { glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)offset); offset += 3 * sizeof(float); } } else { size_t offset = 0; glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Positions.size() * sizeof(float); if (m_UV.size() > 0) { glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_UV.size() * sizeof(float); } if (m_Normals.size() > 0) { glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Normals.size() * sizeof(float); } if (m_Tangents.size() > 0) { glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Tangents.size() * sizeof(float); } if (m_Bitangents.size() > 0) { glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)offset); offset += m_Bitangents.size() * sizeof(float); } } glBindVertexArray(0); } Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<MeshTexture> textures) { this->vertices = vertices; this->indices = indices; this->textures = textures; SetupMesh(); } void Mesh::Draw(Shader& shader, bool renderShadowMap, unsigned int shadowMapTextureID) { unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; glBindVertexArray(vertexArrayObject); shader.UseShader(); if (!renderShadowMap) { for (unsigned int i = 0; i < textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); std::string number; std::string name = textures[i].type; if (name == "texture_diffuse") { number = std::to_string(diffuseNr++); } else if (name == "texture_specular") { number = std::to_string(specularNr++); } else if (name == "texture_normal") { number = std::to_string(normalNr++); } else if (name == "texture_height") { number = std::to_string(heightNr++); } shader.UseShader(); glUniform1i(glGetUniformLocation(shader.GetShaderID(), (name + number).c_str()), i); glBindTexture(GL_TEXTURE_2D, textures[i].id); } } glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); for (int i = 0; i < 32; i++) { if (i == 3) { continue; } glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } glBindVertexArray(0); } void Mesh::SetupMesh() { glGenVertexArrays(1, &vertexArrayObject); glGenBuffers(1, &vertexBufferObject); glGenBuffers(1, &indexBufferObject); glBindVertexArray(vertexArrayObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferObject); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords)); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent)); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent)); glEnableVertexAttribArray(5); glVertexAttribIPointer(5, 4, GL_INT, sizeof(Vertex), (void*)(offsetof(Vertex, BoneIDs) + 0 * sizeof(int))); glEnableVertexAttribArray(6); glVertexAttribIPointer(6, 4, GL_INT, sizeof(Vertex), (void*)(offsetof(Vertex, BoneIDs) + 4 * sizeof(int))); glEnableVertexAttribArray(7); glVertexAttribPointer(7, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, BoneWeights) + 0 * sizeof(float))); glEnableVertexAttribArray(8); glVertexAttribPointer(8, 4, GL_FLOAT, false, sizeof(Vertex), (void*)(offsetof(Vertex, BoneWeights) + 4 * sizeof(float))); glBindVertexArray(0); } void Mesh::RecursivelyUpdateBoneMatrices(int animationIndex, aiNode* node, glm::mat4 transform, double ticks) { static auto mat4_from_aimatrix4x4 = [](aiMatrix4x4 matrix) -> glm::mat4 { glm::mat4 res; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) res[j][i] = matrix[i][j]; return res; }; std::string node_name = node->mName.C_Str(); auto animation = m_Animations[animationIndex]->m_Animation; glm::mat4 current_transform; if (m_AnimationChannelMap.count(std::pair<uint32_t, std::string>(animationIndex, node_name))) { uint32_t channel_id = m_AnimationChannelMap[std::pair<uint32_t, std::string>(animationIndex, node_name)]; auto channel = animation->mChannels[channel_id]; glm::mat4 translation_matrix = InterpolateTranslationMatrix(channel->mPositionKeys, channel->mNumPositionKeys, ticks); glm::mat4 rotation_matrix = InterpolateRotationMatrix(channel->mRotationKeys, channel->mNumRotationKeys, ticks); glm::mat4 scaling_matrix = InterpolateScalingMatrix(channel->mScalingKeys, channel->mNumScalingKeys, ticks); current_transform = translation_matrix * rotation_matrix * scaling_matrix; } else { current_transform = mat4_from_aimatrix4x4(node->mTransformation); } if (m_BoneMapper.RetrieveBoneLibrary().count(node_name)) { uint32_t i = m_BoneMapper.RetrieveBoneLibrary()[node_name]; m_BoneMatrices[i] = transform * current_transform * m_BoneOffsets[i]; } for (int i = 0; i < node->mNumChildren; i++) { RecursivelyUpdateBoneMatrices(animationIndex, node->mChildren[i], transform * current_transform, ticks); } } glm::mat4 Mesh::InterpolateTranslationMatrix(aiVectorKey* keys, uint32_t n, double ticks) { static auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 { return glm::translate(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z)); }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aivector3d(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue); aiVectorKey anchor; anchor.mTime = ticks; auto right_ptr =
; auto left_ptr = right_ptr - 1; float factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); return mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor); } glm::mat4 Mesh::InterpolateRotationMatrix(aiQuatKey* keys, uint32_t n, double ticks) { static auto mat4_from_aiquaternion = [](aiQuaternion quaternion) -> glm::mat4 { auto rotation_matrix = quaternion.GetMatrix(); glm::mat4 res(1); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) res[j][i] = rotation_matrix[i][j]; return res; }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aiquaternion(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aiquaternion(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aiquaternion(keys[n - 1].mValue); aiQuatKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiQuatKey& a, const aiQuatKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; double factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); aiQuaternion out; aiQuaternion::Interpolate(out, left_ptr->mValue, right_ptr->mValue, factor); return mat4_from_aiquaternion(out); } glm::mat4 Mesh::InterpolateScalingMatrix(aiVectorKey* keys, uint32_t n, double ticks) { static auto mat4_from_aivector3d = [](aiVector3D vector) -> glm::mat4 { return glm::scale(glm::mat4(1), glm::vec3(vector.x, vector.y, vector.z)); }; if (n == 0) return glm::mat4(1); if (n == 1) return mat4_from_aivector3d(keys->mValue); if (ticks <= keys[0].mTime) return mat4_from_aivector3d(keys[0].mValue); if (keys[n - 1].mTime <= ticks) return mat4_from_aivector3d(keys[n - 1].mValue); aiVectorKey anchor; anchor.mTime = ticks; auto right_ptr = std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) { return a.mTime < b.mTime; }); auto left_ptr = right_ptr - 1; float factor = (ticks - left_ptr->mTime) / (right_ptr->mTime - left_ptr->mTime); return mat4_from_aivector3d(left_ptr->mValue * (1.0f - factor) + right_ptr->mValue * factor); } }
std::upper_bound(keys, keys + n, anchor, [](const aiVectorKey& a, const aiVectorKey& b) { return a.mTime < b.mTime; })
call_expression
[ { "content": "struct aiMeshKey\n\n{\n\n /** The time of this key */\n\n double mTime;\n\n\n\n /** Index into the aiMesh::mAnimMeshes array of the\n\n * mesh corresponding to the #aiMeshAnim hosting this\n\n * key frame. The referenced anim mesh is evaluated\n\n * according to the rules d...
C++
src/common/partial.hh
sergeyfilip/objectstore
e2d0c86134c46c77fb143f7198d13fab7f5b1ea5
#ifndef COMMON_PARTIAL_HH #define COMMON_PARTIAL_HH template <typename R> class BindBase { public: virtual R operator()() const = 0; virtual ~BindBase() { } virtual BindBase* clone() const = 0; }; template <typename R, typename Obj> class BindBaseM { public: virtual R operator()(Obj&) const = 0; virtual ~BindBaseM() { } virtual BindBaseM* clone() const = 0; }; template <typename R, typename F1> class BindF1Base { public: virtual R operator()(F1) const = 0; virtual ~BindF1Base() { } virtual BindF1Base* clone() const = 0; }; template <typename R> class Bind0 : public BindBase<R> { public: Bind0(R (*f)()) : f(f) { } virtual ~Bind0() { } R operator()() const { return f(); } R (*function() const)() { return f; } Bind0<R>* clone() const { return new Bind0<R>(*this); } private: R (*f)(); }; template <typename R, typename Obj> class Bind0M : public BindBaseM<R, Obj> { public: Bind0M(R (Obj::*f)()) : f(f) { } virtual ~Bind0M() { } R operator()(Obj& obj) const { return (obj.*f)(); } R (Obj::*function() const)() { return f; } Bind0M<R, Obj>* clone() const { return new Bind0M<R, Obj>(*this); } private: R (Obj::*f)(); }; template <typename R, typename F1> class Bind0F1 : public BindF1Base<R,F1> { public: Bind0F1(R (*f)(F1)) : f(f) { } virtual ~Bind0F1() { } R operator()(F1 arg) const { return f(arg); } R (*function(F1) const)() { return f; } Bind0F1<R,F1>* clone() const { return new Bind0F1<R,F1>(*this); } private: R (*f)(F1); }; template <typename R, typename A1> class Bind1 : public BindBase<R> { public: Bind1(R (*f)(A1), A1 a1) : f(f), a1(a1) { } virtual ~Bind1() { } R operator()() const { return f(a1); } R (*function() const)(A1) { return f; } Bind1<R,A1>* clone() const { return new Bind1<R,A1>(*this); } private: R (*f)(A1); A1 a1; }; template <typename R, typename Obj, typename A1> class Bind1M : public BindBaseM<R, Obj> { public: Bind1M(R (Obj::*f)(A1), A1 a1) : f(f), a1(a1) { } virtual ~Bind1M() { } R operator()(Obj& obj) const { return (obj.*f)(a1); } R (Obj::*function() const)(A1) { return f; } Bind1M<R, Obj, A1>* clone() const { return new Bind1M<R, Obj, A1>(*this); } private: R (Obj::*f)(A1); A1 a1; }; template <typename R, typename A1, typename A2> class Bind2 : public BindBase<R> { public: Bind2(R (*f)(const A1, const A2), A1 a1, A2 a2) : f(f), a1(a1), a2(a2) { } virtual ~Bind2() { } R operator()() const { return f(a1,a2); } R (*function() const)(A1, A2) { return f; } Bind2<R,A1,A2>* clone() const { return new Bind2<R,A1,A2>(*this); } private: R (*f)(A1, A2); A1 a1; A2 a2; }; template <typename R, typename Obj, typename A1, typename A2> class Bind2M : public BindBaseM<R, Obj> { public: Bind2M(R (Obj::*f)(const A1, const A2), A1 a1, A2 a2) : f(f), a1(a1), a2(a2) { } virtual ~Bind2M() { } R operator()(Obj& obj) const { return (obj.*f)(a1,a2); } R (Obj::*function() const)(A1, A2) { return f; } Bind2M<R,Obj,A1,A2>* clone() const { return new Bind2M<R,Obj,A1,A2>(*this); } private: R (Obj::*f)(A1, A2); A1 a1; A2 a2; }; template <typename R, typename A1, typename A2, typename A3> class Bind3 : public BindBase<R> { public: Bind3(R (*f)(const A1, const A2, const A3), A1 a1, A2 a2, A3 a3) : f(f), a1(a1), a2(a2), a3(a3) { } virtual ~Bind3() { } R operator()() const { return f(a1,a2,a3); } R (*function() const)(A1, A2, A3) { return f; } Bind3<R,A1,A2,A3>* clone() const { return new Bind3<R,A1,A2,A3>(*this); } private: R (*f)(A1, A2, A3); A1 a1; A2 a2; A3 a3; }; template <class InstanceT, class Out> class Closure0 : public BindBase<Out> { public: inline Closure0(InstanceT *i, Out (InstanceT::*f)()): instance(i), fun(f) {} virtual ~Closure0() { } Out operator() () const { return (instance->*fun)(); } Closure0<InstanceT,Out>* clone() const { return new Closure0<InstanceT,Out>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(); }; template <class Out> inline Bind0<Out> papply(Out (*f)()) { return Bind0<Out>(f); } template <class Out, class Obj> inline Bind0M<Out, Obj> papply(Out (Obj::*f)()) { return Bind0M<Out, Obj>(f); } template <class Out, class In> inline Bind0F1<Out,In> papply(Out (*f)(In)) { return Bind0F1<Out,In>(f); } template <class Out, class In> inline Bind1<Out,In> papply(Out (*f)(In), In in) { return Bind1<Out,In>(f, in); } template <class Out, class Obj, class In> inline Bind1M<Out, Obj, In> papply(Out (Obj::*f)(In), In in) { return Bind1M<Out, Obj, In>(f, in); } template <class Out, class In1, class In2> inline Bind2<Out,In1,In2> papply(Out (*f)(In1,In2), In1 in1, In2 in2) { return Bind2<Out,In1,In2>(f, in1, in2); } template <class Out, class Obj, class In1, class In2> inline Bind2M<Out, Obj, In1, In2> papply(Out (Obj::*f)(In1,In2), In1 in1, In2 in2) { return Bind2M<Out, Obj, In1, In2>(f, in1, in2); } template <class Out, class In1, class In2, class In3> inline Bind3<Out,In1,In2,In3> papply(Out (*f)(In1,In2,In3), In1 in1, In2 in2, In3 in3) { return Bind3<Out,In1,In2,In3>(f, in1, in2, in3); } template <class InstanceT, class Out> class Closure0c : public BindBase<Out> { public: inline Closure0c(const InstanceT *i, Out (InstanceT::*f)() const): instance(i), fun(f) {} virtual ~Closure0c() { } Out operator() () const { return (instance->*fun)(); } Closure0c<InstanceT,Out>* clone() const { return new Closure0c<InstanceT,Out>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)() const; }; template <class InstanceT, class Out, class In> class Closure1 : public BindF1Base<Out,In> { public: inline Closure1(InstanceT *i, Out (InstanceT::*f)(In)): instance(i), fun(f) {} virtual ~Closure1() { } Out operator() (In in) const { return (instance->*fun)(in); } Closure1<InstanceT,Out,In>* clone() const { return new Closure1<InstanceT,Out,In>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(In); }; template <class InstanceT, class Out, class In> class Closure1c : public BindF1Base<Out,In> { public: inline Closure1c(const InstanceT *i, Out (InstanceT::*f)(In) const): instance(i), fun(f) {} virtual ~Closure1c() { } Out operator() (In in) const { return (instance->*fun)(in); } Closure1c<InstanceT,Out,In>* clone() const { return new Closure1c<InstanceT,Out,In>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(In) const; }; template <class InstanceT, class Out, class Bound> class Closure0B1 : public BindBase<Out> { public: template <class C> inline Closure0B1(C *i, Out (C::*f)(Bound), Bound b): instance(i), fun(f), bound(b) { } virtual ~Closure0B1() { } Out operator() () const { return (instance->*fun)(bound); } Closure0B1<InstanceT,Out,Bound>* clone() const { return new Closure0B1<InstanceT,Out,Bound>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(Bound); Bound bound; }; template <class InstanceT, class Out, class Bound> class Closure0B1c : public BindBase<Out> { public: template <class C> inline Closure0B1c(const C *i, Out (C::*f)(Bound) const, Bound b): instance(i), fun(f), bound(b) { } virtual ~Closure0B1c() { } Out operator() () const { return (instance->*fun)(bound); } Closure0B1c<InstanceT,Out,Bound>* clone() const { return new Closure0B1c<InstanceT,Out,Bound>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound) const; Bound bound; }; template <class InstanceT, class Out, class Bound1, class Bound2> class Closure0B2 : public BindBase<Out> { public: template <class C> inline Closure0B2(C *i, Out (C::*f)(Bound1,Bound2), Bound1 b1, Bound2 b2): instance(i), fun(f), bound1(b1), bound2(b2) { } virtual ~Closure0B2() { } Out operator() () const { return (instance->*fun)(bound1,bound2); } Closure0B2<InstanceT,Out,Bound1,Bound2>* clone() const { return new Closure0B2<InstanceT,Out,Bound1,Bound2>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2); Bound1 bound1; Bound2 bound2; }; template <class InstanceT, class Out, class Bound1, class Bound2> class Closure0B2c : public BindBase<Out> { public: template <class C> inline Closure0B2c(const C *i, Out (C::*f)(Bound1,Bound2) const, Bound1 b1, Bound2 b2) : instance(i), fun(f), bound1(b1), bound2(b2) { } virtual ~Closure0B2c() { } Out operator() () const { return (instance->*fun)(bound1,bound2); } Closure0B2c<InstanceT,Out,Bound1,Bound2>* clone() const { return new Closure0B2c<InstanceT,Out,Bound1,Bound2>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2) const; Bound1 bound1; Bound2 bound2; }; template <class InstanceT, class Out, class Bound1, class Bound2, class Bound3> class Closure0B3c : public BindBase<Out> { public: template <class C> inline Closure0B3c(const C *i, Out (C::*f)(Bound1,Bound2,Bound3) const, Bound1 b1, Bound2 b2, Bound3 b3) : instance(i), fun(f), bound1(b1), bound2(b2), bound3(b3) { } virtual ~Closure0B3c() { } Out operator() () const { return (instance->*fun)(bound1,bound2,bound3); } Closure0B3c<InstanceT,Out,Bound1,Bound2,Bound3>* clone() const { return new Closure0B3c<InstanceT,Out,Bound1,Bound2,Bound3>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2,Bound3) const; Bound1 bound1; Bound2 bound2; Bound3 bound3; }; template <class C, class Out> inline Closure0c<const C,Out> papply(const C *i, Out (C::*f)() const) { return Closure0c<const C, Out>(i, f); } template <class C, class Out> inline Closure0<C,Out> papply(C *i, Out (C::*f)()) { return Closure0<C, Out>(i, f); } template <class Out, class C, class In> inline Closure1c<C,Out,In> papply(const C *i, Out (C::*f)(In) const) { return Closure1c<C, Out, In>(i, f); } template <class Out, class C, class In> inline Closure1<C,Out,In> papply(C *i, Out (C::*f)(In)) { return Closure1<C, Out, In>(i, f); } template <class Out, class C, class In> inline Closure0B1c<C,Out,In> papply(const C *i, Out (C::*f)(In) const, In in) { return Closure0B1c<C, Out, In>(i, f, in); } template <class Out, class C, class In> inline Closure0B1<C,Out,In> papply(C *i, Out (C::*f)(In), In in) { return Closure0B1<C, Out, In>(i, f, in); } template <class Out, class C, class In1, class In2> inline Closure0B2c<C,Out,In1,In2> papply(const C *i, Out (C::*f)(In1,In2) const, In1 in1, In2 in2) { return Closure0B2c<C, Out, In1,In2>(i, f, in1, in2); } template <class Out, class C, class In1, class In2> inline Closure0B2<C,Out,In1,In2> papply(C *i, Out (C::*f)(In1,In2), In1 in1, In2 in2) { return Closure0B2<C, Out, In1,In2>(i, f, in1, in2); } template <class Out, class C, class In1, class In2, class In3> inline Closure0B3c<C,Out,In1,In2,In3> papply(const C *i, Out (C::*f)(In1,In2,In3) const, In1 in1, In2 in2, In3 in3) { return Closure0B3c<C, Out, In1,In2,In3>(i, f, in1, in2, in3); } #endif
#ifndef COMMON_PARTIAL_HH #define COMMON_PARTIAL_HH template <typename R> class BindBase { public: virtual R operator()() const = 0; virtual ~BindBase() { } virtual BindBase* clone() const = 0; }; template <typename R, typename Obj> class BindBaseM { public: virtual R operator()(Obj&) const = 0; virtual ~BindBaseM() { } virtual BindBaseM* clone() const = 0; }; template <typename R, typename F1> class BindF1Base { public: virtual R operator()(F1) const = 0; virtual ~BindF1Base() { } virtual BindF1Base* clone() const = 0; }; template <typename R> class Bind0 : public BindBase<R> { public: Bind0(R (*f)()) : f(f) { } virtual ~Bind0() { } R operator()() const { return f(); } R (*function() const)() { return f; } Bind0<R>* clone() const { return new Bind0<R>(*this); } private: R (*f)(); }; template <typename R, typename Obj> class Bind0M : public BindBaseM<R, Obj> { public: Bind0M(R (Obj::*f)()) : f(f) { } virtual ~Bind0M() { } R operator()(Obj& obj) const { return (obj.*f)(); } R (Obj::*function() const)() { return f; } Bind0M<R, Obj>* clone() const { return new Bind0M<R, Obj>(*this); } private: R (Obj::*f)(); }; template <typename R, typename F1> class Bind0F1 : public BindF1Base<R,F1> { public: Bind0F1(R (*f)(F1)) : f(f) { } virtual ~Bind0F1() { } R operator()(F1 arg) const { return f(arg); } R (*function(F1) const)() { return f; } Bind0F1<R,F1>* clone() const { return new Bind0F1<R,F1>(*this); } private: R (*f)(F1); }; template <typename R, typename A1> class Bind1 : public BindBase<R> { public: Bind1(R (*f)(A1), A1 a1) : f(f), a1(a1) { } virtual ~Bind1() { } R operator()() const { return f(a1); } R (*function() const)(A1) { return f; } Bind1<R,A1>* clone() const { return new Bind1<R,A1>(*this); } private: R (*f)(A1); A1 a1; }; template <typename R, typename Obj, typename A1> class Bind1M : public BindBaseM<R, Obj> { public: Bind1M(R (Obj::*f)(A1), A1 a1) : f(f), a1(a1) { } virtual ~Bind1M() { } R operator()(Obj& obj) const { return (obj.*f)(a1); } R (Obj::*function() const)(A1) { return f; } Bind1M<R, Obj, A1>* clone() const { return new Bind1M<R, Obj, A1>(*this); } private: R (Obj::*f)(A1); A1 a1; }; template <typename R, typename A1, typename A2> class Bind2 : public BindBase<R> { public: Bind2(R (*f)(const A1, const A2), A1 a1, A2 a2) : f(f), a1(a1), a2(a2) { } virtual ~Bind2() { } R operator()() const { return f(a1,a2); } R (*function() const)(A1, A2) { return f; } Bind2<R,A1,A2>* clone() const { return new Bind2<R,A1,A2>(*this); } private: R (*f)(A1, A2); A1 a1; A2 a2; }; template <typename R, typename Obj, typename A1, typename A2> class Bind2M : public BindBaseM<R, Obj> { public: Bind2M(R (Obj::*f)(const A1, const A2), A1 a1, A2 a2) : f(f), a1(a1), a2(a2) { } virtual ~Bind2M() { } R operator()(Obj& obj) const { return (obj.*f)(a1,a2); } R (Obj::*function() const)(A1, A2) { return f; } Bind2M<R,Obj,A1,A2>* clone() const { return new Bind2M<R,Obj,A1,A2>(*this); } private: R (Obj::*f)(A1, A2); A1 a1; A2 a2; }; template <typename R, typename A1, typename A2, typename A3> class Bind3 : public BindBase<R> { public: Bind3(R (*f)(const A1, const A2, const A3), A1 a1, A2 a2, A3 a3) : f(f), a1(a1), a2(a2), a3(a3) { } virtual ~Bind3() { } R operator()() const { return f(a1,a2,a3); } R (*function() const)(A1, A2, A3) { return f; } Bind3<R,A1,A2,A3>* clone() const { return new Bind3<R,A1,A2,A3>(*this); } private: R (*f)(A1, A2, A3); A1 a1; A2 a2; A3 a3; }; template <class InstanceT, class Out> class Closure0 : public BindBase<Out> { public: inline Closure0(InstanceT *i, Out (InstanceT::*f)()): instance(i), fun(f) {} virtual ~Closure0() { } Out operator() () const { return (instance->*fun)(); } Closure0<InstanceT,Out>* clone() const { return new Closure0<InstanceT,Out>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(); }; template <class Out> inline Bind0<Out> papply(Out (*f)()) { return Bind0<Out>(f); } template <class Out, class Obj> inline Bind0M<Out, Obj> papply(Out (Obj::*f)()) { return Bind0M<Out, Obj>(f); } template <class Out, class In> inline Bind0F1<Out,In> papply(Out (*f)(In)) { return Bind0F1<Out,In>(f); } template <class Out, class In> inline Bind1<Out,In> papply(Out (*f)(In), In in) { return Bind1<Out,In>(f, in); } template <class Out, class Obj, class In> inline Bind1M<Out, Obj, I
*fun)(bound1,bound2,bound3); } Closure0B3c<InstanceT,Out,Bound1,Bound2,Bound3>* clone() const { return new Closure0B3c<InstanceT,Out,Bound1,Bound2,Bound3>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2,Bound3) const; Bound1 bound1; Bound2 bound2; Bound3 bound3; }; template <class C, class Out> inline Closure0c<const C,Out> papply(const C *i, Out (C::*f)() const) { return Closure0c<const C, Out>(i, f); } template <class C, class Out> inline Closure0<C,Out> papply(C *i, Out (C::*f)()) { return Closure0<C, Out>(i, f); } template <class Out, class C, class In> inline Closure1c<C,Out,In> papply(const C *i, Out (C::*f)(In) const) { return Closure1c<C, Out, In>(i, f); } template <class Out, class C, class In> inline Closure1<C,Out,In> papply(C *i, Out (C::*f)(In)) { return Closure1<C, Out, In>(i, f); } template <class Out, class C, class In> inline Closure0B1c<C,Out,In> papply(const C *i, Out (C::*f)(In) const, In in) { return Closure0B1c<C, Out, In>(i, f, in); } template <class Out, class C, class In> inline Closure0B1<C,Out,In> papply(C *i, Out (C::*f)(In), In in) { return Closure0B1<C, Out, In>(i, f, in); } template <class Out, class C, class In1, class In2> inline Closure0B2c<C,Out,In1,In2> papply(const C *i, Out (C::*f)(In1,In2) const, In1 in1, In2 in2) { return Closure0B2c<C, Out, In1,In2>(i, f, in1, in2); } template <class Out, class C, class In1, class In2> inline Closure0B2<C,Out,In1,In2> papply(C *i, Out (C::*f)(In1,In2), In1 in1, In2 in2) { return Closure0B2<C, Out, In1,In2>(i, f, in1, in2); } template <class Out, class C, class In1, class In2, class In3> inline Closure0B3c<C,Out,In1,In2,In3> papply(const C *i, Out (C::*f)(In1,In2,In3) const, In1 in1, In2 in2, In3 in3) { return Closure0B3c<C, Out, In1,In2,In3>(i, f, in1, in2, in3); } #endif
n> papply(Out (Obj::*f)(In), In in) { return Bind1M<Out, Obj, In>(f, in); } template <class Out, class In1, class In2> inline Bind2<Out,In1,In2> papply(Out (*f)(In1,In2), In1 in1, In2 in2) { return Bind2<Out,In1,In2>(f, in1, in2); } template <class Out, class Obj, class In1, class In2> inline Bind2M<Out, Obj, In1, In2> papply(Out (Obj::*f)(In1,In2), In1 in1, In2 in2) { return Bind2M<Out, Obj, In1, In2>(f, in1, in2); } template <class Out, class In1, class In2, class In3> inline Bind3<Out,In1,In2,In3> papply(Out (*f)(In1,In2,In3), In1 in1, In2 in2, In3 in3) { return Bind3<Out,In1,In2,In3>(f, in1, in2, in3); } template <class InstanceT, class Out> class Closure0c : public BindBase<Out> { public: inline Closure0c(const InstanceT *i, Out (InstanceT::*f)() const): instance(i), fun(f) {} virtual ~Closure0c() { } Out operator() () const { return (instance->*fun)(); } Closure0c<InstanceT,Out>* clone() const { return new Closure0c<InstanceT,Out>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)() const; }; template <class InstanceT, class Out, class In> class Closure1 : public BindF1Base<Out,In> { public: inline Closure1(InstanceT *i, Out (InstanceT::*f)(In)): instance(i), fun(f) {} virtual ~Closure1() { } Out operator() (In in) const { return (instance->*fun)(in); } Closure1<InstanceT,Out,In>* clone() const { return new Closure1<InstanceT,Out,In>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(In); }; template <class InstanceT, class Out, class In> class Closure1c : public BindF1Base<Out,In> { public: inline Closure1c(const InstanceT *i, Out (InstanceT::*f)(In) const): instance(i), fun(f) {} virtual ~Closure1c() { } Out operator() (In in) const { return (instance->*fun)(in); } Closure1c<InstanceT,Out,In>* clone() const { return new Closure1c<InstanceT,Out,In>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(In) const; }; template <class InstanceT, class Out, class Bound> class Closure0B1 : public BindBase<Out> { public: template <class C> inline Closure0B1(C *i, Out (C::*f)(Bound), Bound b): instance(i), fun(f), bound(b) { } virtual ~Closure0B1() { } Out operator() () const { return (instance->*fun)(bound); } Closure0B1<InstanceT,Out,Bound>* clone() const { return new Closure0B1<InstanceT,Out,Bound>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(Bound); Bound bound; }; template <class InstanceT, class Out, class Bound> class Closure0B1c : public BindBase<Out> { public: template <class C> inline Closure0B1c(const C *i, Out (C::*f)(Bound) const, Bound b): instance(i), fun(f), bound(b) { } virtual ~Closure0B1c() { } Out operator() () const { return (instance->*fun)(bound); } Closure0B1c<InstanceT,Out,Bound>* clone() const { return new Closure0B1c<InstanceT,Out,Bound>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound) const; Bound bound; }; template <class InstanceT, class Out, class Bound1, class Bound2> class Closure0B2 : public BindBase<Out> { public: template <class C> inline Closure0B2(C *i, Out (C::*f)(Bound1,Bound2), Bound1 b1, Bound2 b2): instance(i), fun(f), bound1(b1), bound2(b2) { } virtual ~Closure0B2() { } Out operator() () const { return (instance->*fun)(bound1,bound2); } Closure0B2<InstanceT,Out,Bound1,Bound2>* clone() const { return new Closure0B2<InstanceT,Out,Bound1,Bound2>(*this); } private: InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2); Bound1 bound1; Bound2 bound2; }; template <class InstanceT, class Out, class Bound1, class Bound2> class Closure0B2c : public BindBase<Out> { public: template <class C> inline Closure0B2c(const C *i, Out (C::*f)(Bound1,Bound2) const, Bound1 b1, Bound2 b2) : instance(i), fun(f), bound1(b1), bound2(b2) { } virtual ~Closure0B2c() { } Out operator() () const { return (instance->*fun)(bound1,bound2); } Closure0B2c<InstanceT,Out,Bound1,Bound2>* clone() const { return new Closure0B2c<InstanceT,Out,Bound1,Bound2>(*this); } private: const InstanceT *instance; Out (InstanceT::*fun)(Bound1,Bound2) const; Bound1 bound1; Bound2 bound2; }; template <class InstanceT, class Out, class Bound1, class Bound2, class Bound3> class Closure0B3c : public BindBase<Out> { public: template <class C> inline Closure0B3c(const C *i, Out (C::*f)(Bound1,Bound2,Bound3) const, Bound1 b1, Bound2 b2, Bound3 b3) : instance(i), fun(f), bound1(b1), bound2(b2), bound3(b3) { } virtual ~Closure0B3c() { } Out operator() () const { return (instance->
random
[]
C++
server/modules/routing/binlogrouter/blr_event.cc
tut-blog/MaxScale
cabd6dba0665cb8025c694acf98cffaa68d10de0
#include "blr.hh" #include <inttypes.h> #include <maxscale/alloc.h> bool blr_handle_one_event(MXS_ROUTER* instance, REP_HEADER& hdr, uint8_t* ptr, uint32_t len, int semisync) { ROUTER_INSTANCE* router = static_cast<ROUTER_INSTANCE*>(instance); router->lastEventReceived = hdr.event_type; router->lastEventTimestamp = hdr.timestamp; pthread_mutex_lock(&router->binlog_lock); if (router->trx_safe == 0 || (router->trx_safe && router->pending_transaction.state == BLRM_NO_TRANSACTION)) { router->binlog_position = router->current_pos; router->current_safe_event = router->current_pos; } pthread_mutex_unlock(&router->binlog_lock); if (router->trx_safe) { if (router->mariadb10_compat && hdr.event_type == MARIADB10_GTID_EVENT) { uint64_t n_sequence; uint32_t domainid; unsigned int flags; n_sequence = extract_field(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN, 64); domainid = extract_field(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 8, 32); flags = *(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 8 + 4); pthread_mutex_lock(&router->binlog_lock); router->pending_transaction.standalone = flags & MARIADB_FL_STANDALONE; if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { MXS_ERROR("A MariaDB 10 transaction " "is already open " "@ %lu (GTID %u-%u-%lu) and " "a new one starts @ %lu", router->binlog_position, domainid, hdr.serverid, n_sequence, router->current_pos); } router->pending_transaction.state = BLRM_TRANSACTION_START; if (router->mariadb10_gtid) { char mariadb_gtid[GTID_MAX_LEN + 1]; snprintf(mariadb_gtid, GTID_MAX_LEN, "%u-%u-%lu", domainid, hdr.serverid, n_sequence); MXS_DEBUG("MariaDB GTID received: (%s). Current file %s, pos %lu", mariadb_gtid, router->binlog_name, router->current_pos); strcpy(router->pending_transaction.gtid, mariadb_gtid); router->pending_transaction.gtid_elms.domain_id = domainid; router->pending_transaction.gtid_elms.server_id = hdr.serverid; router->pending_transaction.gtid_elms.seq_no = n_sequence; } router->pending_transaction.start_pos = router->current_pos; router->pending_transaction.end_pos = 0; pthread_mutex_unlock(&router->binlog_lock); } if (hdr.event_type == QUERY_EVENT) { char* statement_sql; int db_name_len, var_block_len, statement_len; db_name_len = ptr[MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4]; var_block_len = ptr[MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2]; statement_len = len - (MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2 + 2 \ + var_block_len + 1 + db_name_len); statement_sql = static_cast<char*>(MXS_CALLOC(1, statement_len + 1)); MXS_ABORT_IF_NULL(statement_sql); memcpy(statement_sql, (char*)ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2 + 2 \ + var_block_len + 1 + db_name_len, statement_len); pthread_mutex_lock(&router->binlog_lock); if (strncmp(statement_sql, "BEGIN", 5) == 0) { if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { MXS_ERROR("A transaction is already open " "@ %lu and a new one starts @ %lu", router->binlog_position, router->current_pos); } router->pending_transaction.state = BLRM_TRANSACTION_START; router->pending_transaction.start_pos = router->current_pos; router->pending_transaction.end_pos = 0; } if (strncmp(statement_sql, "COMMIT", 6) == 0) { router->pending_transaction.state = BLRM_COMMIT_SEEN; } if (router->pending_transaction.state > BLRM_NO_TRANSACTION && router->pending_transaction.standalone) { router->pending_transaction.state = BLRM_STANDALONE_SEEN; } pthread_mutex_unlock(&router->binlog_lock); MXS_FREE(statement_sql); } if (hdr.event_type == XID_EVENT) { pthread_mutex_lock(&router->binlog_lock); if (router->pending_transaction.state >= BLRM_TRANSACTION_START) { router->pending_transaction.state = BLRM_XID_EVENT_SEEN; } pthread_mutex_unlock(&router->binlog_lock); } } int event_limit = router->mariadb10_compat ? MAX_EVENT_TYPE_MARIADB10 : MAX_EVENT_TYPE; if (hdr.event_type <= event_limit) { router->stats.events[hdr.event_type]++; } else { char errmsg[BINLOG_ERROR_MSG_LEN + 1]; sprintf(errmsg, "Event type [%d] not supported yet. " "Check master server configuration and " "disable any new feature. " "Replication from master has been stopped.", hdr.event_type); MXS_ERROR("%s", errmsg); pthread_mutex_lock(&router->lock); char* old_errmsg = router->m_errmsg; router->m_errmsg = MXS_STRDUP_A(errmsg); router->m_errno = 1235; router->master_state = BLRM_SLAVE_STOPPED; router->stats.n_binlog_errors++; pthread_mutex_unlock(&router->lock); MXS_FREE(old_errmsg); blr_master_close(router); return false; } if (hdr.event_type == FORMAT_DESCRIPTION_EVENT && hdr.next_pos == 0) { router->stats.n_fakeevents++; MXS_DEBUG("Replication Fake FORMAT_DESCRIPTION_EVENT event. " "Binlog %s @ %lu.", router->binlog_name, router->current_pos); } else { if (hdr.event_type == HEARTBEAT_EVENT) { #ifdef SHOW_EVENTS printf("Replication heartbeat\n"); #endif MXS_DEBUG("Replication heartbeat. " "Binlog %s @ %lu.", router->binlog_name, router->current_pos); router->stats.n_heartbeats++; if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { router->stats.lastReply = time(0); } } else if (hdr.flags != LOG_EVENT_ARTIFICIAL_F) { if (hdr.event_type == ROTATE_EVENT) { pthread_mutex_lock(&router->binlog_lock); router->rotating = 1; pthread_mutex_unlock(&router->binlog_lock); } uint32_t offset = MYSQL_HEADER_LEN + 1; if (blr_write_binlog_record(router, &hdr, len - offset, ptr + offset) == 0) { blr_master_close(router); blr_start_master_in_main(router); return false; } if (hdr.event_type == ROTATE_EVENT) { if (!blr_rotate_event(router, ptr + offset, &hdr)) { blr_master_close(router); blr_start_master_in_main(router); return false; } } if (router->master_semi_sync != MASTER_SEMISYNC_NOT_AVAILABLE && semisync == BLR_MASTER_SEMI_SYNC_ACK_REQ) { MXS_DEBUG("%s: binlog record in file %s, pos %lu has " "SEMI_SYNC_ACK_REQ and needs a Semi-Sync ACK packet to " "be sent to the master server [%s]:%d", router->service->name, router->binlog_name, router->current_pos, router->service->dbref->server->address, router->service->dbref->server->port); blr_send_semisync_ack(router, hdr.next_pos); semisync = 0; } pthread_mutex_lock(&router->binlog_lock); if (router->trx_safe == 0 || (router->trx_safe && router->pending_transaction.state == BLRM_NO_TRANSACTION)) { router->binlog_position = router->current_pos; router->current_safe_event = router->last_event_pos; pthread_mutex_unlock(&router->binlog_lock); blr_notify_all_slaves(router); } else { if (router->pending_transaction.state > BLRM_TRANSACTION_START) { if (router->mariadb10_compat) { router->pending_transaction.end_pos = router->current_pos; if (router->mariadb10_compat && router->mariadb10_gtid) { strcpy(router->last_mariadb_gtid, router->pending_transaction.gtid); blr_save_mariadb_gtid(router); } } pthread_mutex_unlock(&router->binlog_lock); blr_notify_all_slaves(router); pthread_mutex_lock(&router->binlog_lock); router->binlog_position = router->current_pos; router->pending_transaction.state = BLRM_NO_TRANSACTION; router->pending_transaction.standalone = false; pthread_mutex_unlock(&router->binlog_lock); } else { pthread_mutex_unlock(&router->binlog_lock); } } } else { router->stats.n_artificial++; MXS_DEBUG("Artificial event not written " "to disk or distributed. " "Type 0x%x, Length %d, Binlog " "%s @ %lu.", hdr.event_type, hdr.event_size, router->binlog_name, router->current_pos); ptr += MYSQL_HEADER_LEN + 1; if (hdr.event_type == ROTATE_EVENT) { if (!blr_handle_fake_rotate(router, &hdr, ptr)) { blr_master_close(router); blr_start_master_in_main(router); return false; } MXS_INFO("Fake ROTATE_EVENT received: " "binlog file %s, pos %" PRIu64 "", router->binlog_name, router->current_pos); } else if (hdr.event_type == MARIADB10_GTID_GTID_LIST_EVENT) { blr_handle_fake_gtid_list(router, &hdr, ptr); } } } return true; }
#include "blr.hh" #include <inttypes.h> #include <maxscale/alloc.h> bool blr_handle_one_event(MXS_ROUTER* instance, REP_HEADER& hdr, uint8_t* ptr, uint32_t len, int semisync) { ROUTER_INSTANCE* router = static_cast<ROUTER_INSTANCE*>(instance); router->lastEventReceived = hdr.event_type; router->lastEventTimestamp = hdr.timestamp; pthread_mutex_lock(&router->binlog_lock); if (router->trx_safe == 0 || (router->trx_safe && router->pending_transaction.state == BLRM_NO_TRANSACTION)) { router->binlog_position = router->current_pos; router->current_safe_event = router->current_pos; } pthread_mutex_unlock(&router->binlog_lock); if (router->trx_safe) { if (router->mariadb10_compat && hdr.event_type == MARIADB10_GTID_EVENT) { uint64_t n_sequence; uint32_t domainid; unsigned int flags; n_sequence = extract_field(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN, 64); domainid = extract_field(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 8, 32); flags = *(ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 8 + 4); pthread_mutex_lock(&router->binlog_lock); router->pending_transaction.standalone = flags & MARIADB_FL_STANDALONE; if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { MXS_ERROR("A MariaDB 10 transaction " "is already open " "@ %lu (GTID %u-%u-%lu) and " "a new one starts @ %lu", router->binlog_position, domainid, hdr.serverid, n_sequence, router->current_pos); } router->pending_transaction.state = BLRM_TRANSACTION_START; if (router->mariadb10_gtid) { char mariadb_gtid[GTID_MAX_LEN + 1]; snprintf(mariadb_gtid, GTID_MAX_LEN, "%u-%u-%lu", domainid, hdr.serverid, n_sequence); MXS_DEBUG("MariaDB GTID received: (%s). Current file %s, pos %lu", mariadb_gtid, router->binlog_name, router->current_pos); strcpy(router->pending_transaction.gtid, mariadb_gtid); router->pending_transaction.gtid_elms.domain_id = domainid; router->pending_transaction.gtid_elms.server_id = hdr.serverid; router->pending_transaction.gtid_elms.seq_no = n_sequence; } router->pending_transaction.start_pos = router->current_pos; router->pending_transaction.end_pos = 0; pthread_mutex_unlock(&router->binlog_lock); } if (hdr.event_type == QUERY_EVENT) { char* statement_sql; int db_name_len, var_block_len, statement_len; db_name_len = ptr[MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4]; var_block_len = ptr[MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2]; statement_len = len - (MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2 + 2 \ + var_block_len + 1 + db_name_len); statement_sql = static_cast<char*>(MXS_CALLOC(1, statement_len + 1)); MXS_ABORT_IF_NULL(statement_sql); memcpy(statement_sql, (char*)ptr + MYSQL_HEADER_LEN + 1 + BINLOG_EVENT_HDR_LEN + 4 + 4 + 1 + 2 + 2 \ + var_block_len + 1 + db_name_len, statement_len); pthread_mutex_lock(&router->binlog_lock);
if (strncmp(statement_sql, "COMMIT", 6) == 0) { router->pending_transaction.state = BLRM_COMMIT_SEEN; } if (router->pending_transaction.state > BLRM_NO_TRANSACTION && router->pending_transaction.standalone) { router->pending_transaction.state = BLRM_STANDALONE_SEEN; } pthread_mutex_unlock(&router->binlog_lock); MXS_FREE(statement_sql); } if (hdr.event_type == XID_EVENT) { pthread_mutex_lock(&router->binlog_lock); if (router->pending_transaction.state >= BLRM_TRANSACTION_START) { router->pending_transaction.state = BLRM_XID_EVENT_SEEN; } pthread_mutex_unlock(&router->binlog_lock); } } int event_limit = router->mariadb10_compat ? MAX_EVENT_TYPE_MARIADB10 : MAX_EVENT_TYPE; if (hdr.event_type <= event_limit) { router->stats.events[hdr.event_type]++; } else { char errmsg[BINLOG_ERROR_MSG_LEN + 1]; sprintf(errmsg, "Event type [%d] not supported yet. " "Check master server configuration and " "disable any new feature. " "Replication from master has been stopped.", hdr.event_type); MXS_ERROR("%s", errmsg); pthread_mutex_lock(&router->lock); char* old_errmsg = router->m_errmsg; router->m_errmsg = MXS_STRDUP_A(errmsg); router->m_errno = 1235; router->master_state = BLRM_SLAVE_STOPPED; router->stats.n_binlog_errors++; pthread_mutex_unlock(&router->lock); MXS_FREE(old_errmsg); blr_master_close(router); return false; } if (hdr.event_type == FORMAT_DESCRIPTION_EVENT && hdr.next_pos == 0) { router->stats.n_fakeevents++; MXS_DEBUG("Replication Fake FORMAT_DESCRIPTION_EVENT event. " "Binlog %s @ %lu.", router->binlog_name, router->current_pos); } else { if (hdr.event_type == HEARTBEAT_EVENT) { #ifdef SHOW_EVENTS printf("Replication heartbeat\n"); #endif MXS_DEBUG("Replication heartbeat. " "Binlog %s @ %lu.", router->binlog_name, router->current_pos); router->stats.n_heartbeats++; if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { router->stats.lastReply = time(0); } } else if (hdr.flags != LOG_EVENT_ARTIFICIAL_F) { if (hdr.event_type == ROTATE_EVENT) { pthread_mutex_lock(&router->binlog_lock); router->rotating = 1; pthread_mutex_unlock(&router->binlog_lock); } uint32_t offset = MYSQL_HEADER_LEN + 1; if (blr_write_binlog_record(router, &hdr, len - offset, ptr + offset) == 0) { blr_master_close(router); blr_start_master_in_main(router); return false; } if (hdr.event_type == ROTATE_EVENT) { if (!blr_rotate_event(router, ptr + offset, &hdr)) { blr_master_close(router); blr_start_master_in_main(router); return false; } } if (router->master_semi_sync != MASTER_SEMISYNC_NOT_AVAILABLE && semisync == BLR_MASTER_SEMI_SYNC_ACK_REQ) { MXS_DEBUG("%s: binlog record in file %s, pos %lu has " "SEMI_SYNC_ACK_REQ and needs a Semi-Sync ACK packet to " "be sent to the master server [%s]:%d", router->service->name, router->binlog_name, router->current_pos, router->service->dbref->server->address, router->service->dbref->server->port); blr_send_semisync_ack(router, hdr.next_pos); semisync = 0; } pthread_mutex_lock(&router->binlog_lock); if (router->trx_safe == 0 || (router->trx_safe && router->pending_transaction.state == BLRM_NO_TRANSACTION)) { router->binlog_position = router->current_pos; router->current_safe_event = router->last_event_pos; pthread_mutex_unlock(&router->binlog_lock); blr_notify_all_slaves(router); } else { if (router->pending_transaction.state > BLRM_TRANSACTION_START) { if (router->mariadb10_compat) { router->pending_transaction.end_pos = router->current_pos; if (router->mariadb10_compat && router->mariadb10_gtid) { strcpy(router->last_mariadb_gtid, router->pending_transaction.gtid); blr_save_mariadb_gtid(router); } } pthread_mutex_unlock(&router->binlog_lock); blr_notify_all_slaves(router); pthread_mutex_lock(&router->binlog_lock); router->binlog_position = router->current_pos; router->pending_transaction.state = BLRM_NO_TRANSACTION; router->pending_transaction.standalone = false; pthread_mutex_unlock(&router->binlog_lock); } else { pthread_mutex_unlock(&router->binlog_lock); } } } else { router->stats.n_artificial++; MXS_DEBUG("Artificial event not written " "to disk or distributed. " "Type 0x%x, Length %d, Binlog " "%s @ %lu.", hdr.event_type, hdr.event_size, router->binlog_name, router->current_pos); ptr += MYSQL_HEADER_LEN + 1; if (hdr.event_type == ROTATE_EVENT) { if (!blr_handle_fake_rotate(router, &hdr, ptr)) { blr_master_close(router); blr_start_master_in_main(router); return false; } MXS_INFO("Fake ROTATE_EVENT received: " "binlog file %s, pos %" PRIu64 "", router->binlog_name, router->current_pos); } else if (hdr.event_type == MARIADB10_GTID_GTID_LIST_EVENT) { blr_handle_fake_gtid_list(router, &hdr, ptr); } } } return true; }
if (strncmp(statement_sql, "BEGIN", 5) == 0) { if (router->pending_transaction.state > BLRM_NO_TRANSACTION) { MXS_ERROR("A transaction is already open " "@ %lu and a new one starts @ %lu", router->binlog_position, router->current_pos); } router->pending_transaction.state = BLRM_TRANSACTION_START; router->pending_transaction.start_pos = router->current_pos; router->pending_transaction.end_pos = 0; }
if_condition
[ { "content": "#define GTID_MAX_LEN 64\n\n\n", "file_path": "include/maxscale/mysql_binlog.h", "rank": 0, "score": 229626.218827728 }, { "content": " struct mxs_router* router_instance; /**< The router instance for this\n", "file_path": "include/maxscale/service.h", "ra...
C++
game/src/main/cpp/game/Particles/Splash.cpp
zorin-egor/PingPongGame
fc4084f4e0efaa8d24605e7ae00b630c2ae984b7
#include "Splash.h" Splash::Splash(GLuint count, GLuint lifeTime, GLuint programID, GLuint textureID, GLuint positionAttr, GLuint colorStartAttr, GLuint colorEndAttr, GLuint deltaAttr, GLuint sizeUniform ) : m_nCount(count), m_nLifeTime(lifeTime), m_nProgramId(programID), m_nTextureId(textureID), m_nPositionAttr(positionAttr), m_nColorStartAttr(colorStartAttr), m_nColorEndAttr(colorEndAttr), m_nDeltaAttr(deltaAttr), m_nSizeUniform(sizeUniform), TOTAL_LIFE_TIME(lifeTime) { LOGI("Splash::Splash()"); m_pIsVisible = true; m_fPointSize = 5.0f; initArrays(); setSplashPosition(0.0f, 0.0f); } Splash::~Splash() { LOGI("Splash::~Splash()"); deleteObjects(); } void Splash::render() { if (!m_pIsVisible) { return; } if (m_nLifeTime < 0) { return; } setValues(); glUseProgram(m_nProgramId); checkGLError("Splash - glUseProgram"); glBindTexture(GL_TEXTURE_2D, m_nTextureId); checkGLError("Splash - glBindTexture"); glVertexAttribPointer(m_nPositionAttr, 2, GL_FLOAT, GL_FALSE, 0, m_pPositionArray); checkGLError("Splash - glVertexAttribPointer - m_nPositionAttr"); glEnableVertexAttribArray(m_nPositionAttr); checkGLError("Splash - glVertexAttribPointer - m_nPositionAttr - enabled"); glVertexAttribPointer(m_nColorStartAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorStartArray); checkGLError("Splash - glVertexAttribPointer - m_nColorStartAttr"); glEnableVertexAttribArray(m_nColorStartAttr); checkGLError("Splash - glVertexAttribPointer - m_nColorStartAttr - enabled"); glVertexAttribPointer(m_nColorEndAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorEndArray); checkGLError("Splash - glVertexAttribPointer - m_nColorEndAttr"); glEnableVertexAttribArray(m_nColorEndAttr); checkGLError("Splash - glVertexAttribPointer - m_nColorEndAttr - enabled"); glVertexAttribPointer(m_nDeltaAttr, 1, GL_FLOAT, GL_FALSE, 0, m_pDeltaArray); checkGLError("Splash - glVertexAttribPointer - m_nDeltaAttr"); glEnableVertexAttribArray(m_nDeltaAttr); checkGLError("Splash - glVertexAttribPointer - m_nDeltaAttr - enabled"); glUniform2f(m_nSizeUniform, m_pSizeArray[0], m_pSizeArray[1]); checkGLError("Splash - glUniform2f - m_nSizeUniform"); glDrawArrays(GL_POINTS, 0, m_nCount); checkGLError("Splash - glDrawArrays"); } void Splash::initArrays() { m_pPositionArray = new GLfloat[m_nCount * 2]; Methods::fillArray(m_pPositionArray, 0.0f, m_nCount * 2); m_pDeltaArray = new GLfloat[m_nCount]; m_pColorStartArray = new GLfloat[m_nCount * 4]; Methods::fillArray(m_pColorStartArray, 0.0f, m_nCount * 4); m_pColorEndArray = new GLfloat[m_nCount * 4]; Methods::fillArray(m_pColorEndArray, 0.0f, m_nCount * 4); m_pSizeArray = new GLfloat[2]; m_pSizeArray[0] = 2.0f; m_pSizeArray[1] = m_fPointSize; m_pDxArray = new GLfloat[m_nCount]; m_pDyArray = new GLfloat[m_nCount]; for (int i = 0; i < m_nCount; i++) { m_pDxArray[i] = Methods::getFullRandom() * 0.02; m_pDyArray[i] = Methods::getFullRandom() * 0.02; m_pDeltaArray[i] = Methods::getShortRandom() * 0.9; } } void Splash::setSplashPosition(GLfloat x, GLfloat y) { m_nLifeTime = TOTAL_LIFE_TIME; for (int i = 0; i < m_nCount; i++) { m_pPositionArray[i * 2] = x; m_pPositionArray[i * 2 + 1] = y; } } void Splash::setValues() { m_nLifeTime--; for (int i = 0; i < m_nCount; i++) { m_pPositionArray[i * 2] += m_pDxArray[i]; m_pPositionArray[i * 2 + 1] += m_pDyArray[i]; m_pColorStartArray[i * 4] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 1] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 2] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 3] = 0.1; m_pColorEndArray[i * 4] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 1] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 2] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 3] = (float) m_nLifeTime / (float) TOTAL_LIFE_TIME; } } void Splash::setParticlesCount(GLuint count) { m_nCount = count > 100 && count < 500 ? count : m_nCount; } void Splash::setParticlesSize(GLfloat size) { m_fPointSize = size > 2.0f && size < 20.0f ? size : m_fPointSize; } void Splash::deleteObjects() { delete [] m_pPositionArray; delete [] m_pColorStartArray; delete [] m_pColorEndArray; delete [] m_pDeltaArray; delete [] m_pSizeArray; delete [] m_pDxArray; delete [] m_pDyArray; } void Splash::setSettings() { deleteObjects(); initArrays(); } void Splash::resetTimer() { m_nLifeTime = 0; }
#include "Splash.h" Splash::Splash(GLuint count, GLuint lifeTime, GLuint programID, GLuint textureID, GLuint positionAttr, GLuint colorStartAttr, GLuint colorEndAttr, GLuint deltaAttr, GLuint sizeUniform ) : m_nCount(count), m_nLifeTime(lifeTime), m_nProgramId(programID), m_nTextureId(textureID), m_nPositionAttr(positionAttr), m_nColorStartAttr(colorStartAttr), m_nColorEndAttr(colorEndAttr), m_nDeltaAttr(deltaAttr), m_nSizeUniform(sizeUniform), TOTAL_LIFE_TIME(lifeTime) { LOGI("Splash::Splash()"); m_pIsVisible = true; m_fPointSize = 5.0f; initArrays(); setSplashPosition(0.0f, 0.0f); } Splash::~Splash() { LOGI("Splash::~Splash()"); deleteObjects(); } void Splash::render() { if (!m_pIsVisible) { return; } if (m_nLifeTime < 0) { return; } setValues(); glUseProgram(m_nProgramId); checkGLError("Splash - glUseProgram"); glBindTexture(GL_TEXTURE_2D, m_nTextureId); checkGLError("Splash - glBindTexture"); glVertexAttribPointer(m_nPositionAttr, 2, GL_FLOAT, GL_FALSE, 0, m_pPositionArray); checkGLError("Splash - glVertexAttribPointer - m_nPositionAttr"); glEnableVertexAttribArray(m_nPositionAttr); checkGLError("Splash - glVertexAttribPointer - m_nPositionAttr - enabled"); glVertexAttribPointer(m_nColorStartAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorStartArray); checkGLError("Splash - glVertexAttribPointer - m_nColorStartAttr"); glEnableVertexAttribArray(m_nColorStartAttr); checkGLError("Splash - glVertexAttribPointer - m_nColorStartAttr - enabled"); glVertexAttribPointer(m_nColorEndAttr, 4, GL_FLOAT, GL_FALSE, 0, m_pColorEndArray); checkGLError("Splash - glVertexAttribPointer - m_nColorEndAttr"); glEnableVertexAttribArray(m_nColorEndAttr); checkGLError("Splash - glVertexAttribPointer - m_nColorEndAttr - enabled"); glVertexAttribPointer(m_nDeltaAttr, 1, GL_FLOAT, GL_FALSE, 0, m_pDeltaArray); checkGLError("Splash - glVertexAttribPointer - m_nDeltaAttr"); glEnableVertexAttribArray(m_nDeltaAttr); checkGLError("Splash - glVertexAttribPointer - m_nDeltaAttr - enabled"); glUniform2f(m_nSizeUniform, m_pSizeArray[0], m_pSizeArray[1]); checkGLError("Splash - glUniform2f - m_nSizeUniform"); glDrawArrays(GL_POINTS, 0, m_nCount); checkGLError("Splash - glDrawArrays"); }
void Splash::setSplashPosition(GLfloat x, GLfloat y) { m_nLifeTime = TOTAL_LIFE_TIME; for (int i = 0; i < m_nCount; i++) { m_pPositionArray[i * 2] = x; m_pPositionArray[i * 2 + 1] = y; } } void Splash::setValues() { m_nLifeTime--; for (int i = 0; i < m_nCount; i++) { m_pPositionArray[i * 2] += m_pDxArray[i]; m_pPositionArray[i * 2 + 1] += m_pDyArray[i]; m_pColorStartArray[i * 4] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 1] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 2] = Methods::getShortRandom() * 0.5f; m_pColorStartArray[i * 4 + 3] = 0.1; m_pColorEndArray[i * 4] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 1] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 2] = Methods::getShortRandom() + 0.5f; m_pColorEndArray[i * 4 + 3] = (float) m_nLifeTime / (float) TOTAL_LIFE_TIME; } } void Splash::setParticlesCount(GLuint count) { m_nCount = count > 100 && count < 500 ? count : m_nCount; } void Splash::setParticlesSize(GLfloat size) { m_fPointSize = size > 2.0f && size < 20.0f ? size : m_fPointSize; } void Splash::deleteObjects() { delete [] m_pPositionArray; delete [] m_pColorStartArray; delete [] m_pColorEndArray; delete [] m_pDeltaArray; delete [] m_pSizeArray; delete [] m_pDxArray; delete [] m_pDyArray; } void Splash::setSettings() { deleteObjects(); initArrays(); } void Splash::resetTimer() { m_nLifeTime = 0; }
void Splash::initArrays() { m_pPositionArray = new GLfloat[m_nCount * 2]; Methods::fillArray(m_pPositionArray, 0.0f, m_nCount * 2); m_pDeltaArray = new GLfloat[m_nCount]; m_pColorStartArray = new GLfloat[m_nCount * 4]; Methods::fillArray(m_pColorStartArray, 0.0f, m_nCount * 4); m_pColorEndArray = new GLfloat[m_nCount * 4]; Methods::fillArray(m_pColorEndArray, 0.0f, m_nCount * 4); m_pSizeArray = new GLfloat[2]; m_pSizeArray[0] = 2.0f; m_pSizeArray[1] = m_fPointSize; m_pDxArray = new GLfloat[m_nCount]; m_pDyArray = new GLfloat[m_nCount]; for (int i = 0; i < m_nCount; i++) { m_pDxArray[i] = Methods::getFullRandom() * 0.02; m_pDyArray[i] = Methods::getFullRandom() * 0.02; m_pDeltaArray[i] = Methods::getShortRandom() * 0.9; } }
function_block-full_function
[ { "content": "def APP_CODE = 2\n", "file_path": "game/build.gradle", "rank": 0, "score": 19471.39118875441 }, { "content": " m_nColorResetTimer = COLOR_INITIAL_TIMER;\n\n m_bIsColorReset = true;\n\n}\n\n\n\nvoid Shape::setParticlesCount(GLuint count) {\n\n m_nCount = count > 5000 &&...
C++
media/gpu/chromeos/platform_video_frame_utils.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
#include "media/gpu/chromeos/platform_video_frame_utils.h" #include <drm_fourcc.h> #include <xf86drm.h> #include <limits> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/scoped_file.h" #include "base/no_destructor.h" #include "base/posix/eintr_wrapper.h" #include "base/strings/stringprintf.h" #include "base/synchronization/lock.h" #include "gpu/ipc/common/gpu_client_ids.h" #include "gpu/ipc/common/gpu_memory_buffer_support.h" #include "gpu/ipc/service/gpu_memory_buffer_factory.h" #include "media/base/color_plane_layout.h" #include "media/base/format_utils.h" #include "media/base/scopedfd_helper.h" #include "media/base/video_frame_layout.h" #include "media/base/video_util.h" #include "media/gpu/buffer_validation.h" #include "media/gpu/macros.h" #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gfx/linux/drm_util_linux.h" #include "ui/gfx/linux/gbm_buffer.h" #include "ui/gfx/linux/gbm_device.h" #include "ui/gfx/linux/gbm_util.h" #include "ui/gfx/linux/gbm_wrapper.h" #include "ui/gfx/linux/native_pixmap_dmabuf.h" #include "ui/gfx/native_pixmap.h" namespace media { namespace { class GbmDeviceWrapper { public: GbmDeviceWrapper(const GbmDeviceWrapper&) = delete; GbmDeviceWrapper& operator=(const GbmDeviceWrapper&) = delete; static GbmDeviceWrapper* Get() { static base::NoDestructor<GbmDeviceWrapper> gbm_device_wrapper; return gbm_device_wrapper.get(); } gfx::GpuMemoryBufferHandle CreateGpuMemoryBuffer( gfx::BufferFormat format, const gfx::Size& size, gfx::BufferUsage buffer_usage) { base::AutoLock lock(lock_); if (!gbm_device_) return gfx::GpuMemoryBufferHandle(); const int fourcc_format = ui::GetFourCCFormatFromBufferFormat(format); if (fourcc_format == DRM_FORMAT_INVALID) return gfx::GpuMemoryBufferHandle(); const uint32_t flags = ui::BufferUsageToGbmFlags(buffer_usage); std::unique_ptr<ui::GbmBuffer> buffer = gbm_device_->CreateBuffer(fourcc_format, size, flags); if (!buffer) return gfx::GpuMemoryBufferHandle(); gfx::NativePixmapHandle native_pixmap_handle = buffer->ExportHandle(); if (native_pixmap_handle.planes.empty()) return gfx::GpuMemoryBufferHandle(); CHECK_LT(next_gpu_memory_buffer_id_, std::numeric_limits<int>::max()); const gfx::GpuMemoryBufferId gpu_memory_buffer_id( next_gpu_memory_buffer_id_++); gfx::GpuMemoryBufferHandle gmb_handle; gmb_handle.type = gfx::GpuMemoryBufferType::NATIVE_PIXMAP; gmb_handle.id = gpu_memory_buffer_id; gmb_handle.native_pixmap_handle = std::move(native_pixmap_handle); return gmb_handle; } private: GbmDeviceWrapper() { constexpr char kRenderNodeFilePattern[] = "/dev/dri/renderD%d"; for (int i = 128;; i++) { base::FilePath dev_path(FILE_PATH_LITERAL( base::StringPrintf(kRenderNodeFilePattern, i).c_str())); render_node_file_ = base::File(dev_path, base::File::FLAG_OPEN | base::File::FLAG_READ); if (!render_node_file_.IsValid()) return; drmVersionPtr version = drmGetVersion(render_node_file_.GetPlatformFile()); if (!version) continue; std::string version_name( version->name, base::checked_cast<std::string::size_type>(version->name_len)); drmFreeVersion(version); if (base::LowerCaseEqualsASCII(version_name, "vgem")) continue; gbm_device_ = ui::CreateGbmDevice(render_node_file_.GetPlatformFile()); if (gbm_device_) return; } } ~GbmDeviceWrapper() = default; friend class base::NoDestructor<GbmDeviceWrapper>; base::Lock lock_; base::File render_node_file_ GUARDED_BY(lock_); std::unique_ptr<ui::GbmDevice> gbm_device_ GUARDED_BY(lock_); int next_gpu_memory_buffer_id_ GUARDED_BY(lock_) = 0; }; gfx::GpuMemoryBufferHandle AllocateGpuMemoryBufferHandle( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, gfx::BufferUsage buffer_usage, base::ScopedClosureRunner& destroy_cb) { DCHECK(factory || buffer_usage == gfx::BufferUsage::VEA_READ_CAMERA_AND_CPU_READ_WRITE); gfx::GpuMemoryBufferHandle gmb_handle; auto buffer_format = VideoPixelFormatToGfxBufferFormat(pixel_format); if (!buffer_format) return gmb_handle; if (!factory) { return GbmDeviceWrapper::Get()->CreateGpuMemoryBuffer( *buffer_format, coded_size, buffer_usage); } int gpu_memory_buffer_id; { static base::NoDestructor<base::Lock> id_lock; static int next_gpu_memory_buffer_id = 0; base::AutoLock lock(*id_lock); CHECK_LT(next_gpu_memory_buffer_id, std::numeric_limits<int>::max()); gpu_memory_buffer_id = next_gpu_memory_buffer_id++; } gmb_handle = factory->CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId(gpu_memory_buffer_id), coded_size, GetRectSizeFromOrigin(visible_rect), *buffer_format, buffer_usage, gpu::kPlatformVideoFramePoolClientId, gfx::kNullAcceleratedWidget); DCHECK(gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP || VideoFrame::NumPlanes(pixel_format) == gmb_handle.native_pixmap_handle.planes.size()); if (gmb_handle.is_null()) return gmb_handle; destroy_cb.ReplaceClosure( base::BindOnce(&gpu::GpuMemoryBufferFactory::DestroyGpuMemoryBuffer, base::Unretained(factory), gmb_handle.id, gpu::kPlatformVideoFramePoolClientId)); return gmb_handle; } } scoped_refptr<VideoFrame> CreateGpuMemoryBufferVideoFrame( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, base::TimeDelta timestamp, gfx::BufferUsage buffer_usage) { base::ScopedClosureRunner destroy_cb((base::DoNothing())); auto gmb_handle = AllocateGpuMemoryBufferHandle(factory, pixel_format, coded_size, visible_rect, buffer_usage, destroy_cb); if (gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP) return nullptr; auto buffer_format = VideoPixelFormatToGfxBufferFormat(pixel_format); DCHECK(buffer_format); gpu::GpuMemoryBufferSupport support; std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer = support.CreateGpuMemoryBufferImplFromHandle( std::move(gmb_handle), coded_size, *buffer_format, buffer_usage, base::NullCallback()); if (!gpu_memory_buffer) return nullptr; const gpu::MailboxHolder mailbox_holders[VideoFrame::kMaxPlanes] = {}; auto frame = VideoFrame::WrapExternalGpuMemoryBuffer( visible_rect, natural_size, std::move(gpu_memory_buffer), mailbox_holders, base::NullCallback(), timestamp); if (frame) frame->AddDestructionObserver(destroy_cb.Release()); return frame; } scoped_refptr<VideoFrame> CreatePlatformVideoFrame( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, base::TimeDelta timestamp, gfx::BufferUsage buffer_usage) { base::ScopedClosureRunner destroy_cb((base::DoNothing())); auto gmb_handle = AllocateGpuMemoryBufferHandle(factory, pixel_format, coded_size, visible_rect, buffer_usage, destroy_cb); if (gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP) return nullptr; std::vector<ColorPlaneLayout> planes; for (const auto& plane : gmb_handle.native_pixmap_handle.planes) planes.emplace_back(plane.stride, plane.offset, plane.size); auto layout = VideoFrameLayout::CreateWithPlanes( pixel_format, coded_size, std::move(planes), VideoFrameLayout::kBufferAddressAlignment, gmb_handle.native_pixmap_handle.modifier); if (!layout) return nullptr; std::vector<base::ScopedFD> dmabuf_fds; for (auto& plane : gmb_handle.native_pixmap_handle.planes) dmabuf_fds.emplace_back(plane.fd.release()); auto frame = VideoFrame::WrapExternalDmabufs( *layout, visible_rect, natural_size, std::move(dmabuf_fds), timestamp); if (!frame) return nullptr; frame->AddDestructionObserver(destroy_cb.Release()); return frame; } base::Optional<VideoFrameLayout> GetPlatformVideoFrameLayout( gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, gfx::BufferUsage buffer_usage) { auto frame = CreatePlatformVideoFrame( gpu_memory_buffer_factory, pixel_format, coded_size, gfx::Rect(coded_size), coded_size, base::TimeDelta(), buffer_usage); return frame ? base::make_optional<VideoFrameLayout>(frame->layout()) : base::nullopt; } gfx::GpuMemoryBufferHandle CreateGpuMemoryBufferHandle( const VideoFrame* video_frame) { DCHECK(video_frame); gfx::GpuMemoryBufferHandle handle; switch (video_frame->storage_type()) { case VideoFrame::STORAGE_GPU_MEMORY_BUFFER: handle = video_frame->GetGpuMemoryBuffer()->CloneHandle(); CHECK_EQ(handle.type, gfx::NATIVE_PIXMAP) << "The cloned handle has an unexpected type: " << handle.type; CHECK(!handle.native_pixmap_handle.planes.empty()) << "The cloned handle has no planes"; break; case VideoFrame::STORAGE_DMABUFS: { const size_t num_planes = VideoFrame::NumPlanes(video_frame->format()); std::vector<base::ScopedFD> duped_fds = DuplicateFDs(video_frame->DmabufFds()); while (num_planes != duped_fds.size()) { int duped_fd = -1; duped_fd = HANDLE_EINTR(dup(duped_fds.back().get())); PCHECK(duped_fd >= 0) << "Failed duplicating a dma-buf fd"; duped_fds.emplace_back(duped_fd); } handle.type = gfx::NATIVE_PIXMAP; DCHECK_EQ(video_frame->layout().planes().size(), num_planes); handle.native_pixmap_handle.modifier = video_frame->layout().modifier(); for (size_t i = 0; i < num_planes; ++i) { const auto& plane = video_frame->layout().planes()[i]; handle.native_pixmap_handle.planes.emplace_back( plane.stride, plane.offset, plane.size, std::move(duped_fds[i])); } } break; default: NOTREACHED() << "Unsupported storage type: " << video_frame->storage_type(); } if (!handle.is_null() && handle.type == gfx::NATIVE_PIXMAP && !VerifyGpuMemoryBufferHandle(video_frame->format(), video_frame->coded_size(), handle)) { VLOGF(1) << "Created GpuMemoryBufferHandle is invalid"; } return handle; } scoped_refptr<gfx::NativePixmapDmaBuf> CreateNativePixmapDmaBuf( const VideoFrame* video_frame) { DCHECK(video_frame); gfx::GpuMemoryBufferHandle gpu_memory_buffer_handle = CreateGpuMemoryBufferHandle(video_frame); if (gpu_memory_buffer_handle.is_null() || gpu_memory_buffer_handle.type != gfx::NATIVE_PIXMAP) { VLOGF(1) << "Failed to create native GpuMemoryBufferHandle"; return nullptr; } auto buffer_format = VideoPixelFormatToGfxBufferFormat(video_frame->layout().format()); if (!buffer_format) { VLOGF(1) << "Unexpected video frame format"; return nullptr; } auto native_pixmap = base::MakeRefCounted<gfx::NativePixmapDmaBuf>( video_frame->coded_size(), *buffer_format, std::move(gpu_memory_buffer_handle.native_pixmap_handle)); DCHECK(native_pixmap->AreDmaBufFdsValid()); return native_pixmap; } }
#include "media/gpu/chromeos/platform_video_frame_utils.h" #include <drm_fourcc.h> #include <xf86drm.h> #include <limits> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/scoped_file.h" #include "base/no_destructor.h" #include "base/posix/eintr_wrapper.h" #include "base/strings/stringprintf.h" #include "base/synchronization/lock.h" #include "gpu/ipc/common/gpu_client_ids.h" #include "gpu/ipc/common/gpu_memory_buffer_support.h" #include "gpu/ipc/service/gpu_memory_buffer_factory.h" #include "media/base/color_plane_layout.h" #include "media/base/format_utils.h" #include "media/base/scopedfd_helper.h" #include "media/base/video_frame_layout.h" #include "media/base/video_util.h" #include "media/gpu/buffer_validation.h" #include "media/gpu/macros.h" #include "ui/gfx/gpu_memory_buffer.h" #include "ui/gfx/linux/drm_util_linux.h" #include "ui/gfx/linux/gbm_buffer.h" #include "ui/gfx/linux/gbm_device.h" #include "ui/gfx/linux/gbm_util.h" #include "ui/gfx/linux/gbm_wrapper.h" #include "ui/gfx/linux/native_pixmap_dmabuf.h" #include "ui/gfx/native_pixmap.h" namespace media { namespace { class GbmDeviceWrapper { public: GbmDeviceWrapper(const GbmDeviceWrapper&) = delete; GbmDevice
fx::Size& natural_size, base::TimeDelta timestamp, gfx::BufferUsage buffer_usage) { base::ScopedClosureRunner destroy_cb((base::DoNothing())); auto gmb_handle = AllocateGpuMemoryBufferHandle(factory, pixel_format, coded_size, visible_rect, buffer_usage, destroy_cb); if (gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP) return nullptr; auto buffer_format = VideoPixelFormatToGfxBufferFormat(pixel_format); DCHECK(buffer_format); gpu::GpuMemoryBufferSupport support; std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer = support.CreateGpuMemoryBufferImplFromHandle( std::move(gmb_handle), coded_size, *buffer_format, buffer_usage, base::NullCallback()); if (!gpu_memory_buffer) return nullptr; const gpu::MailboxHolder mailbox_holders[VideoFrame::kMaxPlanes] = {}; auto frame = VideoFrame::WrapExternalGpuMemoryBuffer( visible_rect, natural_size, std::move(gpu_memory_buffer), mailbox_holders, base::NullCallback(), timestamp); if (frame) frame->AddDestructionObserver(destroy_cb.Release()); return frame; } scoped_refptr<VideoFrame> CreatePlatformVideoFrame( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const gfx::Size& natural_size, base::TimeDelta timestamp, gfx::BufferUsage buffer_usage) { base::ScopedClosureRunner destroy_cb((base::DoNothing())); auto gmb_handle = AllocateGpuMemoryBufferHandle(factory, pixel_format, coded_size, visible_rect, buffer_usage, destroy_cb); if (gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP) return nullptr; std::vector<ColorPlaneLayout> planes; for (const auto& plane : gmb_handle.native_pixmap_handle.planes) planes.emplace_back(plane.stride, plane.offset, plane.size); auto layout = VideoFrameLayout::CreateWithPlanes( pixel_format, coded_size, std::move(planes), VideoFrameLayout::kBufferAddressAlignment, gmb_handle.native_pixmap_handle.modifier); if (!layout) return nullptr; std::vector<base::ScopedFD> dmabuf_fds; for (auto& plane : gmb_handle.native_pixmap_handle.planes) dmabuf_fds.emplace_back(plane.fd.release()); auto frame = VideoFrame::WrapExternalDmabufs( *layout, visible_rect, natural_size, std::move(dmabuf_fds), timestamp); if (!frame) return nullptr; frame->AddDestructionObserver(destroy_cb.Release()); return frame; } base::Optional<VideoFrameLayout> GetPlatformVideoFrameLayout( gpu::GpuMemoryBufferFactory* gpu_memory_buffer_factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, gfx::BufferUsage buffer_usage) { auto frame = CreatePlatformVideoFrame( gpu_memory_buffer_factory, pixel_format, coded_size, gfx::Rect(coded_size), coded_size, base::TimeDelta(), buffer_usage); return frame ? base::make_optional<VideoFrameLayout>(frame->layout()) : base::nullopt; } gfx::GpuMemoryBufferHandle CreateGpuMemoryBufferHandle( const VideoFrame* video_frame) { DCHECK(video_frame); gfx::GpuMemoryBufferHandle handle; switch (video_frame->storage_type()) { case VideoFrame::STORAGE_GPU_MEMORY_BUFFER: handle = video_frame->GetGpuMemoryBuffer()->CloneHandle(); CHECK_EQ(handle.type, gfx::NATIVE_PIXMAP) << "The cloned handle has an unexpected type: " << handle.type; CHECK(!handle.native_pixmap_handle.planes.empty()) << "The cloned handle has no planes"; break; case VideoFrame::STORAGE_DMABUFS: { const size_t num_planes = VideoFrame::NumPlanes(video_frame->format()); std::vector<base::ScopedFD> duped_fds = DuplicateFDs(video_frame->DmabufFds()); while (num_planes != duped_fds.size()) { int duped_fd = -1; duped_fd = HANDLE_EINTR(dup(duped_fds.back().get())); PCHECK(duped_fd >= 0) << "Failed duplicating a dma-buf fd"; duped_fds.emplace_back(duped_fd); } handle.type = gfx::NATIVE_PIXMAP; DCHECK_EQ(video_frame->layout().planes().size(), num_planes); handle.native_pixmap_handle.modifier = video_frame->layout().modifier(); for (size_t i = 0; i < num_planes; ++i) { const auto& plane = video_frame->layout().planes()[i]; handle.native_pixmap_handle.planes.emplace_back( plane.stride, plane.offset, plane.size, std::move(duped_fds[i])); } } break; default: NOTREACHED() << "Unsupported storage type: " << video_frame->storage_type(); } if (!handle.is_null() && handle.type == gfx::NATIVE_PIXMAP && !VerifyGpuMemoryBufferHandle(video_frame->format(), video_frame->coded_size(), handle)) { VLOGF(1) << "Created GpuMemoryBufferHandle is invalid"; } return handle; } scoped_refptr<gfx::NativePixmapDmaBuf> CreateNativePixmapDmaBuf( const VideoFrame* video_frame) { DCHECK(video_frame); gfx::GpuMemoryBufferHandle gpu_memory_buffer_handle = CreateGpuMemoryBufferHandle(video_frame); if (gpu_memory_buffer_handle.is_null() || gpu_memory_buffer_handle.type != gfx::NATIVE_PIXMAP) { VLOGF(1) << "Failed to create native GpuMemoryBufferHandle"; return nullptr; } auto buffer_format = VideoPixelFormatToGfxBufferFormat(video_frame->layout().format()); if (!buffer_format) { VLOGF(1) << "Unexpected video frame format"; return nullptr; } auto native_pixmap = base::MakeRefCounted<gfx::NativePixmapDmaBuf>( video_frame->coded_size(), *buffer_format, std::move(gpu_memory_buffer_handle.native_pixmap_handle)); DCHECK(native_pixmap->AreDmaBufFdsValid()); return native_pixmap; } }
Wrapper& operator=(const GbmDeviceWrapper&) = delete; static GbmDeviceWrapper* Get() { static base::NoDestructor<GbmDeviceWrapper> gbm_device_wrapper; return gbm_device_wrapper.get(); } gfx::GpuMemoryBufferHandle CreateGpuMemoryBuffer( gfx::BufferFormat format, const gfx::Size& size, gfx::BufferUsage buffer_usage) { base::AutoLock lock(lock_); if (!gbm_device_) return gfx::GpuMemoryBufferHandle(); const int fourcc_format = ui::GetFourCCFormatFromBufferFormat(format); if (fourcc_format == DRM_FORMAT_INVALID) return gfx::GpuMemoryBufferHandle(); const uint32_t flags = ui::BufferUsageToGbmFlags(buffer_usage); std::unique_ptr<ui::GbmBuffer> buffer = gbm_device_->CreateBuffer(fourcc_format, size, flags); if (!buffer) return gfx::GpuMemoryBufferHandle(); gfx::NativePixmapHandle native_pixmap_handle = buffer->ExportHandle(); if (native_pixmap_handle.planes.empty()) return gfx::GpuMemoryBufferHandle(); CHECK_LT(next_gpu_memory_buffer_id_, std::numeric_limits<int>::max()); const gfx::GpuMemoryBufferId gpu_memory_buffer_id( next_gpu_memory_buffer_id_++); gfx::GpuMemoryBufferHandle gmb_handle; gmb_handle.type = gfx::GpuMemoryBufferType::NATIVE_PIXMAP; gmb_handle.id = gpu_memory_buffer_id; gmb_handle.native_pixmap_handle = std::move(native_pixmap_handle); return gmb_handle; } private: GbmDeviceWrapper() { constexpr char kRenderNodeFilePattern[] = "/dev/dri/renderD%d"; for (int i = 128;; i++) { base::FilePath dev_path(FILE_PATH_LITERAL( base::StringPrintf(kRenderNodeFilePattern, i).c_str())); render_node_file_ = base::File(dev_path, base::File::FLAG_OPEN | base::File::FLAG_READ); if (!render_node_file_.IsValid()) return; drmVersionPtr version = drmGetVersion(render_node_file_.GetPlatformFile()); if (!version) continue; std::string version_name( version->name, base::checked_cast<std::string::size_type>(version->name_len)); drmFreeVersion(version); if (base::LowerCaseEqualsASCII(version_name, "vgem")) continue; gbm_device_ = ui::CreateGbmDevice(render_node_file_.GetPlatformFile()); if (gbm_device_) return; } } ~GbmDeviceWrapper() = default; friend class base::NoDestructor<GbmDeviceWrapper>; base::Lock lock_; base::File render_node_file_ GUARDED_BY(lock_); std::unique_ptr<ui::GbmDevice> gbm_device_ GUARDED_BY(lock_); int next_gpu_memory_buffer_id_ GUARDED_BY(lock_) = 0; }; gfx::GpuMemoryBufferHandle AllocateGpuMemoryBufferHandle( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, gfx::BufferUsage buffer_usage, base::ScopedClosureRunner& destroy_cb) { DCHECK(factory || buffer_usage == gfx::BufferUsage::VEA_READ_CAMERA_AND_CPU_READ_WRITE); gfx::GpuMemoryBufferHandle gmb_handle; auto buffer_format = VideoPixelFormatToGfxBufferFormat(pixel_format); if (!buffer_format) return gmb_handle; if (!factory) { return GbmDeviceWrapper::Get()->CreateGpuMemoryBuffer( *buffer_format, coded_size, buffer_usage); } int gpu_memory_buffer_id; { static base::NoDestructor<base::Lock> id_lock; static int next_gpu_memory_buffer_id = 0; base::AutoLock lock(*id_lock); CHECK_LT(next_gpu_memory_buffer_id, std::numeric_limits<int>::max()); gpu_memory_buffer_id = next_gpu_memory_buffer_id++; } gmb_handle = factory->CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId(gpu_memory_buffer_id), coded_size, GetRectSizeFromOrigin(visible_rect), *buffer_format, buffer_usage, gpu::kPlatformVideoFramePoolClientId, gfx::kNullAcceleratedWidget); DCHECK(gmb_handle.is_null() || gmb_handle.type != gfx::NATIVE_PIXMAP || VideoFrame::NumPlanes(pixel_format) == gmb_handle.native_pixmap_handle.planes.size()); if (gmb_handle.is_null()) return gmb_handle; destroy_cb.ReplaceClosure( base::BindOnce(&gpu::GpuMemoryBufferFactory::DestroyGpuMemoryBuffer, base::Unretained(factory), gmb_handle.id, gpu::kPlatformVideoFramePoolClientId)); return gmb_handle; } } scoped_refptr<VideoFrame> CreateGpuMemoryBufferVideoFrame( gpu::GpuMemoryBufferFactory* factory, VideoPixelFormat pixel_format, const gfx::Size& coded_size, const gfx::Rect& visible_rect, const g
random
[]
C++
projects/client/gui/bloom/source/bloom/Garden.cpp
silentorb/mythic-cpp
97319d158800d77e1a944c47c13523662bc07e08
#include "Garden.h" #include "clienting/Mythic_Client.h" #include "haft/Input_State.h" #include "lookinglass/Lookinglass_Resources.h" #include <iostream> #include <bloom/layout/Axis.h> #include <bloom/flowers/Group.h> #include "framing/Frame_Info.h" #include "bloom/flowers/Flower.h" #include <bloom/flowers/Root.h> using namespace haft; namespace bloom { Garden *Garden::instance = nullptr; Garden::Garden(Draw_Interface &draw) : draw(draw), select_action(new Action(1, "Select")), converter(draw.get_frame().get_dimensions()) { Measurement::pixel_scale = draw.get_frame().get_pixel_scale(); root = unique_ptr<flowers::Root>(new flowers::Root()); instance = this; } Garden::~Garden() {} flowers::Parent &Garden::get_root() const { return *root; } flowers::Flower &Garden::get_event_root() const { return modal_stack.size() > 0 ? *modal_stack.top()->root : *root; } void Garden::update_input(haft::Input_State &input_state) { auto input_result = garden_input.update_input(input_state); { flowers::Flower &start = get_event_root(); if (input_result.mouse_click) { auto &position = input_state.get_position(); if (start.check_event({Events::activate, vec2(position.x, position.y)})) { input_state.clear_gestures(); } } } { flowers::Flower &start = get_event_root(); if (input_result.dragging) { auto &position = garden_input.get_drag_start(); start.check_event({Events::drag, vec2(position.x, position.y)}); } else if (input_result.down) { start.check_event({Events::mouse_down, garden_input.get_position()}); } else if (input_result.up) { start.check_event({Events::mouse_down, garden_input.get_position()}); } } } void Garden::update_layout() { auto dimensions = draw.get_frame().get_dimensions(); converter.set_pixel_dimensions(dimensions); Axis_Values_Old base_axis_values{ converter.get_axis_values<Horizontal_Axis>(), converter.get_axis_values<Vertical_Axis>() }; auto pixel_dimensions = converter.convert_to_pixels({base_axis_values.x.length, base_axis_values.y.length}); root->update_dimensions(pixel_dimensions); root->update_position(ivec2(), pixel_dimensions); } void Garden::render() { update_layout(); root->render(); } void Garden::add_modal(flowers::Flower &flower) { modal_stack.push(unique_ptr<Modal>(new Modal(&flower))); } flowers::Flower *Garden::get_modal() const { if (modal_stack.size() == 0) return nullptr; return modal_stack.top().get()->root; } void Garden::pop_modal() { modal_stack.pop(); } const framing::Frame_Info &Garden::get_frame() const { return draw.get_frame(); } void Garden::update(float delta) { root->update(delta); } }
#include "Garden.h" #include "clienting/Mythic_Client.h" #include "haft/Input_State.h" #include "lookinglass/Lookinglass_Resources.h" #include <iostream> #include <bloom/layout/Axis.h> #include <bloom/flowers/Group.h> #include "framing/Frame_Info.h" #include "bloom/flowers/Flower.h" #include <bloom/flowers/Root.h> using namespace haft; namespace bloom { Garden *Garden::instance = nullptr; Garden::Garden(Draw_Interface &draw) : draw(draw), select_action(new Action(1, "Select")), converter(draw.get_frame().get_dimensions()) { Measurement::pixel_scale = draw.get_frame().get_pixel_scale(); root = unique_ptr<flowers::Root>(new flowers::Root()); instance = this; } Garden::~Garden() {} flowers::Parent &Garden::get_root() const { return *root; } flowers::Flower &Garden::get_event_root() const { return modal_stack.size() > 0 ? *modal_stack.top()->root : *root; }
void Garden::update_layout() { auto dimensions = draw.get_frame().get_dimensions(); converter.set_pixel_dimensions(dimensions); Axis_Values_Old base_axis_values{ converter.get_axis_values<Horizontal_Axis>(), converter.get_axis_values<Vertical_Axis>() }; auto pixel_dimensions = converter.convert_to_pixels({base_axis_values.x.length, base_axis_values.y.length}); root->update_dimensions(pixel_dimensions); root->update_position(ivec2(), pixel_dimensions); } void Garden::render() { update_layout(); root->render(); } void Garden::add_modal(flowers::Flower &flower) { modal_stack.push(unique_ptr<Modal>(new Modal(&flower))); } flowers::Flower *Garden::get_modal() const { if (modal_stack.size() == 0) return nullptr; return modal_stack.top().get()->root; } void Garden::pop_modal() { modal_stack.pop(); } const framing::Frame_Info &Garden::get_frame() const { return draw.get_frame(); } void Garden::update(float delta) { root->update(delta); } }
void Garden::update_input(haft::Input_State &input_state) { auto input_result = garden_input.update_input(input_state); { flowers::Flower &start = get_event_root(); if (input_result.mouse_click) { auto &position = input_state.get_position(); if (start.check_event({Events::activate, vec2(position.x, position.y)})) { input_state.clear_gestures(); } } } { flowers::Flower &start = get_event_root(); if (input_result.dragging) { auto &position = garden_input.get_drag_start(); start.check_event({Events::drag, vec2(position.x, position.y)}); } else if (input_result.down) { start.check_event({Events::mouse_down, garden_input.get_position()}); } else if (input_result.up) { start.check_event({Events::mouse_down, garden_input.get_position()}); } } }
function_block-full_function
[ { "content": " class Root;\n\n }\n\n\n", "file_path": "projects/client/gui/bloom/source/bloom/Garden.h", "rank": 0, "score": 198418.698124333 }, { "content": " class Garden {\n\n// shared_ptr<Style> default_style;\n\n unique_ptr<flowers::Root> root;\n\n unique_ptr<haft::A...
C++
ProjectLunarFront/LogSystem.hpp
Edgaru089/ProjectLunarFront
bf59c6dec36e0576082acf3c72abf3c82bc92241
#pragma once #include <iostream> #include <string> #include <ctime> #include <cstring> #include <cstdio> #include <functional> #include <vector> #include <mutex> #include "StringParser.hpp" using namespace std; #define AUTOLOCK(a) lock_guard<mutex> __mutex_lock(a) #ifndef DISABLE_ALL_LOGS class Log { public: const wstring logLevelName[6] = { L"DEBUG", L"INFO", L"EVENT", L"WARN", L"ERROR", L"FATAL ERROR" }; enum LogLevel { Debug, Info, Event, Warning, Error, FatalError }; Log() :ignoreLevel(-1) {} Log(wostream& output) :out({ &output }), ignoreLevel(-1) {} Log(wostream* output) :out({ output }), ignoreLevel(-1) {} void log(const wstring& content, LogLevel level = Info) { if (level <= ignoreLevel) return; time_t curtime = time(NULL); wchar_t buffer[64] = {}; wcsftime(buffer, 63, L"[%T", localtime(&curtime)); wstring final = wstring(buffer) + L" " + logLevelName[level] + L"] " + content + L'\n'; lock.lock(); buffers.push_back(final); for (wostream* i : out) { (*i) << final; i->flush(); if (!(*i)) i->clear(); } for (const auto& i : outf) i(final); lock.unlock(); } template<typename... Args> void logf(LogLevel level, wstring format, Args... args) { wchar_t buf[2560]; wsprintf(buf, format.c_str(), args...); log(wstring(buf), level); } void operator() (const wstring& content, LogLevel level = Info) { log(content, level); } void addOutputStream(wostream& output) { lock.lock(); out.push_back(&output); lock.unlock(); } void addOutputStream(wostream* output) { lock.lock(); out.push_back(output); lock.unlock(); } void addOutputHandler(function<void(const wstring&)> output) { lock.lock(); outf.push_back(output); lock.unlock(); } void ignore(int level) { ignoreLevel = level; } int getIgnoreLevel() { return ignoreLevel; } const vector<wstring>& getBuffers() { return buffers; } void clearBuffer() { AUTOLOCK(lock); buffers.clear(); } private: vector<wostream*> out; vector<function<void(const wstring&)>> outf; mutex lock; int ignoreLevel; vector<wstring> buffers; }; extern Log dlog; class LogMessage { public: LogMessage() :level(Log::Info) {} LogMessage(Log::LogLevel level) :level(level) {} LogMessage& operator <<(bool data) { buffer += data ? L"true" : L"false"; return *this; } LogMessage& operator <<(char data) { buffer += (data); return *this; } LogMessage& operator <<(unsigned char data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(short data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned short data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(int data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned int data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned long long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(float data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(double data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long double data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(const wchar_t* data) { buffer += wstring(data); return *this; } LogMessage& operator <<(const char* data) { buffer += utf8ToWstring(data); return *this; } LogMessage& operator <<(const wstring& data) { buffer += data; return *this; } LogMessage& operator <<(const string& data) { buffer += utf8ToWstring(data); return *this; } LogMessage& operator <<(Log::LogLevel level) { this->level = level; return *this; } LogMessage& operator <<(Log& log) { flush(log); return *this; } public: void setLevel(Log::LogLevel level) { this->level = level; } void flush(Log& log) { logout(log); clear(); } void logout(Log& log) { log(buffer, level); } void clear() { buffer.clear(); } private: wstring buffer; Log::LogLevel level; }; #define mlog LogMessage() #define mloge LogMessage(Log::Event) #define mlogd LogMessage(Log::Debug) #else class Log { public: enum LogLevel { Debug, Info, Event, Warning, Error, FatalError }; Log() {} Log(wostream& output) {} Log(wostream* output) {} void log(const wstring&, LogLevel) {} template<typename... Args> void logf(LogLevel, wstring, Args...) {} void operator() (const wstring&, LogLevel level) {} void addOutputStream(wostream&) {} void addOutputStream(wostream*) {} void addOutputHandler(function<void(const wstring&)>) {} void ignore(int) {} int getIgnoreLevel() { return -1; } const vector<wstring>& getBuffers() {} void clearBuffer() {} }; class LogMessage { public: LogMessage() {} LogMessage(Log::LogLevel level) {} LogMessage& operator <<(bool) { return *this; } LogMessage& operator <<(char) { return *this; } LogMessage& operator <<(unsigned char) { return *this; } LogMessage& operator <<(short) { return *this; } LogMessage& operator <<(unsigned short) { return *this; } LogMessage& operator <<(int) { return *this; } LogMessage& operator <<(unsigned int) { return *this; } LogMessage& operator <<(long long) { return *this; } LogMessage& operator <<(unsigned long long) { return *this; } LogMessage& operator <<(float) { return *this; } LogMessage& operator <<(double) { return *this; } LogMessage& operator <<(const wchar_t*) { return *this; } LogMessage& operator <<(const char*) { return *this; } LogMessage& operator <<(const wstring&) { return *this; } LogMessage& operator <<(const string&) { return *this; } LogMessage& operator <<(Log::LogLevel) { return *this; } LogMessage& operator <<(Log&) { return *this; } public: void setLevel(Log::LogLevel) {} void flush(Log&) {} void logout(Log&) {} void clear() {} }; #ifdef USE_WCOUT_AS_LOG #define mlog (wcout << L"[INFO] ") #define mloge (wcout << L"[EVENT] ") #define mlogd (wcout << L"DEBUG ") #define dlog endl inline wostream& operator << (wostream& out, const string& str) { out << utf8ToWstring(str); return out; } #else extern Log dlog; #define mlog LogMessage() #define mloge LogMessage(Log::Event) #define mlogd LogMessage(Log::Debug) #endif #endif
#pragma once #include <iostream> #include <string> #include <ctime> #include <cstring> #include <cstdio> #include <functional> #include <vector> #include <mutex> #include "StringParser.hpp" using namespace std; #define AUTOLOCK(a) lock_guard<mutex> __mutex_lock(a) #ifndef DISABLE_ALL_LOGS class Log { public: const wstring logLevelName[6] = { L"DEBUG", L"INFO", L"EVENT", L"WARN", L"ERROR", L"FATAL ERROR" }; enum LogLevel { Debug, Info, Event, Warning, Error, FatalError }; Log() :ignoreLevel(-1) {} Log(wostream& output) :out({ &output }), ignoreLevel(-1) {} Log(wostream* output) :out({ output }), ignoreLevel(-1) {}
template<typename... Args> void logf(LogLevel level, wstring format, Args... args) { wchar_t buf[2560]; wsprintf(buf, format.c_str(), args...); log(wstring(buf), level); } void operator() (const wstring& content, LogLevel level = Info) { log(content, level); } void addOutputStream(wostream& output) { lock.lock(); out.push_back(&output); lock.unlock(); } void addOutputStream(wostream* output) { lock.lock(); out.push_back(output); lock.unlock(); } void addOutputHandler(function<void(const wstring&)> output) { lock.lock(); outf.push_back(output); lock.unlock(); } void ignore(int level) { ignoreLevel = level; } int getIgnoreLevel() { return ignoreLevel; } const vector<wstring>& getBuffers() { return buffers; } void clearBuffer() { AUTOLOCK(lock); buffers.clear(); } private: vector<wostream*> out; vector<function<void(const wstring&)>> outf; mutex lock; int ignoreLevel; vector<wstring> buffers; }; extern Log dlog; class LogMessage { public: LogMessage() :level(Log::Info) {} LogMessage(Log::LogLevel level) :level(level) {} LogMessage& operator <<(bool data) { buffer += data ? L"true" : L"false"; return *this; } LogMessage& operator <<(char data) { buffer += (data); return *this; } LogMessage& operator <<(unsigned char data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(short data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned short data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(int data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned int data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(unsigned long long data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(float data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(double data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(long double data) { buffer += to_wstring(data); return *this; } LogMessage& operator <<(const wchar_t* data) { buffer += wstring(data); return *this; } LogMessage& operator <<(const char* data) { buffer += utf8ToWstring(data); return *this; } LogMessage& operator <<(const wstring& data) { buffer += data; return *this; } LogMessage& operator <<(const string& data) { buffer += utf8ToWstring(data); return *this; } LogMessage& operator <<(Log::LogLevel level) { this->level = level; return *this; } LogMessage& operator <<(Log& log) { flush(log); return *this; } public: void setLevel(Log::LogLevel level) { this->level = level; } void flush(Log& log) { logout(log); clear(); } void logout(Log& log) { log(buffer, level); } void clear() { buffer.clear(); } private: wstring buffer; Log::LogLevel level; }; #define mlog LogMessage() #define mloge LogMessage(Log::Event) #define mlogd LogMessage(Log::Debug) #else class Log { public: enum LogLevel { Debug, Info, Event, Warning, Error, FatalError }; Log() {} Log(wostream& output) {} Log(wostream* output) {} void log(const wstring&, LogLevel) {} template<typename... Args> void logf(LogLevel, wstring, Args...) {} void operator() (const wstring&, LogLevel level) {} void addOutputStream(wostream&) {} void addOutputStream(wostream*) {} void addOutputHandler(function<void(const wstring&)>) {} void ignore(int) {} int getIgnoreLevel() { return -1; } const vector<wstring>& getBuffers() {} void clearBuffer() {} }; class LogMessage { public: LogMessage() {} LogMessage(Log::LogLevel level) {} LogMessage& operator <<(bool) { return *this; } LogMessage& operator <<(char) { return *this; } LogMessage& operator <<(unsigned char) { return *this; } LogMessage& operator <<(short) { return *this; } LogMessage& operator <<(unsigned short) { return *this; } LogMessage& operator <<(int) { return *this; } LogMessage& operator <<(unsigned int) { return *this; } LogMessage& operator <<(long long) { return *this; } LogMessage& operator <<(unsigned long long) { return *this; } LogMessage& operator <<(float) { return *this; } LogMessage& operator <<(double) { return *this; } LogMessage& operator <<(const wchar_t*) { return *this; } LogMessage& operator <<(const char*) { return *this; } LogMessage& operator <<(const wstring&) { return *this; } LogMessage& operator <<(const string&) { return *this; } LogMessage& operator <<(Log::LogLevel) { return *this; } LogMessage& operator <<(Log&) { return *this; } public: void setLevel(Log::LogLevel) {} void flush(Log&) {} void logout(Log&) {} void clear() {} }; #ifdef USE_WCOUT_AS_LOG #define mlog (wcout << L"[INFO] ") #define mloge (wcout << L"[EVENT] ") #define mlogd (wcout << L"DEBUG ") #define dlog endl inline wostream& operator << (wostream& out, const string& str) { out << utf8ToWstring(str); return out; } #else extern Log dlog; #define mlog LogMessage() #define mloge LogMessage(Log::Event) #define mlogd LogMessage(Log::Debug) #endif #endif
void log(const wstring& content, LogLevel level = Info) { if (level <= ignoreLevel) return; time_t curtime = time(NULL); wchar_t buffer[64] = {}; wcsftime(buffer, 63, L"[%T", localtime(&curtime)); wstring final = wstring(buffer) + L" " + logLevelName[level] + L"] " + content + L'\n'; lock.lock(); buffers.push_back(final); for (wostream* i : out) { (*i) << final; i->flush(); if (!(*i)) i->clear(); } for (const auto& i : outf) i(final); lock.unlock(); }
function_block-full_function
[ { "content": "class StringDatabase :public Lockable {\n\npublic:\n\n\n\n\tbool initializeWithFolder(const fs::path& dbFolder);\n\n\n\n\tUuid insert(const string& contents);\n\n\tbool remove(Uuid id);\n\n\n\n\tconst StringDBObject& get(Uuid id) {\n\n\t\tlock_guard<Lockable>(*this);\n\n\t\tauto i = objs.find(id);...
C++
src/HistTool.cpp
xzf89718/bbtautau-hists
3f20c9d9cf82149df12aef155c6dd148a367aece
#include "HistTool.h" #include <exception> #include <algorithm> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <set> #include <map> #include <iomanip> using namespace std; # define FOUR_COLUMN_TABLE(A, B, C, D) \ std::left << setw(36) << A \ << std::left << setw(15) << B \ << std::left << setw(30) << C \ << std::left << setw(15) << D << endl # define FIVE_COLUMN_TABLE(A, B, C, D, E) \ std::left << setw(40) << A \ << std::left << setw(15) << B \ << std::left << setw(15) << C \ << std::left << setw(15) << D \ << std::left << setw(15) << E << endl bool HistTool::check(const Config* c) const { vector<ProcessInfo*>* ps = c->processes->content(); clog << "INFO: removing nullptrs\n"; ps->erase(remove_if(ps->begin(), ps->end(), [](const ProcessInfo* p) { return !p->histogram; }), ps->end()); if (ps->size() < 1) { cerr << "FAIL: empty input\n"; return false; } return true; } void HistTool::manipulate(Config* c) { c->setManipulated(true); vector<ProcessInfo*>* ps_in_c = c->processes->content(); clog << "INFO: merging\n"; map<eProcess, vector<ProcessInfo*>> procs; for_each(ps_in_c->begin(), ps_in_c->end(), [&procs](ProcessInfo* p) { procs[p->process].push_back(p); }); for_each(procs.begin(), procs.end(), [&ps_in_c, &c](pair<const eProcess, vector<ProcessInfo*>>& pair) { ProcessInfo* front = pair.second.front(); ProcessInfo* merged = new ProcessInfo( front->process_name, front->process_name, front->type, front->process, front->process_name, front->color); merged->histogram = (TH1*)front->histogram->Clone(); for_each(pair.second.begin() + 1, pair.second.end(), [&merged](const ProcessInfo* p) { merged->histogram->Add(p->histogram); }); if (!(front->systematic_histograms.empty())) { for (auto & pp : front->systematic_histograms) { std::cout << pp.first << std::endl; merged->systematic_histograms[pp.first] = (TH1*)front->systematic_histograms[pp.first]->Clone(); for_each(pair.second.begin() + 1, pair.second.end(), [&merged, &pp](const ProcessInfo* p) { std::cout << p->name << std::endl; if (!p->systematic_histograms.empty()) { if (p->systematic_histograms.find(pp.first) != p->systematic_histograms.end()) merged->systematic_histograms[pp.first]->Add(p->systematic_histograms.at(pp.first)); else merged->systematic_histograms[pp.first]->Add(p->histogram); } }); } } merged->isMerged = true; merged->norm_factor = front->norm_factor; merged->current_region = front->current_region; merged->current_variable = front->current_variable; c->current_region = merged->current_region; c->current_variable = merged->current_variable; ps_in_c->emplace_back(merged); }); ps_in_c->erase(remove_if(ps_in_c->begin(), ps_in_c->end(), [](const ProcessInfo* p) { return !p->isMerged; }), ps_in_c->end()); sort(ps_in_c->begin(), ps_in_c->end(), [](const ProcessInfo* p1, const ProcessInfo* p2) { return p1->type < p2->type; }); } void HistTool::rebin(const Config* c, eRebinOption opt, const std::string& info, bool transform) const { Tools::println("INFO: from HistTool::rebin(): %", info); switch (opt) { case eRebinOption::Self: rebin(c); break; case eRebinOption::N_Rebin: HistToolHelper::rebinByNRebin(c); break; case eRebinOption::Array: HistToolHelper::rebinByArray(c, transform); break; default: break; } } void HistTool::makeYield(const Config* c, const std::string& tag) const { ostringstream oss; oss << output_path << "/" << c->current_region->name << "_" << tag << "_" << c->current_variable->name << ".txt"; ofstream fout(oss.str()); vector<ProcessInfo*>* ps = c->processes->content(); bool hasBkg = false; int entriesBkg = 0; double sumBkg = 0.0; double errBkg = 0.0; fout << FIVE_COLUMN_TABLE("Process", "Entries", "Yield", "Error", "Rel.Err."); for (ProcessInfo* p : *ps) { double error; int from = 0; int to = p->histogram->GetNbinsX() + 1; int nentries = p->histogram->GetEntries(); double integral = p->histogram->IntegralAndError(from, to, error, ""); double eOverI = integral > (double)0. ? error / integral : 0.; fout << FIVE_COLUMN_TABLE(p->name, nentries, integral * p->norm_factor, error * p->norm_factor, eOverI); for (auto& pp : p->systematic_histograms) { auto systEntries = pp.second->GetEntries(); auto systInt = pp.second->Integral(); fout << " |- " << FOUR_COLUMN_TABLE(pp.first, systEntries, systInt, systInt / integral - 1.f); } if (p->type == eProcessType::BKG) { hasBkg = true; entriesBkg += nentries; sumBkg += integral * p->norm_factor; errBkg += error * error * p->norm_factor * p->norm_factor; } } if (hasBkg) { errBkg = sqrt(errBkg); fout << FIVE_COLUMN_TABLE("Total Bkg", entriesBkg, sumBkg, errBkg, errBkg / sumBkg); } clog << "INFO: Yields saved in " << oss.str() << '\n'; } bool HistToolHelper::check(const Config* c) { vector<ProcessInfo*>* ps = c->processes->content(); clog << "INFO: removing nullptrs\n"; ps->erase(remove_if(ps->begin(), ps->end(), [](const ProcessInfo* p) { return !p->histogram; }), ps->end()); if (ps->size() < 1) { cerr << "FAIL: empty input\n"; return false; } return true; } void HistToolHelper::rebinByNRebin(const Config* c) { vector<ProcessInfo*>* ps = c->processes->content(); for_each(ps->begin(), ps->end(), [&c](ProcessInfo* p) { p->histogram->Rebin(c->current_variable->n_rebin); for (auto& pp : p->systematic_histograms) { pp.second->Rebin(c->current_variable->n_rebin); } }); } void HistToolHelper::rebinByArray(const Config* c, bool transform) { vector<ProcessInfo*>* ps = c->processes->content(); if (c->current_variable->binning) { for_each(ps->begin(), ps->end(), [&c, &transform](ProcessInfo* p) { std::string name = p->histogram->GetName(); TH1* rebinned = p->histogram->Rebin(c->current_variable->n_bins, (name + "rebinned").c_str(), c->current_variable->binning); TH1* transformed = new TH1D((name + "transformed").c_str(), (name + "transformed").c_str(), rebinned->GetNbinsX(), 0., 1.); Utils::properties_copy(transformed, rebinned); for (int i = 1; i <= rebinned->GetNbinsX(); ++i) { transformed->SetBinContent(i, rebinned->GetBinContent(i)); transformed->SetBinError(i, rebinned->GetBinError(i)); } if (transform) { p->histogram = (TH1*)transformed->Clone(); } else { p->histogram = (TH1*)rebinned->Clone(); } for (auto& pp : p->systematic_histograms) { name = pp.second->GetName(); TH1* rebinned_pp = pp.second->Rebin(c->current_variable->n_bins, (name + "rebinned").c_str(), c->current_variable->binning); TH1* transformed_pp = new TH1D((name + "transformed").c_str(), (name + "transformed").c_str(), rebinned->GetNbinsX(), 0., 1.); Utils::properties_copy(transformed_pp, rebinned_pp); pp.second = (TH1*)rebinned_pp->Clone(); for (int i = 1; i <= rebinned_pp->GetNbinsX(); ++i) { transformed_pp->SetBinContent(i, rebinned_pp->GetBinContent(i)); transformed_pp->SetBinError(i, rebinned_pp->GetBinError(i)); } if (transform) { pp.second = (TH1*)transformed_pp->Clone(); } else { pp.second = (TH1*)rebinned_pp->Clone(); } delete rebinned_pp; delete transformed_pp; } delete rebinned; delete transformed; }); } else { clog << "WARN: Binning not given, will rebin based on rebinByNRebin(c) instead\n"; HistToolHelper::rebinByNRebin(c); } }
#include "HistTool.h" #include <exception> #include <algorithm> #include <vector> #include <iostream> #include <fstream> #include <sstream> #include <set> #include <map> #include <iomanip> using namespace std; # define FOUR_COLUMN_TABLE(A, B, C, D) \ std::left << setw(36) << A \ << std::left << setw(15) << B \ << std::left << setw(30) << C \ << std::left << setw(15) << D << endl # define FIVE_COLUMN_TABLE(A, B, C, D, E) \ std::left << setw(40) << A \ << std::left << setw(15) << B \ << std::left << setw(15) << C \ << std::left << setw(15) << D \ << std::left << setw(15) << E << endl bool HistTool::check(const Config* c) const { vector<ProcessInfo*>* ps = c->processes->content(); clog << "INFO: removing nullptrs\n"; ps->erase(remove_if(ps->begin(), ps->end(), [](const ProcessInfo* p) { return !p->histogram; }), ps->end()); if (ps->size()
oid HistToolHelper::rebinByNRebin(const Config* c) { vector<ProcessInfo*>* ps = c->processes->content(); for_each(ps->begin(), ps->end(), [&c](ProcessInfo* p) { p->histogram->Rebin(c->current_variable->n_rebin); for (auto& pp : p->systematic_histograms) { pp.second->Rebin(c->current_variable->n_rebin); } }); } void HistToolHelper::rebinByArray(const Config* c, bool transform) { vector<ProcessInfo*>* ps = c->processes->content(); if (c->current_variable->binning) { for_each(ps->begin(), ps->end(), [&c, &transform](ProcessInfo* p) { std::string name = p->histogram->GetName(); TH1* rebinned = p->histogram->Rebin(c->current_variable->n_bins, (name + "rebinned").c_str(), c->current_variable->binning); TH1* transformed = new TH1D((name + "transformed").c_str(), (name + "transformed").c_str(), rebinned->GetNbinsX(), 0., 1.); Utils::properties_copy(transformed, rebinned); for (int i = 1; i <= rebinned->GetNbinsX(); ++i) { transformed->SetBinContent(i, rebinned->GetBinContent(i)); transformed->SetBinError(i, rebinned->GetBinError(i)); } if (transform) { p->histogram = (TH1*)transformed->Clone(); } else { p->histogram = (TH1*)rebinned->Clone(); } for (auto& pp : p->systematic_histograms) { name = pp.second->GetName(); TH1* rebinned_pp = pp.second->Rebin(c->current_variable->n_bins, (name + "rebinned").c_str(), c->current_variable->binning); TH1* transformed_pp = new TH1D((name + "transformed").c_str(), (name + "transformed").c_str(), rebinned->GetNbinsX(), 0., 1.); Utils::properties_copy(transformed_pp, rebinned_pp); pp.second = (TH1*)rebinned_pp->Clone(); for (int i = 1; i <= rebinned_pp->GetNbinsX(); ++i) { transformed_pp->SetBinContent(i, rebinned_pp->GetBinContent(i)); transformed_pp->SetBinError(i, rebinned_pp->GetBinError(i)); } if (transform) { pp.second = (TH1*)transformed_pp->Clone(); } else { pp.second = (TH1*)rebinned_pp->Clone(); } delete rebinned_pp; delete transformed_pp; } delete rebinned; delete transformed; }); } else { clog << "WARN: Binning not given, will rebin based on rebinByNRebin(c) instead\n"; HistToolHelper::rebinByNRebin(c); } }
< 1) { cerr << "FAIL: empty input\n"; return false; } return true; } void HistTool::manipulate(Config* c) { c->setManipulated(true); vector<ProcessInfo*>* ps_in_c = c->processes->content(); clog << "INFO: merging\n"; map<eProcess, vector<ProcessInfo*>> procs; for_each(ps_in_c->begin(), ps_in_c->end(), [&procs](ProcessInfo* p) { procs[p->process].push_back(p); }); for_each(procs.begin(), procs.end(), [&ps_in_c, &c](pair<const eProcess, vector<ProcessInfo*>>& pair) { ProcessInfo* front = pair.second.front(); ProcessInfo* merged = new ProcessInfo( front->process_name, front->process_name, front->type, front->process, front->process_name, front->color); merged->histogram = (TH1*)front->histogram->Clone(); for_each(pair.second.begin() + 1, pair.second.end(), [&merged](const ProcessInfo* p) { merged->histogram->Add(p->histogram); }); if (!(front->systematic_histograms.empty())) { for (auto & pp : front->systematic_histograms) { std::cout << pp.first << std::endl; merged->systematic_histograms[pp.first] = (TH1*)front->systematic_histograms[pp.first]->Clone(); for_each(pair.second.begin() + 1, pair.second.end(), [&merged, &pp](const ProcessInfo* p) { std::cout << p->name << std::endl; if (!p->systematic_histograms.empty()) { if (p->systematic_histograms.find(pp.first) != p->systematic_histograms.end()) merged->systematic_histograms[pp.first]->Add(p->systematic_histograms.at(pp.first)); else merged->systematic_histograms[pp.first]->Add(p->histogram); } }); } } merged->isMerged = true; merged->norm_factor = front->norm_factor; merged->current_region = front->current_region; merged->current_variable = front->current_variable; c->current_region = merged->current_region; c->current_variable = merged->current_variable; ps_in_c->emplace_back(merged); }); ps_in_c->erase(remove_if(ps_in_c->begin(), ps_in_c->end(), [](const ProcessInfo* p) { return !p->isMerged; }), ps_in_c->end()); sort(ps_in_c->begin(), ps_in_c->end(), [](const ProcessInfo* p1, const ProcessInfo* p2) { return p1->type < p2->type; }); } void HistTool::rebin(const Config* c, eRebinOption opt, const std::string& info, bool transform) const { Tools::println("INFO: from HistTool::rebin(): %", info); switch (opt) { case eRebinOption::Self: rebin(c); break; case eRebinOption::N_Rebin: HistToolHelper::rebinByNRebin(c); break; case eRebinOption::Array: HistToolHelper::rebinByArray(c, transform); break; default: break; } } void HistTool::makeYield(const Config* c, const std::string& tag) const { ostringstream oss; oss << output_path << "/" << c->current_region->name << "_" << tag << "_" << c->current_variable->name << ".txt"; ofstream fout(oss.str()); vector<ProcessInfo*>* ps = c->processes->content(); bool hasBkg = false; int entriesBkg = 0; double sumBkg = 0.0; double errBkg = 0.0; fout << FIVE_COLUMN_TABLE("Process", "Entries", "Yield", "Error", "Rel.Err."); for (ProcessInfo* p : *ps) { double error; int from = 0; int to = p->histogram->GetNbinsX() + 1; int nentries = p->histogram->GetEntries(); double integral = p->histogram->IntegralAndError(from, to, error, ""); double eOverI = integral > (double)0. ? error / integral : 0.; fout << FIVE_COLUMN_TABLE(p->name, nentries, integral * p->norm_factor, error * p->norm_factor, eOverI); for (auto& pp : p->systematic_histograms) { auto systEntries = pp.second->GetEntries(); auto systInt = pp.second->Integral(); fout << " |- " << FOUR_COLUMN_TABLE(pp.first, systEntries, systInt, systInt / integral - 1.f); } if (p->type == eProcessType::BKG) { hasBkg = true; entriesBkg += nentries; sumBkg += integral * p->norm_factor; errBkg += error * error * p->norm_factor * p->norm_factor; } } if (hasBkg) { errBkg = sqrt(errBkg); fout << FIVE_COLUMN_TABLE("Total Bkg", entriesBkg, sumBkg, errBkg, errBkg / sumBkg); } clog << "INFO: Yields saved in " << oss.str() << '\n'; } bool HistToolHelper::check(const Config* c) { vector<ProcessInfo*>* ps = c->processes->content(); clog << "INFO: removing nullptrs\n"; ps->erase(remove_if(ps->begin(), ps->end(), [](const ProcessInfo* p) { return !p->histogram; }), ps->end()); if (ps->size() < 1) { cerr << "FAIL: empty input\n"; return false; } return true; } v
random
[ { "content": "class BasicInfo\n\n{\n\npublic:\n\n BasicInfo(const string& ecm, const string& lumi) noexcept;\n\n\n\npublic:\n\n string ecm;\n\n string luminosity;\n\n};\n\n\n\n\n", "file_path": "src/Config.h", "rank": 0, "score": 76141.76415751204 }, { "content": "class Config\n\n{\...
C++
src/GRCPrinter.cpp
dilawar/cec-esteral
c21ed6dea7392a3c4553d304eeeaaee188a6f567
#include "GRCPrinter.hpp" #include <cassert> namespace GRCDot { void GRCDP::visit_cfg(GRCNode *n) { assert(n); if (reached.find(n) == reached.end()) { reached.insert(n); assert(cfgnum.find(n) != cfgnum.end()); mynum = cfgnum[n]; o << 'n' << mynum << ' '; n->welcome(*this); for (vector<GRCNode *>::const_iterator k = n->dataPredecessors.begin() ; k != n->dataPredecessors.end() ; k++) { assert(cfgnum.find(*k) != cfgnum.end()); o << 'n' << cfgnum[*k] << " -> n" << cfgnum[n]; if (clean) o << " [color=red]\n"; else o << " [color=red constraint=false]\n"; } for ( vector<GRCNode*>::iterator j = n->successors.begin() ; j != n->successors.end() ; j++ ) { if (*j) { o << 'n' << cfgnum[n] << " -> n" << cfgnum[*j]; if ( n->successors.size() > 1) { if (clean) { if (dynamic_cast<Switch*>(n) != NULL || dynamic_cast<Sync*>(n) != NULL) o << " [label=\"" << j - n->successors.begin() << "\"]"; else if (dynamic_cast<Test*>(n) != NULL && j == n->successors.end() - 1) o << " [label=\"P\"]"; } else { o << " [label=\"" << j - n->successors.begin() << "\"]"; } } o << '\n'; } else if (!clean) { o << 'n'<< cfgnum[n] << " -> n" << nextnum << "[label=\"" << j-n->successors.begin() << "\"]" << '\n'; o << 'n' << nextnum++ << " [shape=octagon style=filled color=black]\n"; } } for ( vector<GRCNode*>::iterator j = n->successors.begin() ; j != n->successors.end() ; j++ ) if (*j) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->predecessors.begin() ; j != n->predecessors.end() ; j++ ) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->dataSuccessors.begin() ; j != n->dataSuccessors.end() ; j++ ) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->dataPredecessors.begin() ; j != n->dataPredecessors.end() ; j++ ) visit_cfg(*j); } } Status GRCDP::visit(Switch &s) { if (clean) { o << "[label=\"s" << stnum[s.st] << "\" shape=diamond peripheries=2]\n"; o << "{ rank=same n" << mynum << " n" << stnum[s.st] << " }\n"; } else { o << "[label=\"" << mynum << " switch "; o << stnum[s.st] << "\" shape=diamond color=pink style=filled]\n"; drawSTlink(&s,s.st); } return Status(); } Status GRCDP::visit(Test &s) { o << "[label=\""; if (!clean) o << mynum << " test "; s.predicate->welcome(ep); o << "\" shape=diamond]\n"; return Status(); } Status GRCDP::visit(STSuspend &s){ o << "[label=\""; if (!clean) o << mynum << " Suspend "; o << stnum[s.st] << "\" shape=egg]\n"; return Status(); } Status GRCDP::visit(Terminate &s) { if (clean) { o << "[label=\"" << s.code << "\" shape=octagon]\n"; } else { o << "[label=\"" << mynum << ' ' << s.index << '@' << s.code << "\" shape=octagon color=red style=filled " "fontcolor=white fontname=\"Times-Bold\"]\n"; } return Status(); } Status GRCDP::visit(Sync &s) { o << "[label=\""; if (!clean) o << mynum << " sync" << " " << stnum[s.st]; o << "\" shape=invtriangle]\n"; o << "{ rank=same; "; for ( vector<GRCNode*>::iterator i = s.predecessors.begin() ; i != s.predecessors.end() ; i++ ) o << 'n' << cfgnum[*i] << "; "; o << "}\n"; return Status(); } Status GRCDP::visit(Fork &s) { o << "[label=\""; if (!clean) o << mynum << " fork"; o << "\" shape=triangle]\n"; return Status(); } Status GRCDP::visit(Action &s) { o << "[label=\""; if (!clean) o << mynum << " action "; s.body->welcome(ep); o << '\"'; if (dynamic_cast<Emit*>(s.body)) o << " shape=house orientation=270]\n"; else o << " shape=box]\n"; return Status(); } Status GRCDP::visit(Enter &s) { if (clean) { STNode *n = s.st; STNode *parent = NULL; STexcl *exclusive = NULL; for (;;) { parent = n->parent; exclusive = dynamic_cast<STexcl*>(parent); if ( exclusive != NULL ) break; n = parent; } vector<STNode*>::iterator i = exclusive->children.begin(); while (*i != n && i != exclusive->children.end()) i++; int childnum = i - exclusive->children.begin(); o << "[label=\"s" << stnum[parent] << '=' << childnum << "\" shape=box]\n"; } else { o << "[label=\"" << mynum << " enter " << stnum[s.st] << "\" shape=house color=palegreen1 style=filled]\n"; } return Status(); } Status GRCDP::visit(EnterGRC &s){ o << "[label=\""; if (!clean) o << mynum << " EnterGRC"; o << "\"]\n"; return Status(); } Status GRCDP::visit(ExitGRC &s){ o << "[label=\""; if (!clean) o << mynum << " ExitGRC"; o << "\"]\n"; return Status(); } Status GRCDP::visit(Nop &s){ o << "[label=\""; if (!clean) o << mynum << " "; if (s.isflowin()) o << "*"; else if (s.isshortcut()) o << "#"; else o << "\\n" << s.code; o << "\" shape=circle]\n"; return Status(); } Status GRCDP::visit(DefineSignal &s){ o << "[label=\""; if (!clean) o << mynum << " DefS\\n"; o << s.signal->name << "\" shape=house orientation=90]\n"; return Status(); } void GRCDP::visit_st(STNode *n) { assert(n); mynum = stnum[n]; o << 'n' << mynum << ' '; n->welcome(*this); for ( vector<STNode*>::const_iterator i = n->children.begin() ; i != n->children.end() ; i++ ) if (*i) { visit_st(*i); o << 'n' << stnum[n] << " -> n" << stnum[*i]; if (!clean || dynamic_cast<STexcl*>(n) != NULL) o << " [label=\"" << (i - n->children.begin()) << "\"]"; o << '\n'; } else { o << 'n'<< stnum[n] << " -> n" << nextnum << "[label=\"" << i - n->children.begin() << "\"]"<<'\n'; o << 'n' << nextnum++; if (clean) o << " [shape=point]\n"; else o << " [shape=octagon style=filled color=black]\n"; } } Status GRCDP::visit(STexcl &s) { if (clean) { o << "[label=\"s" << mynum << "\" shape=diamond peripheries=2]\n"; } else { o << "[label=\"" << mynum << "\" shape=diamond color=pink style=filled]\n"; } return Status(); } Status GRCDP::visit(STref &s) { if (clean) { o << "[shape=box label=\"\"]\n"; } else { o << "[label=\"" << mynum << " "; if(s.isabort()) o << "A"; if(s.issuspend()) o << "S"; o << "\" ]\n"; } return Status(); } Status GRCDP::visit(STpar &s) { if (clean) { o << "[label=\"\" shape=triangle]\n"; } else { o << "[label=\"" << mynum << "\" shape=triangle]\n"; } return Status(); } Status GRCDP::visit(STleaf &s) { if (clean) { o << "[label=\""; if(s.isfinal()) o << "*"; o << "\" shape=box]\n"; } else { o << "[label=\"" << mynum << " "; if(s.isfinal()) o << "*"; o << "\" shape=box]\n"; } return Status(); } void drawDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean, CFGmap &cfgmap, STmap &stmap, int mxnode) { GRCDP visitor(o, cfgmap, stmap, mxnode+1); visitor.drawstlink = drawstlink; visitor.clean = clean; o << "digraph " << m->symbol->name << " {" << std::endl; o << "size=\"7.5,10\"\n"; visitor.visit_st(g->selection_tree); visitor.visit_cfg(g->control_flow_graph); o << "}" << std::endl; } int GRCDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean, CFGmap &cfgmap, STmap &stmap, int mxnode) { assert(g); assert(m); assert(m->symbol); mxnode = g->enumerate(cfgmap, stmap, mxnode); drawDot(o, g, m, drawstlink, clean, cfgmap, stmap, mxnode); return mxnode; } void GRCDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean) { assert(g); assert(m); assert(m->symbol); CFGmap cfgmap; STmap stmap; int mxnode = g->enumerate(cfgmap, stmap); drawDot(o, g, m, drawstlink, clean, cfgmap, stmap, mxnode); } void GRCDP::drawSTlink(GRCNode *g, STNode *s) { o << "{ rank=same; n" << cfgnum[g] << "; n" << stnum[s] << " }\n"; if (!drawstlink) return; assert( stnum.find(s) != stnum.end() ); o << 'n' << cfgnum[g] << " -> n" << stnum[s]; o << "[color=blue constraint=false]"; o << '\n'; } }
#include "GRCPrinter.hpp" #include <cassert> namespace GRCDot { void GRCDP::visit_cfg(GRCNode *n) { assert(n); if (reached.find(n) == reached.end()) { reached.insert(n); assert(cfgnum.find(n) != cfgnum.end()); mynum = cfgnum[n]; o << 'n' << mynum << ' '; n->welcome(*this); for (vector<GRCNode *>::const_iterator k = n->dataPredecessors.begin() ; k != n->dataPredecessors.end() ; k++) { assert(cfgnum.find(*k) != cfgnum.end()); o << 'n' << cfgnum[*k] << " -> n" << cfgnum[n]; if (clean) o << " [color=red]\n"; else o << " [color=red constraint=false]\n"; } for ( vector<GRCNode*>::iterator j = n->successors.begin() ; j != n->successors.end() ; j++ ) { if (*j) { o << 'n' << cfgnum[n] << " -> n" << cfgnum[*j]; if ( n->successors.size() > 1) { if (clean) { if (dynamic_cast<Switch*>(n) != NULL || dynamic_cast<Sync*>(n) != NULL) o << " [label=\"" << j - n->successors.begin() << "\"]"; else if (dynamic_cast<Test*>(n) != NULL && j == n->successors.end() - 1) o << " [label=\"P\"]"; } else { o << " [label=\"" << j - n->successors.begin() << "\"]"; } } o << '\n'; } else if (!clean) { o << 'n'<< cfgnum[n] << " -> n" << nextnum << "[label=\"" << j-n->successors.begin() << "\"]" << '\n'; o << 'n' << nextnum++ << " [shape=octagon style=filled color=black]\n"; } } for ( vector<GRCNode*>::iterator j = n->successors.begin() ; j != n->successors.end() ; j++ ) if (*j) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->predecessors.begin() ; j != n->predecessors.end() ; j++ ) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->dataSuccessors.begin() ; j != n->dataSuccessors.end() ; j++ ) visit_cfg(*j); for ( vector<GRCNode*>::iterator j = n->dataPredecessors.begin() ; j != n->dataPredecessors.end() ; j++ ) visit_cfg(*j); } } Status GRCDP::visit(Switch &s) { if (clean) { o << "[label=\"s" << stnum[s.st] << "\" shape=diamond peripheries=2]\n"; o << "{ rank=same n" << mynum << " n" << stnum[s.st] << " }\n"; } else { o << "[label=\"" << mynum << " switch "; o << stnum[s.st] << "\" shape=diamond color=pink style=filled]\n"; drawSTlink(&s,s.st); } return Status(); } Status GRCDP::visit(Test &s) { o << "[label=\""; if (!clean) o << mynum << " test "; s.predicate->welcome(ep); o << "\" shape=diamond]\n"; return Status(); } Status GRCDP::visit(STSuspend &s){ o << "[label=\""; if (!clean) o << mynum << " Suspend "; o << stnum[s.st] << "\" shape=egg]\n"; return Status(); } Status GRCDP::visit(Terminate &s) { if (clean) { o << "[label=\"" << s.code << "\" shape=octagon]\n"; } else { o << "[label=\"" << mynum << ' ' << s.index << '@' << s.code << "\" shape=octagon color=red style=filled " "fontcolor=white fontname=\"Times-Bold\"]\n"; } return Status(); } Status GRCDP::visit(Sync &s) { o << "[label=\""; if (!clean) o << mynum << " sync" << " " << stnum[s.st]; o << "\" shape=invtriangle]\n"; o << "{ rank=same; "; for ( vector<GRCNode*>::iterator i = s.predecessors.begin() ; i != s.predecessors.end() ; i++ ) o << 'n' << cfgnum[*i] << "; "; o << "}\n"; return Status(); } Status GRCDP::visit(Fork &s) { o << "[label=\""; if (!clean) o << mynum << " fork"; o << "\" shape=triangle]\n"; return Status(); } Status GRCDP::visit(Action &s) { o << "[label=\""; if (!clean) o << mynum << " action "; s.body->welcome(ep); o << '\"'; if (dynamic_cast<Emit*>(s.body)) o << " shape=house orientation=270]\n"; else o << " shape=box]\n"; return Status(); } Status GRCDP::visit(Enter &s) { if (clean) { STNode *n = s.st; STNode *parent = NULL; STexcl *exclusive = NULL; for (;;) { parent = n->parent; exclusive = dynamic_cast<STexcl*>(parent); if ( exclusive != NULL ) break; n = parent; } vector<STNode*>::iterator i = exclusive->children.begin(); while (*i != n && i != exclusive->children.end()) i++; int childnum = i - exclusive->children.begin(); o << "[label=\"s" << stnum[parent] << '=' << childnum << "\" shape=box]\n"; } else { o << "[label=\"" << mynum << " enter " << stnum[s.st] << "\" shape=house color=palegreen1 style=filled]\n"; } return Status(); } Status GRCDP::visit(EnterGRC &s){ o << "[label=\""; if (!clean) o << mynum << " EnterGRC"; o << "\"]\n"; return Status(); } Status GRCDP::visit(ExitGRC &s){ o << "[label=\""; if (!clean) o << mynum << " ExitGRC"; o << "\"]\n"; return Status(); }
Status GRCDP::visit(DefineSignal &s){ o << "[label=\""; if (!clean) o << mynum << " DefS\\n"; o << s.signal->name << "\" shape=house orientation=90]\n"; return Status(); } void GRCDP::visit_st(STNode *n) { assert(n); mynum = stnum[n]; o << 'n' << mynum << ' '; n->welcome(*this); for ( vector<STNode*>::const_iterator i = n->children.begin() ; i != n->children.end() ; i++ ) if (*i) { visit_st(*i); o << 'n' << stnum[n] << " -> n" << stnum[*i]; if (!clean || dynamic_cast<STexcl*>(n) != NULL) o << " [label=\"" << (i - n->children.begin()) << "\"]"; o << '\n'; } else { o << 'n'<< stnum[n] << " -> n" << nextnum << "[label=\"" << i - n->children.begin() << "\"]"<<'\n'; o << 'n' << nextnum++; if (clean) o << " [shape=point]\n"; else o << " [shape=octagon style=filled color=black]\n"; } } Status GRCDP::visit(STexcl &s) { if (clean) { o << "[label=\"s" << mynum << "\" shape=diamond peripheries=2]\n"; } else { o << "[label=\"" << mynum << "\" shape=diamond color=pink style=filled]\n"; } return Status(); } Status GRCDP::visit(STref &s) { if (clean) { o << "[shape=box label=\"\"]\n"; } else { o << "[label=\"" << mynum << " "; if(s.isabort()) o << "A"; if(s.issuspend()) o << "S"; o << "\" ]\n"; } return Status(); } Status GRCDP::visit(STpar &s) { if (clean) { o << "[label=\"\" shape=triangle]\n"; } else { o << "[label=\"" << mynum << "\" shape=triangle]\n"; } return Status(); } Status GRCDP::visit(STleaf &s) { if (clean) { o << "[label=\""; if(s.isfinal()) o << "*"; o << "\" shape=box]\n"; } else { o << "[label=\"" << mynum << " "; if(s.isfinal()) o << "*"; o << "\" shape=box]\n"; } return Status(); } void drawDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean, CFGmap &cfgmap, STmap &stmap, int mxnode) { GRCDP visitor(o, cfgmap, stmap, mxnode+1); visitor.drawstlink = drawstlink; visitor.clean = clean; o << "digraph " << m->symbol->name << " {" << std::endl; o << "size=\"7.5,10\"\n"; visitor.visit_st(g->selection_tree); visitor.visit_cfg(g->control_flow_graph); o << "}" << std::endl; } int GRCDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean, CFGmap &cfgmap, STmap &stmap, int mxnode) { assert(g); assert(m); assert(m->symbol); mxnode = g->enumerate(cfgmap, stmap, mxnode); drawDot(o, g, m, drawstlink, clean, cfgmap, stmap, mxnode); return mxnode; } void GRCDot(std::ostream &o, GRCgraph *g, Module *m, bool drawstlink, bool clean) { assert(g); assert(m); assert(m->symbol); CFGmap cfgmap; STmap stmap; int mxnode = g->enumerate(cfgmap, stmap); drawDot(o, g, m, drawstlink, clean, cfgmap, stmap, mxnode); } void GRCDP::drawSTlink(GRCNode *g, STNode *s) { o << "{ rank=same; n" << cfgnum[g] << "; n" << stnum[s] << " }\n"; if (!drawstlink) return; assert( stnum.find(s) != stnum.end() ); o << 'n' << cfgnum[g] << " -> n" << stnum[s]; o << "[color=blue constraint=false]"; o << '\n'; } }
Status GRCDP::visit(Nop &s){ o << "[label=\""; if (!clean) o << mynum << " "; if (s.isflowin()) o << "*"; else if (s.isshortcut()) o << "#"; else o << "\\n" << s.code; o << "\" shape=circle]\n"; return Status(); }
function_block-function_prefix_line
[ { "content": " class Sync;\n", "file_path": "src/AST.hpp", "rank": 0, "score": 85744.66952829852 }, { "content": " class Fork;\n", "file_path": "src/AST.hpp", "rank": 1, "score": 85739.77028225773 }, { "content": " class Action;\n", "file_path": "src/AST.hpp", ...
C++
src/nlr/LPFormulator.cpp
yuvaljacoby/Marabou-1
553b780ef2e2cfe349b3954adc433a27af37a50f
#include "GurobiWrapper.h" #include "InfeasibleQueryException.h" #include "LPFormulator.h" #include "Layer.h" #include "MStringf.h" #include "NLRError.h" #include "TimeUtils.h" namespace NLR { LPFormulator::LPFormulator( LayerOwner *layerOwner ) : _layerOwner( layerOwner ) , _cutoffInUse( false ) , _cutoffValue( 0 ) { } LPFormulator::~LPFormulator() { } double LPFormulator::solveLPRelaxation( const Map<unsigned, Layer *> &layers, MinOrMax minOrMax, String variableName, unsigned lastLayer ) { GurobiWrapper gurobi; createLPRelaxation( layers, gurobi, lastLayer ); List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, variableName ) ); if ( minOrMax == MAX ) gurobi.setObjective( terms ); else gurobi.setCost( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); Map<String, double> dontCare; double result = 0; gurobi.extractSolution( dontCare, result ); return result; } void LPFormulator::optimizeBoundsWithIncrementalLpRelaxation( const Map<unsigned, Layer *> &layers ) { GurobiWrapper gurobi; List<GurobiWrapper::Term> terms; Map<String, double> dontCare; double lb = 0; double ub = 0; double currentLb = 0; double currentUb = 0; unsigned tighterBoundCounter = 0; unsigned signChanges = 0; unsigned cutoffs = 0; struct timespec gurobiStart; (void) gurobiStart; struct timespec gurobiEnd; (void) gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); for ( unsigned i = 0; i < _layerOwner->getNumberOfLayers(); ++i ) { ASSERT( layers.exists( i ) ); Layer *layer = layers[i]; addLayerToModel( gurobi, layer ); for ( unsigned j = 0; j < layer->getSize(); ++j ) { if ( layer->neuronEliminated( j ) ) continue; currentLb = layer->getLb( j ); currentUb = layer->getUb( j ); if ( _cutoffInUse && ( currentLb > _cutoffValue || currentUb < _cutoffValue ) ) continue; unsigned variable = layer->neuronToVariable( j ); Stringf variableName( "x%u", variable ); terms.clear(); terms.append( GurobiWrapper::Term( 1, variableName ) ); gurobi.reset(); gurobi.setObjective( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); gurobi.extractSolution( dontCare, ub ); if ( ub < currentUb ) { gurobi.setUpperBound( variableName, ub ); if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; layer->setUb( j, ub ); _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) { ++cutoffs; continue; } } gurobi.reset(); gurobi.setCost( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); gurobi.extractSolution( dontCare, lb ); if ( lb > currentLb ) { gurobi.setLowerBound( variableName, lb ); if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; layer->setLb( j, lb ); _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb > _cutoffValue ) { ++cutoffs; continue; } } } } gurobiEnd = TimeUtils::sampleMicro(); LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", tighterBoundCounter, signChanges, cutoffs ).ascii() ); LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); } void LPFormulator::optimizeBoundsWithLpRelaxation( const Map<unsigned, Layer *> &layers ) { double lb = FloatUtils::negativeInfinity(); double ub = FloatUtils::infinity(); double currentLb; double currentUb; unsigned tighterBoundCounter = 0; unsigned signChanges = 0; unsigned cutoffs = 0; struct timespec gurobiStart; (void) gurobiStart; struct timespec gurobiEnd; (void) gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); for ( const auto &currentLayer : layers ) { Layer *layer = currentLayer.second; for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( layer->neuronEliminated( i ) ) continue; currentLb = layer->getLb( i ); currentUb = layer->getUb( i ); if ( _cutoffInUse && ( currentLb > _cutoffValue || currentUb < _cutoffValue ) ) continue; unsigned variable = layer->neuronToVariable( i ); Stringf variableName( "x%u", variable ); ub = solveLPRelaxation( layers, MinOrMax::MAX, variableName, layer->getLayerIndex() ); if ( ub < currentUb ) { if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; layer->setUb( i, ub ); _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) { ++cutoffs; continue; } } lb = solveLPRelaxation( layers, MinOrMax::MIN, variableName, layer->getLayerIndex() ); if ( lb > currentLb ) { if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; layer->setLb( i, lb ); _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb > _cutoffValue ) { ++cutoffs; continue; } } } } gurobiEnd = TimeUtils::sampleMicro(); LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", tighterBoundCounter, signChanges, cutoffs ).ascii() ); LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); } void LPFormulator::createLPRelaxation( const Map<unsigned, Layer *> &layers, GurobiWrapper &gurobi, unsigned lastLayer ) { for ( const auto &layer : layers ) { if ( layer.second->getLayerIndex() > lastLayer ) continue; addLayerToModel( gurobi, layer.second ); } } void LPFormulator::addLayerToModel( GurobiWrapper &gurobi, const Layer *layer ) { switch ( layer->getLayerType() ) { case Layer::INPUT: addInputLayerToLpRelaxation( gurobi, layer ); break; case Layer::RELU: addReluLayerToLpRelaxation( gurobi, layer ); break; case Layer::WEIGHTED_SUM: addWeightedSumLayerToLpRelaxation( gurobi, layer ); break; default: throw NLRError( NLRError::LAYER_TYPE_NOT_SUPPORTED, "MILPFormulator" ); break; } } void LPFormulator::addInputLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { unsigned varibale = layer->neuronToVariable( i ); gurobi.addVariable( Stringf( "x%u", varibale ), layer->getLb( i ), layer->getUb( i ) ); } } void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( !layer->neuronEliminated( i ) ) { unsigned targetVariable = layer->neuronToVariable( i ); List<NeuronIndex> sources = layer->getActivationSources( i ); const Layer *sourceLayer = _layerOwner->getLayer( sources.begin()->_layer ); unsigned sourceNeuron = sources.begin()->_neuron; unsigned sourceVariable = sourceLayer->neuronToVariable( sourceNeuron ); double sourceLb = sourceLayer->getLb( sourceNeuron ); double sourceUb = sourceLayer->getUb( sourceNeuron ); gurobi.addVariable( Stringf( "x%u", targetVariable ), 0, layer->getUb( i ) ); if ( !FloatUtils::isNegative( sourceLb ) ) { if ( sourceLb < 0 ) sourceLb = 0; List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", sourceVariable ) ) ); gurobi.addEqConstraint( terms, 0 ); } else if ( !FloatUtils::isPositive( sourceUb ) ) { List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); gurobi.addEqConstraint( terms, 0 ); } else { List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); gurobi.addGeqConstraint( terms, 0 ); terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", sourceVariable ) ) ); gurobi.addGeqConstraint( terms, 0 ); terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -sourceUb / ( sourceUb - sourceLb ), Stringf( "x%u", sourceVariable ) ) ); gurobi.addLeqConstraint( terms, ( -sourceUb * sourceLb ) / ( sourceUb - sourceLb ) ); } } } } void LPFormulator::addWeightedSumLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( !layer->neuronEliminated( i ) ) { unsigned varibale = layer->neuronToVariable( i ); gurobi.addVariable( Stringf( "x%u", varibale ), layer->getLb( i ), layer->getUb( i ) ); List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", varibale ) ) ); double bias = -layer->getBias( i ); for ( const auto &sourceLayerPair : layer->getSourceLayers() ) { const Layer *sourceLayer = _layerOwner->getLayer( sourceLayerPair.first ); unsigned sourceLayerSize = sourceLayerPair.second; for ( unsigned j = 0; j < sourceLayerSize; ++j ) { double weight = layer->getWeight( sourceLayerPair.first, j, i ); if ( !sourceLayer->neuronEliminated( j ) ) { Stringf sourceVariableName( "x%u", sourceLayer->neuronToVariable( j ) ); terms.append( GurobiWrapper::Term( weight, sourceVariableName ) ); } else { bias += weight * sourceLayer->getEliminatedNeuronValue( j ); } } } gurobi.addEqConstraint( terms, bias ); } } } void LPFormulator::setCutoff( double cutoff ) { _cutoffInUse = true; _cutoffValue = cutoff; } }
#include "GurobiWrapper.h" #include "InfeasibleQueryException.h" #include "LPFormulator.h" #include "Layer.h" #include "MStringf.h" #include "NLRError.h" #include "TimeUtils.h" namespace NLR { LPFormulator::LPFormulator( LayerOwner *layerOwner ) : _layerOwner( layerOwner ) , _cutoffInUse( false ) , _cutoffValue( 0 ) { } LPFormulator::~LPFormulator() { } double LPFormulator::solveLPRelaxation( const Map<unsigned, Layer *> &layers, MinOrMax minOrMax, String variableName, unsigned lastLayer ) { GurobiWrapper gurobi; createLPRelaxation( layers, gurobi, lastLayer ); List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, variableName ) ); if ( minOrMax == MAX ) gurobi.setObjective( terms ); else gurobi.setCost( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); Map<String, double> dontCare; double result = 0; gurobi.extractSolution( dontCare, result ); return result; } void LPFormulator::optimizeBoundsWithIncrementalLpRelaxation( const Map<unsigned, Layer *> &layers ) { GurobiWrapper gurobi; List<GurobiWrapper::Term> terms; Map<String, double> dontCare; double lb = 0; double ub = 0; double currentLb = 0; double currentUb = 0; unsigned tighterBoundCounter = 0; unsigned signChanges = 0; unsigned cutoffs = 0; struct timespec gurobiStart; (void) gurobiStart; struct timespec gurobiEnd; (void) gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); for ( unsigned i = 0; i < _layerOwner->getNumberOfLayers(); ++i ) { ASSERT( layers.exists( i ) ); Layer *layer = layers[i]; addLayerToModel( gurobi, layer ); for ( unsigned j = 0; j < layer->getSize(); ++j ) { if ( layer->neuronEliminated( j ) ) continue; currentLb = layer->getLb( j ); currentUb = layer->getUb( j ); if ( _cutoffInUse && ( currentLb > _cutoffValue || currentUb < _cutoffValue ) ) continue; unsigned variable = layer->neuronToVariable( j ); Stringf variableName( "x%u", variable ); terms.clear(); terms.append( GurobiWrapper::Term( 1, variableName ) ); gurobi.reset(); gurobi.setObjective( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); gurobi.extractSolution( dontCare, ub ); if ( ub < currentUb ) { gurobi.setUpperBound( variableName, ub ); if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; layer->setUb( j, ub ); _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) { ++cutoffs; continue; } } gurobi.reset(); gurobi.setCost( terms ); gurobi.solve(); if ( gurobi.infeasbile() ) throw InfeasibleQueryException(); if ( !gurobi.optimal() ) throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); gurobi.extractSolution( dontCare, lb ); if ( lb > currentLb ) { gurobi.setLowerBound( variableName, lb ); if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; layer->setLb( j, lb ); _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb > _cutoffValue ) { ++cutoffs; continue; } } } } gurobiEnd = TimeUtils::sampleMicro(); LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", tighterBoundCounter, signChanges, cutoffs ).ascii() ); LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); } void LPFormulator::optimizeBoundsWithLpRelaxation( const Map<unsigned, Layer *> &layers ) { double lb = FloatUtils::negativeInfinity(); double ub = FloatUtils::infinity(); double currentLb; double currentUb; unsigned tighterBoundCounter = 0; unsigned signChanges = 0; unsigned cutoffs = 0; struct timespec gurobiStart; (void) gurobiStart; struct timespec gurobiEnd; (void) gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); for ( const auto &currentLayer : layers ) { Layer *layer = currentLayer.second; for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( layer->neuronEliminated( i ) ) continue; currentLb = layer->getLb( i ); currentUb = layer->getUb( i ); if ( _cutoffInUse && ( currentLb > _cutoffValue || currentUb < _cutoffValue ) ) continue; unsigned variable = layer->neuronToVariable( i ); Stringf variableName( "x
rapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); gurobi.addEqConstraint( terms, 0 ); } else { List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); gurobi.addGeqConstraint( terms, 0 ); terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", sourceVariable ) ) ); gurobi.addGeqConstraint( terms, 0 ); terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -sourceUb / ( sourceUb - sourceLb ), Stringf( "x%u", sourceVariable ) ) ); gurobi.addLeqConstraint( terms, ( -sourceUb * sourceLb ) / ( sourceUb - sourceLb ) ); } } } } void LPFormulator::addWeightedSumLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( !layer->neuronEliminated( i ) ) { unsigned varibale = layer->neuronToVariable( i ); gurobi.addVariable( Stringf( "x%u", varibale ), layer->getLb( i ), layer->getUb( i ) ); List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", varibale ) ) ); double bias = -layer->getBias( i ); for ( const auto &sourceLayerPair : layer->getSourceLayers() ) { const Layer *sourceLayer = _layerOwner->getLayer( sourceLayerPair.first ); unsigned sourceLayerSize = sourceLayerPair.second; for ( unsigned j = 0; j < sourceLayerSize; ++j ) { double weight = layer->getWeight( sourceLayerPair.first, j, i ); if ( !sourceLayer->neuronEliminated( j ) ) { Stringf sourceVariableName( "x%u", sourceLayer->neuronToVariable( j ) ); terms.append( GurobiWrapper::Term( weight, sourceVariableName ) ); } else { bias += weight * sourceLayer->getEliminatedNeuronValue( j ); } } } gurobi.addEqConstraint( terms, bias ); } } } void LPFormulator::setCutoff( double cutoff ) { _cutoffInUse = true; _cutoffValue = cutoff; } }
%u", variable ); ub = solveLPRelaxation( layers, MinOrMax::MAX, variableName, layer->getLayerIndex() ); if ( ub < currentUb ) { if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; layer->setUb( i, ub ); _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) { ++cutoffs; continue; } } lb = solveLPRelaxation( layers, MinOrMax::MIN, variableName, layer->getLayerIndex() ); if ( lb > currentLb ) { if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; layer->setLb( i, lb ); _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb > _cutoffValue ) { ++cutoffs; continue; } } } } gurobiEnd = TimeUtils::sampleMicro(); LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", tighterBoundCounter, signChanges, cutoffs ).ascii() ); LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); } void LPFormulator::createLPRelaxation( const Map<unsigned, Layer *> &layers, GurobiWrapper &gurobi, unsigned lastLayer ) { for ( const auto &layer : layers ) { if ( layer.second->getLayerIndex() > lastLayer ) continue; addLayerToModel( gurobi, layer.second ); } } void LPFormulator::addLayerToModel( GurobiWrapper &gurobi, const Layer *layer ) { switch ( layer->getLayerType() ) { case Layer::INPUT: addInputLayerToLpRelaxation( gurobi, layer ); break; case Layer::RELU: addReluLayerToLpRelaxation( gurobi, layer ); break; case Layer::WEIGHTED_SUM: addWeightedSumLayerToLpRelaxation( gurobi, layer ); break; default: throw NLRError( NLRError::LAYER_TYPE_NOT_SUPPORTED, "MILPFormulator" ); break; } } void LPFormulator::addInputLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { unsigned varibale = layer->neuronToVariable( i ); gurobi.addVariable( Stringf( "x%u", varibale ), layer->getLb( i ), layer->getUb( i ) ); } } void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { if ( !layer->neuronEliminated( i ) ) { unsigned targetVariable = layer->neuronToVariable( i ); List<NeuronIndex> sources = layer->getActivationSources( i ); const Layer *sourceLayer = _layerOwner->getLayer( sources.begin()->_layer ); unsigned sourceNeuron = sources.begin()->_neuron; unsigned sourceVariable = sourceLayer->neuronToVariable( sourceNeuron ); double sourceLb = sourceLayer->getLb( sourceNeuron ); double sourceUb = sourceLayer->getUb( sourceNeuron ); gurobi.addVariable( Stringf( "x%u", targetVariable ), 0, layer->getUb( i ) ); if ( !FloatUtils::isNegative( sourceLb ) ) { if ( sourceLb < 0 ) sourceLb = 0; List<GurobiWrapper::Term> terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", sourceVariable ) ) ); gurobi.addEqConstraint( terms, 0 ); } else if ( !FloatUtils::isPositive( sourceUb ) ) { List<GurobiW
random
[ { "content": "class Stringf : public String\n\n{\n\npublic:\n\n enum {\n\n MAX_STRING_LENGTH = 10000,\n\n };\n\n\n\n Stringf( const char *format, ... )\n\n {\n\n va_list argList;\n\n va_start( argList, format );\n\n\n\n char buffer[MAX_STRING_LENGTH];\n\n\n\n vspri...
C++
cpp/meta/typelist.hpp
so61pi/examples
38e2831cd6517864fc05f499f72fbb4ff6ae27c0
#ifndef TYPELIST_HPP #define TYPELIST_HPP #include <cstddef> #include <type_traits> namespace tl { template<typename... Ts> struct typelist; template<typename T, typename... Ts> struct typelist<T, Ts...> { using first_type = T; using next = typelist<Ts...>; using size = std::integral_constant<std::size_t, next::size::value + 1>; }; template<> struct typelist<> { using size = std::integral_constant<std::size_t, 0>; }; template<typename TypeList> struct is_typelist { using type = std::false_type; }; template<typename... Ts> struct is_typelist<typelist<Ts...>> { using type = std::true_type; }; template<typename TypeList> using is_typelist_t = typename is_typelist<TypeList>::type; #define TYPELIST_ASSERT(TypeList) \ static_assert(is_typelist_t<TypeList>::value, "not a typelist"); template<typename TypeList> struct size { TYPELIST_ASSERT(TypeList) using type = typename TypeList::size; }; template<typename TypeList> using size_t = typename size<TypeList>::type; template<typename TypeList> struct is_empty { TYPELIST_ASSERT(TypeList) using type = std::false_type; }; template<> struct is_empty<typelist<>> { using type = std::true_type; }; template<typename TypeList> using is_empty_t = typename is_empty<TypeList>::type; template<typename TypeList, typename IntegralIndex> struct at { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value < size<TypeList>::type::value, "index out of range"); using type = typename at<typename TypeList::next, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; }; template<typename TypeList> struct at<TypeList, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename TypeList::first_type; }; template<typename TypeList, typename IntegralIndex> using at_t = typename at<TypeList, IntegralIndex>::type; template<typename TypeList, std::size_t Index> using at_c = at<TypeList, std::integral_constant<std::size_t, Index>>; template<typename TypeList, std::size_t Index> using at_c_t = typename at_c<TypeList, Index>::type; template<typename TypeList> struct front { TYPELIST_ASSERT(TypeList) static_assert(!is_empty_t<TypeList>::value, "empty typelist"); using type = typename TypeList::first_type; }; template<typename TypeList> using front_t = typename front<TypeList>::type; template<typename TypeList, typename NewType> struct push_front; template<typename... Ts, typename NewType> struct push_front<typelist<Ts...>, NewType> { using type = typelist<NewType, Ts...>; }; template<typename TypeList, typename NewType> using push_front_t = typename push_front<TypeList, NewType>::type; template<typename TypeList, typename NewType> struct push_back { TYPELIST_ASSERT(TypeList) private: using sub = typename push_back<typename TypeList::next, NewType>::type; public: using type = typename push_front<sub, typename TypeList::first_type>::type; }; template<typename NewType> struct push_back<typelist<>, NewType> { using type = typelist<NewType>; }; template<typename TypeList, typename NewType> using push_back_t = typename push_back<TypeList, NewType>::type; template<typename TypeList> struct reverse { TYPELIST_ASSERT(TypeList) private: using reversed_sub = typename reverse<typename TypeList::next>::type; public: using type = typename push_back<reversed_sub, typename TypeList::first_type>::type; }; template<> struct reverse<typelist<>> { using type = typelist<>; }; template<typename TypeList> using reverse_t = typename reverse<TypeList>::type; template<typename TypeList> struct pop_front { TYPELIST_ASSERT(TypeList) using type = typename TypeList::next; }; template<typename TypeList> using pop_front_t = typename pop_front<TypeList>::type; template<typename TypeList> struct pop_back { TYPELIST_ASSERT(TypeList) static_assert(!is_empty_t<TypeList>::value, "empty typelist"); private: using temp = typename pop_front<typename reverse<TypeList>::type>::type; public: using type = typename reverse<temp>::type; }; template<typename TypeList> using pop_back_t = typename pop_back<TypeList>::type; template<typename TypeList, typename NewType, typename IntegralIndex> struct insert { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value <= size<TypeList>::type::value, "index out of range"); private: using sub = typename insert<typename pop_front<TypeList>::type, NewType, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; public: using type = typename push_front<sub, typename front<TypeList>::type>::type; }; template<typename TypeList, typename NewType> struct insert<TypeList, NewType, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename push_front<TypeList, NewType>::type; }; template<typename TypeList, typename NewType, typename IntegralIndex> using insert_t = typename insert<TypeList, NewType, IntegralIndex>::type; template<typename TypeList, typename NewType, std::size_t Index> using insert_c = insert<TypeList, NewType, std::integral_constant<std::size_t, Index>>; template<typename TypeList, typename NewType, std::size_t Index> using insert_c_t = typename insert_c<TypeList, NewType, Index>::type; template<typename TypeList, typename IntegralIndex> struct remove { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value < size<TypeList>::type::value, "index out of range"); private: using sub = typename remove<typename pop_front<TypeList>::type, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; public: using type = typename push_front<sub, typename front<TypeList>::type>::type; }; template<typename TypeList> struct remove<TypeList, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename pop_front<TypeList>::type; }; template<typename TypeList, typename IntegralIndex> using remove_t = typename remove<TypeList, IntegralIndex>::type; template<typename TypeList, std::size_t Index> using remove_c = remove<TypeList, std::integral_constant<std::size_t, Index>>; template<typename TypeList, std::size_t Index> using remove_c_t = typename remove_c<TypeList, Index>::type; template<typename Left, typename Right> struct concat { TYPELIST_ASSERT(Left) TYPELIST_ASSERT(Right) private: using newLeft = typename push_back<Left, typename Right::first_type>::type; using newRight = typename Right::next; public: using type = typename concat<newLeft, newRight>::type; }; template<typename Left> struct concat<Left, typelist<>> { TYPELIST_ASSERT(Left) using type = Left; }; template<typename Left, typename Right> using concat_t = typename concat<Left, Right>::type; } #endif
#ifndef TYPELIST_HPP #define TYPELIST_HPP #include <cstddef> #include <type_traits> namespace tl { template<typename... Ts> struct typelist; template<typename T, typename... Ts> struct typelist<T, Ts...> { using first_type = T; using next = typelist<Ts...>; using size = std::integral_constant<std::size_t, next::size::value + 1>; }; template<> struct typelist<> { using size = std::integral_constant<std::size_t, 0>; }; template<typename TypeList> struct is_typelist { using type = std::false_type; }; template<typename... Ts> struct is_typelist<typelist<Ts...>> { using type = std::true_type; }; template<typename TypeList> using is_typelist_t = typename is_typelist<TypeList>::type; #define TYPELIST_ASSERT(TypeList) \ static_assert(is_typelist_t<TypeList>::value, "not a typelist"); template<typename TypeList> struct size { TYPELIST_ASSERT(TypeList) using type = typename TypeList::size; }; template<typename TypeList> using size_t = typename size<TypeList>::type; template<typename TypeList> struct is_empty { TYPELIST_ASSERT(TypeList) using type = std::false_type; }; template<> struct is_empty<typelist<>> { using type = std::true_type; }; template<typename TypeList> using is_empty_t = typename is_empty<TypeList>::type; template<typename TypeList, typename IntegralIndex> struct at { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value < size<TypeList>::type::value, "index out of range"); using type = typename at<typename TypeList::next, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; }; template<typename TypeList> struct at<TypeList, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename TypeList::first_type; }; template<typename TypeList, typename IntegralIndex> using at_t = typename at<TypeList, IntegralIndex>::type; template<typename TypeList, std::size_t Index> using at_c = at<TypeList, std::integral_constant<std::size_t, Index>>; template<typename TypeList, std::size_t Index> using at_c_t = typename at_c<TypeList, Index>::type; template<typename TypeList> struct front { TYPELIST_ASSERT(TypeList) static_assert(!is_empty_t<TypeList>::value, "empty typelist"); using type = typename TypeList::first_type; }; template<typename TypeList> using front_t = typename front<TypeList>::type; template<typename TypeList, typename NewType> struct push_front; template<typename... Ts, typename NewType> struct push_front<typelist<Ts...>, NewType> { using type = typelist<NewType, Ts...>; }; template<typename TypeList, typename NewType> using push_front_t = typename push_front<TypeList, NewType>::type; template<typename TypeList, typename NewType> struct push_back { TYPELIST_ASSERT(TypeList) private: using sub = typename push_back<typename TypeList::next, NewType>::type; public: using type = typename push_front<sub, typename TypeList::first_type>::type; }; template<typename NewType> struct push_back<typelist<>, NewType> { using type = typelist<NewType>; }; template<typename TypeList, typename NewType> using push_back_t = typename push_back<TypeList, NewType>::type; template<typename TypeList> struct reverse { TYPELIST_ASSERT(TypeList) private: using reversed_sub = typename reverse<typename TypeList::next>::type; public: using type = typename push_back<reversed_sub, typename TypeList::first_type>::type; }; template<> struct reverse<typelist<>> { using type = typelist<>; }; template<typename TypeList> using reverse_t = typename reverse<TypeList>::type; template<typename TypeList> struct pop_front { TYPELIST_ASSERT(TypeList) using type = typename TypeList::next; }; template<typename TypeList> using pop_front_t = typename pop_front<TypeList>::type; template<typename TypeList> struct pop_back { TYPELIST_ASSERT(TypeList) static_assert(!is_empty_t<TypeList>::value, "empty typelist"); private: using temp = typename pop_front<typename reverse<TypeList>::type>::type; public: using type = typename reverse<temp>::type; }; template<typename TypeList> using pop_back_t = typename pop_back<TypeList>::type; template<typename TypeList, typename NewType, typename IntegralIndex> struct insert { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value <= size<TypeList>::type::value, "index out of range"); private: using sub = typename insert<typename pop_front<TypeList>::type, NewType, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; public: using type = typename push_front<sub, typename front<TypeList>::type>::type; }; template<typename TypeList, typename NewType> struct insert<TypeList, NewType, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename push_front<TypeList, NewType>::type; }; template<typename TypeList, typename NewType, typename IntegralIndex> using insert_t = typename insert<TypeList, NewType, IntegralIndex>::type; template<typename TypeList, typename NewType, std::size_t Index> using insert_c = insert<TypeList, NewType, std::integral_constant<std::size_t, Index>>; template<typename TypeList, typename NewType, std::size_t Index> using insert_c_t = typename insert_c<TypeList, NewType, Index>::type; template<typename TypeList, typename IntegralIndex> struct remove { TYPELIST_ASSERT(TypeList) static_assert(IntegralIndex::value < size<TypeList>::type::value, "index out of range"); private: using sub = typename remove<typename pop_front<TypeList>::type, std::integral_constant<std::size_t, IntegralIndex::value - 1>>::type; public: using type = typename push_front<sub, typename front<TypeList>::type>::type; }; template<typename TypeList> struct remove<TypeList, std::integral_constant<std::size_t, 0>> { TYPELIST_ASSERT(TypeList) using type = typename pop_front<TypeList>:
late<typename Left, typename Right> struct concat { TYPELIST_ASSERT(Left) TYPELIST_ASSERT(Right) private: using newLeft = typename push_back<Left, typename Right::first_type>::type; using newRight = typename Right::next; public: using type = typename concat<newLeft, newRight>::type; }; template<typename Left> struct concat<Left, typelist<>> { TYPELIST_ASSERT(Left) using type = Left; }; template<typename Left, typename Right> using concat_t = typename concat<Left, Right>::type; } #endif
:type; }; template<typename TypeList, typename IntegralIndex> using remove_t = typename remove<TypeList, IntegralIndex>::type; template<typename TypeList, std::size_t Index> using remove_c = remove<TypeList, std::integral_constant<std::size_t, Index>>; template<typename TypeList, std::size_t Index> using remove_c_t = typename remove_c<TypeList, Index>::type; temp
random
[ { "content": "struct lambda<std::integral_constant<std::size_t, Index>> {\n\n using type =\n\n struct {\n\n template<typename... Xs>\n\n struct apply {\n\n static_assert(Index < sizeof...(Xs), \"index out of range\");\n\n \n\n using ty...
C++
cplusplus/call/src/alignment_functions.cpp
erasmus-center-for-biomics/Nimbus
bbf7ca288d798d8f1c6156ddf45fed31892bd557
#include <cstdlib> #include <string> #include <sstream> #include <iostream> #include <vector> #include <algorithm> #include <sam.h> #include <alignment_functions.h> #include <cigar.h> #include <sample.h> namespace nimbus { std::string alignment_sequence( const bam1_t* alignment, int start, int end ) { std::stringstream rval ; uint8_t* s = bam_get_seq( alignment ) ; for( int i=start; i<=end; ++i ) { int b = bam_seqi( s, i ) ; switch(b) { case 1: rval << "A" ; break ; case 2: rval << "C" ; break ; case 4: rval << "G" ; break ; case 8: rval << "T" ; break ; default: rval << "N" ; break ; } } return rval.str() ; } int alignment_sequence_quality( const bam1_t* alignment, int start, int end ) { int rval = 0 ; uint8_t* q = bam_get_qual( alignment ) ; for( int i=start; i<=end; ++i ) { rval += (int) q[i] ; } rval /= end - start + 1 ; return rval ; } std::string Sequence( int tid, int pos, const bam1_t* alignment, void* results ) { std::string rval = "" ; int variantqual = 0 ; std::size_t relpos = 0 ; if( alignment->core.pos < pos ) { relpos = (std::size_t) pos - alignment->core.pos ; } Cigar cigar = Cigar( ) ; cigar.from_hts_cigar( bam_get_cigar(alignment), alignment->core.n_cigar ) ; std::size_t opbin = 0 ; std::size_t oppos = 0 ; std::size_t q_pos = cigar.reference_offset_to_query_offset( relpos, opbin, oppos ) ; bool calledindel = false ; if( cigar.at( opbin )->operation() == 'M' || cigar.at( opbin )->operation() == '=' || cigar.at( opbin )->operation() == 'X') { if( (oppos) == cigar.at( opbin )->runLength() - 1) { if ( opbin < cigar.length() - 1 ) { if( cigar.at( opbin + 1 )->operation() == 'D' ) { rval = alignment_sequence( alignment, q_pos, q_pos ) ; rval += std::string( cigar.at( opbin + 1 )->runLength(), '-' ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos ) ; calledindel = true ; } else if( cigar.at( opbin + 1)->operation() == 'I' ) { calledindel = true ; rval = alignment_sequence( alignment, q_pos, q_pos + cigar.at( opbin + 1 )->runLength() ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos + cigar.at( opbin + 1 )->runLength() ) ; } } } if( ! calledindel ) { rval = alignment_sequence( alignment, q_pos, q_pos ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos ) ; } } if( results != NULL ) { SequenceInformation* ret = (SequenceInformation*) results ; ret->query_position = q_pos ; ret->quality = variantqual ; } return rval ; } std::string ReadGroup( const bam1_t* alignment ) { std::string rval = "unknown" ; uint8_t* p = bam_aux_get( alignment, "RG" ) ; if( p ) { rval = std::string( bam_aux2Z(p) ) ; } return rval ; } std::string GetLabel( const bam1_t* alignment, std::string label ) { std::string rval = "unknown" ; if( label.size() != 2 ) return rval ; uint8_t* p = bam_aux_get( alignment, label.c_str() ) ; if( p ) { rval = std::string( bam_aux2Z(p) ) ; } return rval ; } std::string Strand( const bam1_t* alignment ) { return bam_is_rev(alignment) ? "reverse" : "forward" ; } std::string Amplicon( const bam1_t* alignment ) { uint8_t* p = bam_aux_get( alignment, "am" ) ; if( p ) { return std::string( bam_aux2Z(p) ) ; } return "unknown" ; } }
#include <cstdlib> #include <string> #include <sstream> #include <iostream> #include <vector> #include <algorithm> #include <sam.h> #include <alignment_functions.h> #include <cigar.h> #include <sample.h> namespace nimbus { std::string alignment_sequence( const bam1_t* alignment, int start, int end ) { std::stringstream rval ; uint8_t* s = bam_get_seq( alignment ) ; for( int i=start; i<=end; ++i ) { int b = bam_seqi( s, i ) ; switch(b) { case 1: rval << "A" ; break ; case 2: rval << "C" ; break ; case 4: rval << "G" ; break ; case 8: rval << "T" ; break ; default: rval << "N" ; break ; } } return rval.str() ; } int alignment_sequence_quality( const bam1_t* alignment, int start, int end ) { int rval = 0 ; uint8_t* q = bam_get_qual( alignment ) ; for( int i=start; i<=end; ++i ) { rval += (int) q[i] ; } rval /= end - start + 1 ; return rval ; } std::string Sequence( int tid, int pos, const bam1_t* alignment, void* results ) { std::string rval = "" ; int variantqual = 0 ; std::size_t relpos = 0 ; if( alignment->core.pos < pos ) { relpos = (std::size_t) pos - alignment->core.pos ; } Cigar cigar = Cigar( ) ; cigar.from_hts_cigar( bam_get_cigar(alignment), alignment->core.n_cigar ) ; std::size_t opbin = 0 ; std::size_t oppos = 0 ; std::size_t q_pos = cigar.reference_offset_to_query_offset( relpos, opbin, oppos ) ; bool calledindel = false ; if( cigar.at( opbin )->operation() == 'M' || cigar.at( opbin )->operation() == '=' || cigar.at( opbin )->operation() == 'X') { if( (oppos) == cigar.at( opbin )->runLength() - 1) { if ( opbin < cigar.length() - 1 ) { if( cigar.at( opbin + 1 )->operation() == 'D' ) { rval = alignment_sequence( alignment, q_pos, q_pos ) ; rval += std::string( cigar.at( opbin + 1 )->runLength(), '-' ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos ) ; calledindel = true ; } else if( cigar.at( opbin + 1)->operation() == 'I' ) { calledindel = true ; rval = alignment_sequence( alignment, q_pos, q_pos + cigar.at( opbin + 1 )->runLength() ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos + cigar.at( opbin + 1 )->runLength() ) ; } } } if( ! calledindel ) { rval = alignment_sequence( alignment, q_pos, q_pos ) ; variantqual = alignment_sequence_quality( alignment, q_pos, q_pos ) ; } } if( results != NULL ) { SequenceInformation* ret = (SequenceInformation*) results ; ret->query_position = q_pos ; ret->quality = variantqual ; } return rval ; } std::string ReadGroup( const bam1_t* alignment ) { std::string rval = "unknown" ; uint8_t* p = bam_aux_get( alignment, "RG" ) ; if( p ) { rval = std::string( bam_aux2Z(p) ) ; } return rval ; } std::string GetLabel( const bam1_t* alignment, std::string label ) {
std::string Strand( const bam1_t* alignment ) { return bam_is_rev(alignment) ? "reverse" : "forward" ; } std::string Amplicon( const bam1_t* alignment ) { uint8_t* p = bam_aux_get( alignment, "am" ) ; if( p ) { return std::string( bam_aux2Z(p) ) ; } return "unknown" ; } }
std::string rval = "unknown" ; if( label.size() != 2 ) return rval ; uint8_t* p = bam_aux_get( alignment, label.c_str() ) ; if( p ) { rval = std::string( bam_aux2Z(p) ) ; } return rval ; }
function_block-function_prefix_line
[ { "content": "\tclass CigarOperation {\n\n\t\tchar _operation ;\n\n\t\tstd::size_t _runlength ;\n\n\n\n\tpublic:\n\n\t\tCigarOperation() {\n\n\t\t\t_operation = '?' ;\n\n\t\t\t_runlength = 0 ;\n\n\t\t}\n\n\n\n\t\tCigarOperation( char o, std::size_t n ) {\n\n\t\t\tset( o, n ) ;\n\n\t\t}\n\n\n\n\t\tvoid set( char...
C++
software/src/master/src/vca_sample_distribution_server/vca_sample_distribution_server.cpp
c-kuhlman/vision
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
#include "Vk.h" #include "Vca_VOneAppMain_.h" #include "Vca_VServerApplication.h" #include "Vca_VLineGrabber.h" #include "vca_samples_ipublication.h" #include "vca_samples_isubscription.h" namespace VcaSamples { class ThisApp : public Vca::VServerApplication { DECLARE_CONCRETE_RTT (ThisApp, Vca::VServerApplication); public: typedef Reference AppReference; typedef Vca::VLineGrabber_<ThisClass> InputSource; public: class Subscription : public Vca::VRolePlayer { DECLARE_CONCRETE_RTT (Subscription, Vca::VRolePlayer); public: typedef IVReceiver<VString const &> IRecipient; public: Subscription (ThisApp *pApp, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended); private: ~Subscription (); public: using BaseClass::getRole; private: Vca::VRole<ThisClass,ISubscription> m_pISubscription; public: void getRole (ISubscription::Reference &rpRole) { m_pISubscription.getRole (rpRole); } public: void Suspend (ISubscription *pRole); void Resume (ISubscription *pRole); void Cancel (ISubscription *pRole); public: ThisClass *publish (VString const &rMessage); private: void unlink (); private: AppReference const m_pApp; ISubscriber::Reference const m_pSubscriber; IRecipient::Reference const m_pRecipient; Pointer m_pSuccessor; Pointer m_pPredecessor; bool m_bSuspended; bool m_bCanceled; }; friend class Subscription; public: ThisApp (Context *pContext); private: ~ThisApp (); public: using BaseClass::getRole; private: Vca::VRole<ThisClass,IPublication> m_pIPublication; public: void getRole (IPublication::Reference &rpRole) { m_pIPublication.getRole (rpRole); } public: void Subscribe ( IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ); private: virtual void onStandardInput (Vca::VBSProducer *pStdin) OVERRIDE; virtual bool start_() OVERRIDE; public: bool onInputLine (char const *pLine, size_t sLine); void onInputDone (); private: Subscription::Pointer m_pSubscriptions; }; } template class Vca::VLineGrabber_<VcaSamples::ThisApp>; DEFINE_CONCRETE_RTT (VcaSamples::ThisApp); VcaSamples::ThisApp::ThisApp (Context *pContext) : BaseClass (pContext), m_pIPublication (this) { } VcaSamples::ThisApp::~ThisApp () { } void VcaSamples::ThisApp::Subscribe ( IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ) { if (pSubscriber) { Subscription::IRecipient::Reference pMessageReceiver ( dynamic_cast<Subscription::IRecipient*>(pRecipient) ); if (pMessageReceiver.isNil ()) pSubscriber->OnError (0, "Invalid or Missing Recipient"); else { Subscription::Reference pSubscription ( new Subscription (this, pSubscriber, pMessageReceiver, bSuspended) ); } } } bool VcaSamples::ThisApp::start_() { if (!BaseClass::start_()) return false; if (offerSelf ()) getStandardInput (); else { fprintf (stderr, "Usage: No address to offer object.\n"); setExitStatus (ErrorExitValue); } return isStarting (); } void VcaSamples::ThisApp::onStandardInput (Vca::VBSProducer *pStdin) { InputSource::Reference pInputProvider (new InputSource (pStdin, this)); } bool VcaSamples::ThisApp::onInputLine (char const *pLine, size_t sLine) { VString iText; iText.setTo (pLine, sLine); Subscription::Reference pSubscription (m_pSubscriptions); while (pSubscription) { pSubscription.setTo (pSubscription->publish (iText)); } return true; } void VcaSamples::ThisApp::onInputDone () { stop (); } DEFINE_CONCRETE_RTT (VcaSamples::ThisApp::Subscription); VcaSamples::ThisApp::Subscription::Subscription ( ThisApp *pApp, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ) : m_pApp (pApp) , m_pSubscriber (pSubscriber) , m_pRecipient (pRecipient) , m_pSuccessor (pApp->m_pSubscriptions) , m_bSuspended (bSuspended) , m_bCanceled (false) , m_pISubscription (this) { pApp->m_pSubscriptions.setTo (this); retain (); { ISubscription::Reference pRole; getRole (pRole); pSubscriber->OnData (pRole); } untain (); } VcaSamples::ThisApp::Subscription::~Subscription () { unlink (); } void VcaSamples::ThisApp::Subscription::Suspend (ISubscription *pRole) { if (!m_bCanceled) m_bSuspended = true; } void VcaSamples::ThisApp::Subscription::Resume (ISubscription *pRole) { if (!m_bCanceled) m_bSuspended = false; } void VcaSamples::ThisApp::Subscription::Cancel (ISubscription *pRole) { unlink (); } VcaSamples::ThisApp::Subscription *VcaSamples::ThisApp::Subscription::publish (VString const &rMessage) { if (m_pRecipient && !m_bSuspended) m_pRecipient->OnData (rMessage); return m_pSuccessor; } void VcaSamples::ThisApp::Subscription::unlink () { m_bCanceled = m_bSuspended = true; if (m_pSuccessor) m_pSuccessor->m_pPredecessor.setTo (m_pPredecessor); if (m_pPredecessor) m_pPredecessor->m_pSuccessor.setTo (m_pSuccessor); else m_pApp->m_pSubscriptions.setTo (m_pSuccessor); m_pPredecessor.clear (); m_pSuccessor.clear (); } int main (int argc, char *argv[]) { Vca::VOneAppMain_<VcaSamples::ThisApp> iMain (argc, argv); return iMain.processEvents (); }
#include "Vk.h" #include "Vca_VOneAppMain_.h" #include "Vca_VServerApplication.h" #include "Vca_VLineGrabber.h" #include "vca_samples_ipublication.h" #include "vca_samples_isubscription.h" namespace VcaSamples { class ThisApp : public Vca::VServerApplication { DECLARE_CONCRETE_RTT (ThisApp, Vca::VServerApplication); public: typedef Reference AppReference; typedef Vca::VLineGrabber_<ThisClass> InputSource; public: class Subscription : public Vca::VRolePlayer { DECLARE_CONCRETE_RTT (Subscription, Vca::VRolePlayer); public: typedef IVReceiver<VString const &> IRecipient; public: Subscription (ThisApp *pApp, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended); private: ~Subscription (); public: using BaseClass::getRole; private: Vca::VRole<ThisClass,ISubscription> m_pISubscription; public: void getRole (ISubscription::Reference &rpRole) { m_pISubscription.getRole (rpRole); } public: void Suspend (ISubscription *pRole); void Resume (ISubscription *pRole); void Cancel (ISubscription *pRole); public: ThisClass *publish (VString const &rMessage); private: void unlink (); private: AppReference const m_pApp; ISubscriber::Reference const m_pSubscriber; IRecipient::Reference const m_pRecipient; Pointer m_pSuccessor; Pointer m_pPredecessor; bool m_bSuspended; bool m_bCanceled; }; friend class Subscription; public: ThisApp (Context *pContext); private: ~ThisApp (); public: using BaseClass::getRole; private: Vca::VRole<ThisClass,IPublication> m_pIPublication; public: void getRole (IPublication::Reference &rpRole) { m_pIPublication.getRole (rpRole); } public: void Subscribe ( IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ); private: virtual void onStandardInput (Vca::VBSProducer *pStdin) OVERRIDE; virtual bool start_() OVERRIDE; public: bool onInputLine (char const *pLine, size_t sLine); void onInputDone (); private: Subscription::Pointer m_pSubscriptions; }; } template class Vca::VLineGrabber_<VcaSamples::ThisApp>; DEFINE_CONCRETE_RTT (VcaSamples::ThisApp); VcaSamples::ThisApp::ThisApp (Context *pContext) : BaseClass (pContext), m_pIPublication (this) { } VcaSamples::ThisApp::~ThisApp () { }
bool VcaSamples::ThisApp::start_() { if (!BaseClass::start_()) return false; if (offerSelf ()) getStandardInput (); else { fprintf (stderr, "Usage: No address to offer object.\n"); setExitStatus (ErrorExitValue); } return isStarting (); } void VcaSamples::ThisApp::onStandardInput (Vca::VBSProducer *pStdin) { InputSource::Reference pInputProvider (new InputSource (pStdin, this)); } bool VcaSamples::ThisApp::onInputLine (char const *pLine, size_t sLine) { VString iText; iText.setTo (pLine, sLine); Subscription::Reference pSubscription (m_pSubscriptions); while (pSubscription) { pSubscription.setTo (pSubscription->publish (iText)); } return true; } void VcaSamples::ThisApp::onInputDone () { stop (); } DEFINE_CONCRETE_RTT (VcaSamples::ThisApp::Subscription); VcaSamples::ThisApp::Subscription::Subscription ( ThisApp *pApp, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ) : m_pApp (pApp) , m_pSubscriber (pSubscriber) , m_pRecipient (pRecipient) , m_pSuccessor (pApp->m_pSubscriptions) , m_bSuspended (bSuspended) , m_bCanceled (false) , m_pISubscription (this) { pApp->m_pSubscriptions.setTo (this); retain (); { ISubscription::Reference pRole; getRole (pRole); pSubscriber->OnData (pRole); } untain (); } VcaSamples::ThisApp::Subscription::~Subscription () { unlink (); } void VcaSamples::ThisApp::Subscription::Suspend (ISubscription *pRole) { if (!m_bCanceled) m_bSuspended = true; } void VcaSamples::ThisApp::Subscription::Resume (ISubscription *pRole) { if (!m_bCanceled) m_bSuspended = false; } void VcaSamples::ThisApp::Subscription::Cancel (ISubscription *pRole) { unlink (); } VcaSamples::ThisApp::Subscription *VcaSamples::ThisApp::Subscription::publish (VString const &rMessage) { if (m_pRecipient && !m_bSuspended) m_pRecipient->OnData (rMessage); return m_pSuccessor; } void VcaSamples::ThisApp::Subscription::unlink () { m_bCanceled = m_bSuspended = true; if (m_pSuccessor) m_pSuccessor->m_pPredecessor.setTo (m_pPredecessor); if (m_pPredecessor) m_pPredecessor->m_pSuccessor.setTo (m_pSuccessor); else m_pApp->m_pSubscriptions.setTo (m_pSuccessor); m_pPredecessor.clear (); m_pSuccessor.clear (); } int main (int argc, char *argv[]) { Vca::VOneAppMain_<VcaSamples::ThisApp> iMain (argc, argv); return iMain.processEvents (); }
void VcaSamples::ThisApp::Subscribe ( IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended ) { if (pSubscriber) { Subscription::IRecipient::Reference pMessageReceiver ( dynamic_cast<Subscription::IRecipient*>(pRecipient) ); if (pMessageReceiver.isNil ()) pSubscriber->OnError (0, "Invalid or Missing Recipient"); else { Subscription::Reference pSubscription ( new Subscription (this, pSubscriber, pMessageReceiver, bSuspended) ); } } }
function_block-full_function
[ { "content": "\t class Property_<void (Container_T::*)(IVReceiver<Value_T>*) const> : public Property {\n\n\tpublic:\n\n\t typedef void (Container_T::*accessor_t)(IVReceiver<Value_T>*) const;\n\n\t typedef Property_<accessor_t> this_t;\n\n\t DECLARE_CONCRETE_RTTLITE (this_t, Property);\n\n\n\n\t// ...
C++
nestedtensor/csrc/nested_tensor_impl.cpp
jbschlosser/nestedtensor
29d58d85ccd2c1b47fc40f2786f08c713f49acc6
#include <ATen/ATen.h> #include <ATen/NamedTensorUtils.h> #include <ATen/WrapDimUtils.h> #include <ATen/core/op_registration/op_registration.h> #include <nestedtensor/csrc/nested_tensor_impl.h> #include <nestedtensor/csrc/utils/nested_node_functions.h> #include <torch/csrc/jit/runtime/operator.h> #include <torch/library.h> #include <c10/core/DispatchKey.h> #include <nestedtensor/csrc/transpose.h> namespace at { using namespace torch::nested_tensor; using namespace c10; TensorNode _unbind_tensors(TensorNode structure) { std::vector<TensorNode> result_nodes; if (structure.is_leaf()) { for (at::Tensor tensor : structure.payload().unbind()) { result_nodes.emplace_back(TensorNode(std::move(tensor))); } } else { for (TensorNode child : structure.unbind()) { result_nodes.emplace_back(_unbind_tensors(child)); } } return TensorNode(std::move(result_nodes)); } NestedTensorImpl::NestedTensorImpl(std::shared_ptr<NestedTensorStorage> storage) : TensorImpl( c10::DispatchKeySet({NestedTensorKey}), storage->dtype(), storage->device()), _storage(storage) { remove_autograd_key(); key_set_ = key_set_ - c10::DispatchKeySet({c10::DispatchKey::ADInplaceOrView}); } inline TensorNode _squeeze_nested_dim(TensorNode structure, int64_t dim) { return squeeze(structure, dim, false); } int64_t NestedTensor_size_int(const Tensor& self, int64_t dim) { std::vector<c10::optional<int64_t>> size = get_nested_tensor_impl(self)->opt_sizes(); if (size[dim]) { return *(size[dim]); } throw std::runtime_error( "NestedTensor size at dim is not Tensor shape compliant."); } int64_t nt_size(Tensor tensor, int64_t dim) { auto impl = get_nested_tensor_impl(tensor); std::vector<c10::optional<int64_t>> size = impl->opt_sizes(); if (size[dim]) { return *(size[dim]); } throw std::runtime_error( "NestedTensor size at dim is not Tensor shape compliant."); } at::Tensor wrap_tensor_node(TensorNode&& result) { if (result.is_leaf()) { return result.payload(); } PackedStorage* ls = new PackedStorage(std::move(result)); NestedTensorStorage* ls_base = dynamic_cast<NestedTensorStorage*>(ls); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ls_base)); } std::vector<at::Tensor> wrap_tensor_node(std::vector<TensorNode> input) { std::vector<at::Tensor> result; for (size_t i = 0; i < input.size(); i++) { result.push_back(wrap_tensor_node(std::move(input[i]))); } return result; } at::Tensor wrap_buffer(at::Tensor&& buffer, SizeNode nested_size) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); if (nested_size.is_leaf()) { return buffer.reshape(IntArrayRef(nested_size.payload())); } PackedStorage* ps = new PackedStorage(std::move(buffer), nested_size); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } at::Tensor wrap_buffer( at::Tensor&& buffer, EfficientSizeNode efficient_nested_size, EfficientSizeNode efficient_nested_stride) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); TORCH_CHECK( efficient_nested_size.height() > 0, "Internal error: expected nested_size of non-zero height."); TORCH_CHECK( efficient_nested_stride.height() > 0, "Internal error: expected nested_size of non-zero height."); PackedStorage* ps = new PackedStorage( std::move(buffer), efficient_nested_size, efficient_nested_stride); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } at::Tensor wrap_buffer( at::Tensor&& buffer, EfficientSizeNode efficient_nested_size) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); TORCH_CHECK( efficient_nested_size.height() > 0, "Internal error: expected nested_size of non-zero height."); PackedStorage* ps = new PackedStorage( std::move(buffer), efficient_nested_size); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } Tensor NestedTensor_contiguous(const Tensor& self, MemoryFormat memory_format) { if (get_is_contiguous(self, memory_format)) { return self; } TORCH_CHECK( memory_format != MemoryFormat::Preserve, "preserve memory format is unsupported by the contiguous operator"); if (memory_format == at::MemoryFormat::Contiguous) { if (get_is_contiguous(self, c10::MemoryFormat::ChannelsLast)) { auto transposed_sizes = map_efficient_size([](int64_t* size_ptr, int64_t size) { int64_t tmp = size_ptr[0]; size_ptr[0] = size_ptr[2]; size_ptr[2] = tmp; tmp = size_ptr[0]; size_ptr[0] = size_ptr[1]; size_ptr[1] = tmp; }, get_efficient_nested_size(self)); Tensor self_transposed = wrap_buffer(get_buffer(self), transposed_sizes); return transpose_nhwc_nchw(self_transposed); } PackedStorage* ps = new PackedStorage(get_nested_tensor_structure(self)); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } if (memory_format == at::MemoryFormat::ChannelsLast) { Tensor self_cont = self; if (!get_is_contiguous(self, c10::MemoryFormat::Contiguous)) { self_cont = NestedTensor_contiguous(self, at::MemoryFormat::Contiguous); } TORCH_CHECK(get_dim(self_cont) == 4, "ChannelsLast memory format requires 4 dim input."); auto new_strides = map_efficient_size([](int64_t* stride_ptr, int64_t* size_ptr, int64_t size) { stride_ptr[2] = size_ptr[0]; stride_ptr[1] = stride_ptr[2] * size_ptr[2]; stride_ptr[0] = 1; }, get_efficient_nested_stride(self_cont), get_efficient_nested_size(self_cont)); self_cont = transpose_nchw_nhwc(self_cont); return wrap_buffer(get_buffer(self_cont), get_efficient_nested_size(self), new_strides); } TORCH_CHECK(false, "Given memory format ", memory_format, " not supported by NestedTensor_contiguous."); return self; } bool NestedTensor_is_pinned(const Tensor& self, c10::optional<Device> device) { TORCH_CHECK( !device.has_value() || device->is_cuda(), "NestedTensor doesn't support non-CUDA pinned memory"); return get_nested_tensor_impl(self)->is_pinned(); } std::vector<at::Tensor> NestedTensor_unbind( const at::Tensor& self, int64_t dim) { auto _data = get_nested_tensor_impl(self); dim = at::maybe_wrap_dim(dim, get_dim(self)); auto node = _data->get_structure(); if (dim == 0) { return wrap_tensor_node(node.unbind()); } std::vector<std::vector<TensorNode>> unbound; for (auto child : node.unbind()) { std::vector<at::Tensor> tmp = at::unbind(wrap_tensor_node(std::move(child)), dim - 1); for (size_t j = 0; j < tmp.size(); j++) { if (j >= unbound.size()) { unbound.resize(j + 1); } unbound[j].push_back(TensorNode(std::move(tmp[j]))); } } std::vector<TensorNode> result; for (size_t i = 0; i < unbound.size(); i++) { result.push_back(TensorNode(std::move(unbound[i]))); } return wrap_tensor_node(result); } Tensor NestedTensor_select(const Tensor& self, int64_t dim, int64_t index) { int64_t ndim = get_dim(self); dim = maybe_wrap_dim(dim, ndim); if (dim != 0) { TORCH_CHECK_INDEX(false, "select() only supports dim == 0 for now."); } auto tmp = get_nested_tensor_structure(self).unbind()[index]; return wrap_tensor_node(std::move(tmp)); } Tensor NestedTensor_to_nested_tensor( at::Tensor input, c10::optional<int64_t> dim_) { int64_t dim = 0; if (dim_) { dim = *dim_; dim = maybe_wrap_dim(*dim_, get_dim(input) + 1); } TORCH_CHECK( dim <= get_dim(input), "target nested dimension needs to be equal or less than to input dimension"); if (is_nested_tensor_impl(input) && dim >= get_nested_dim(input)) { TensorNode unbound = _unbind_tensors(get_nested_tensor_structure(input)); for (int64_t i = 0; i < (dim - get_nested_dim(input)); i++) { unbound = _unbind_tensors(unbound); } return wrap_tensor_node(std::move(unbound)); } if (!is_nested_tensor_impl(input) && dim > 0) { std::vector<TensorNode> unbound_nodes; for (at::Tensor t : input.unbind()) { unbound_nodes.push_back(TensorNode(std::move(t))); } TensorNode unbound(std::move(unbound_nodes)); for (int64_t i = 1; i < dim; i++) { unbound = _unbind_tensors(unbound); } return wrap_tensor_node(std::move(unbound)); } return input; } Tensor NestedTensor_slice( const Tensor& self, int64_t dim, c10::optional<int64_t> start_, c10::optional<int64_t> end_, int64_t step) { int64_t start; if (start_) { start = *start_; } else { start = 0; } int64_t end; if (end_) { end = *end_; } else { end = 9223372036854775807; } int64_t ndim = get_dim(self); if (ndim == 0) { TORCH_CHECK_INDEX(false, "slice() cannot be applied to a 0-dim tensor."); } dim = maybe_wrap_dim(dim, ndim); if (dim != 0) { TORCH_CHECK_INDEX(false, "slice() only supports dim == 0 for now."); } TORCH_CHECK(step >= 1, "slice step must be positive for now."); int64_t sizes_0 = nt_size(self, 0); if (start < 0) { start += sizes_0; } if (end < 0) { end += sizes_0; } if (start < 0) { start = 0; } else if (start >= sizes_0) { start = sizes_0; } if (end < start) { end = start; } else if (end >= sizes_0) { end = sizes_0; } std::vector<at::Tensor> unbound = at::unbind(self, 0); std::vector<TensorNode> new_tensor_nodes; for (int64_t i = start; i < end; i += step) { if (is_nested_tensor_impl(unbound[i])) { new_tensor_nodes.push_back(get_nested_tensor_structure(unbound[i])); } else { new_tensor_nodes.push_back(TensorNode(std::move(unbound[i]))); } } auto result = wrap_tensor_node(TensorNode(std::move(new_tensor_nodes))); namedinference::propagate_names(result, self); return result; } Tensor& NestedTensor_copy_(Tensor& self, const Tensor& src, bool non_blocking) { apply_nested_tensor( [](at::Tensor& self, at::Tensor& source) { return self.copy_(source); }, self, src); return self; } Tensor _NestedTensor_squeeze_(Tensor self, c10::optional<int64_t> dim_) { auto self_impl = get_nested_tensor_impl(self); if (!dim_) { auto init_sizes = self_impl->opt_sizes(); for (size_t i = 0; i < init_sizes.size() - 1; i++) { int64_t index = init_sizes.size() - i - 1; c10::optional<int64_t> s = init_sizes[index]; if (s && ((*s) == 1)) { self = _NestedTensor_squeeze_(self, index); } } return self; } int64_t dim = at::maybe_wrap_dim(*dim_, get_dim(self)); TORCH_CHECK(dim > 0, "Cannot squeeze first dimension."); TORCH_CHECK( ((get_nested_tensor_impl(self)->opt_sizes()[dim]) && ((*(get_nested_tensor_impl(self)->opt_sizes()[dim])) == 1)), "Given dimension is either undefined or not a singleton."); if (dim < get_nested_tensor_impl(self)->nested_dim()) { return wrap_tensor_node( _squeeze_nested_dim(self_impl->get_structure(), dim)); } int64_t height = self_impl->get_structure().height(); return map_nested_tensor( [dim, height](at::Tensor tensor) { return tensor.squeeze(dim - height); }, self); } Tensor& NestedTensor_squeeze_(Tensor& self) { self = _NestedTensor_squeeze_(self, c10::nullopt); return self; } Tensor& NestedTensor_squeeze__dim(Tensor& self, int64_t dim) { self = _NestedTensor_squeeze_(self, dim); return self; } Tensor NestedTensor_squeeze_dim(const Tensor& self, int64_t dim) { dim = at::maybe_wrap_dim(dim, get_dim(self)); auto self_impl = get_nested_tensor_impl(self); int64_t nested_dim = self_impl->nested_dim(); TORCH_CHECK(dim > 0, "Cannot squeeze first dimension."); TORCH_CHECK(dim >= nested_dim, "Cannot squeeze nested dimension."); TORCH_CHECK( ((self_impl->opt_sizes()[dim]) && ((*(self_impl->opt_sizes()[dim])) == 1)), "Given dimension is either undefined or not a singleton."); return map_nested_tensor( [dim, nested_dim](at::Tensor tensor) { return tensor.squeeze(dim - nested_dim); }, self); } Tensor NestedTensor_squeeze(const Tensor& self) { TORCH_CHECK(false, "squeeze(Tensor) is currently not implemented."); } Tensor NestedTensor_unsqueeze(const Tensor& self, int64_t dim) { dim = maybe_wrap_dim(dim, get_dim(self) + 1); if (dim == 0) { std::vector<TensorNode> one_node; one_node.push_back(get_nested_tensor_structure(self)); return wrap_tensor_node(TensorNode(std::move(one_node))); } std::vector<TensorNode> result_nodes; auto unbound = self.unbind(0); for (size_t i = 0; i < unbound.size(); i++) { result_nodes.push_back( get_nested_tensor_structure(at::unsqueeze(unbound[i], dim - 1))); } return wrap_tensor_node(TensorNode(std::move(result_nodes))); } Tensor NestedTensor_to_dtype_layout( const Tensor& self, c10::optional<ScalarType> dtype, c10::optional<Layout> layout, c10::optional<Device> device, c10::optional<bool> pin_memory, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { auto input_buffer = get_buffer(self); auto result_nt = wrap_buffer(input_buffer.to(dtype, layout, device, pin_memory, non_blocking, copy, c10::nullopt), get_efficient_nested_size(self), get_efficient_nested_stride(self)); if (optional_memory_format) { return NestedTensor_contiguous(result_nt, *optional_memory_format); } return result_nt; } TORCH_LIBRARY_IMPL(aten, NestedTensor, m) { nt_impl(m, "contiguous", NestedTensor_contiguous); nt_impl(m, "copy_", NestedTensor_copy_); nt_impl(m, "is_pinned", NestedTensor_is_pinned); nt_impl(m, "select.int", NestedTensor_select); nt_impl(m, "size.int", NestedTensor_size_int); nt_impl(m, "slice.Tensor", NestedTensor_slice); nt_impl(m, "squeeze", NestedTensor_squeeze); nt_impl(m, "squeeze.dim", NestedTensor_squeeze_dim); nt_impl(m, "squeeze_", NestedTensor_squeeze_); nt_impl(m, "squeeze_.dim", NestedTensor_squeeze__dim); nt_impl(m, "unbind.int", NestedTensor_unbind); nt_impl(m, "unsqueeze", NestedTensor_unsqueeze); nt_impl(m, "to.dtype_layout", NestedTensor_to_dtype_layout); } }
#include <ATen/ATen.h> #include <ATen/NamedTensorUtils.h> #include <ATen/WrapDimUtils.h> #include <ATen/core/op_registration/op_registration.h> #include <nestedtensor/csrc/nested_tensor_impl.h> #include <nestedtensor/csrc/utils/nested_node_functions.h> #include <torch/csrc/jit/runtime/operator.h> #include <torch/library.h> #include <c10/core/DispatchKey.h> #include <nestedtensor/csrc/transpose.h> namespace at { using namespace torch::nested_tensor; using namespace c10; TensorNode _unbind_tensors(TensorNode structure) { std::vector<TensorNode> result_nodes; if (structure.is_leaf()) { for (at::Tensor tensor : structure.payload().unbind()) { result_nodes.emplace_back(TensorNode(std::move(tensor))); } } else { for (TensorNode child : structure.unbind()) { result_nodes.emplace_back(_unbind_tensors(child)); } } return TensorNode(std::move(result_nodes)); } NestedTensorImpl::NestedTensorImpl(std::shared_ptr<NestedTensorStorage> storage) : TensorImpl( c10::DispatchKeySet({NestedTensorKey}), storage->dtype(), storage->device()), _storage(storage) { remove_autograd_key(); key_set_ = key_set_ - c10::DispatchKeySet({c10::DispatchKey::ADInplaceOrView}); } inline TensorNode _squeeze_nested_dim(TensorNode structure, int64_t dim) { return squeeze(structure, dim, false); } int64_t NestedTensor_size_int(const Tensor& self, int64_t dim) { std::vector<c10::optional<int64_t>> size = get_nested_tensor_impl(self)->opt_sizes(); if (size[dim]) { return *(size[dim]); } throw std::runtime_error( "NestedTensor size at dim is not Tensor shape compliant."); } int64_t nt_size(Tensor tensor, int64_t dim) { auto impl = get_nested_tensor_impl(tensor); std::vector<c10::optional<int64_t>> size = impl->opt_sizes(); if (size[dim]) { return *(size[dim]); } throw std::runtime_error( "NestedTensor size at dim is not Tensor shape compliant."); } at::Tensor wrap_tensor_node(TensorNode&& result) { if (result.is_leaf()) { return result.payload(); } PackedStorage* ls = new PackedStorage(std::move(result)); NestedTensorStorage* ls_base = dynamic_cast<NestedTensorStorage*>(ls); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ls_base)); } std::vector<at::Tensor> wrap_tensor_node(std::vector<TensorNode> input) { std::vector<at::Tensor> result; for (size_t i = 0; i < input.size(); i++) { result.push_back(wrap_tensor_node(std::move(input[i]))); } return result; } at::Tensor wrap_buffer(at::Tensor&& buffer, SizeNode nested_size) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); if (nested_size.is_leaf()) { return buffer.reshape(IntArrayRef(nested_size.payload())); } PackedStorage* ps = new PackedStorage(std::move(buffer), nested_size); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } at::Tensor wrap_buffer( at::Tensor&& buffer, EfficientSizeNode efficient_nested_size, EfficientSizeNode efficient_nested_stride) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); TORCH_CHECK( efficient_nested_size.height() > 0, "Internal error: expected nested_size of non-zero height."); TORCH_CHECK( efficient_nested_stride.height() > 0, "Internal error: expected nested_size of non-zero height."); PackedStorage* ps = new PackedStorage( std::move(buffer), efficient_nested_size, efficient_nested_stride); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } at::Tensor wrap_buffer( at::Tensor&& buffer, EfficientSizeNode efficient_nested_size) { TORCH_CHECK(buffer.is_contiguous(), "Given buffer must be contiguous."); TORCH_CHECK( efficient_nested_size.height() > 0, "Internal error: expected nested_size of non-zero height."); PackedStorage* ps = new PackedStorage( std::move(buffer), efficient_nested_size); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } Tensor NestedTensor_contiguous(const Tensor& self, MemoryFormat memory_format) { if (get_is_contiguous(self, memory_format)) { return self; } TORCH_CHECK( memory_format != MemoryFormat::Preserve, "preserve memory format is unsupported by the contiguous operator"); if (memory_format == at::MemoryFormat::Contiguous) { if (get_is_contiguous(self, c10::MemoryFormat::ChannelsLast)) { auto transposed_sizes = map_efficient_size([](int64_t* size_ptr, int64_t size) { int64_t tmp = size_ptr[0]; size_ptr[0] = size_ptr[2]; size_ptr[2] = tmp; tmp = size_ptr[0]; size_ptr[0] = size_ptr[1]; size_ptr[1] = tmp; }, get_efficient_nested_size(self)); Tensor self_transposed = wrap_buffer(get_buffer(self), transposed_sizes); return transpose_nhwc_nchw(self_transposed); } PackedStorage* ps = new PackedStorage(get_nested_tensor_structure(self)); NestedTensorStorage* ps_base = dynamic_cast<NestedTensorStorage*>(ps); return at::detail::make_tensor<NestedTensorImpl>( std::shared_ptr<NestedTensorStorage>(ps_base)); } if (memory_format == at::MemoryFormat::ChannelsLast) { Tensor self_cont = self; if (!get_is_contiguous(self, c10::MemoryFormat::Contiguous)) { self_cont = NestedTensor_contiguous(self, at::MemoryFormat::Contiguous); } TORCH_CHECK(get_dim(self_cont) == 4, "ChannelsLast memory format requires 4 dim input."); auto new_strides = map_efficient_size([](int64_t* stride_ptr, int64_t* size_ptr, int64_t size) { stride_ptr[2] = size_ptr[0]; stride_ptr[1] = stride_ptr[2] * size_ptr[2]; stride_ptr[0] = 1; }, get_efficient_nested_stride(self_cont), get_efficient_nested_size(self_cont)); self_cont = transpose_nchw_nhwc(self_cont);
}, self); } Tensor& NestedTensor_squeeze_(Tensor& self) { self = _NestedTensor_squeeze_(self, c10::nullopt); return self; } Tensor& NestedTensor_squeeze__dim(Tensor& self, int64_t dim) { self = _NestedTensor_squeeze_(self, dim); return self; } Tensor NestedTensor_squeeze_dim(const Tensor& self, int64_t dim) { dim = at::maybe_wrap_dim(dim, get_dim(self)); auto self_impl = get_nested_tensor_impl(self); int64_t nested_dim = self_impl->nested_dim(); TORCH_CHECK(dim > 0, "Cannot squeeze first dimension."); TORCH_CHECK(dim >= nested_dim, "Cannot squeeze nested dimension."); TORCH_CHECK( ((self_impl->opt_sizes()[dim]) && ((*(self_impl->opt_sizes()[dim])) == 1)), "Given dimension is either undefined or not a singleton."); return map_nested_tensor( [dim, nested_dim](at::Tensor tensor) { return tensor.squeeze(dim - nested_dim); }, self); } Tensor NestedTensor_squeeze(const Tensor& self) { TORCH_CHECK(false, "squeeze(Tensor) is currently not implemented."); } Tensor NestedTensor_unsqueeze(const Tensor& self, int64_t dim) { dim = maybe_wrap_dim(dim, get_dim(self) + 1); if (dim == 0) { std::vector<TensorNode> one_node; one_node.push_back(get_nested_tensor_structure(self)); return wrap_tensor_node(TensorNode(std::move(one_node))); } std::vector<TensorNode> result_nodes; auto unbound = self.unbind(0); for (size_t i = 0; i < unbound.size(); i++) { result_nodes.push_back( get_nested_tensor_structure(at::unsqueeze(unbound[i], dim - 1))); } return wrap_tensor_node(TensorNode(std::move(result_nodes))); } Tensor NestedTensor_to_dtype_layout( const Tensor& self, c10::optional<ScalarType> dtype, c10::optional<Layout> layout, c10::optional<Device> device, c10::optional<bool> pin_memory, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { auto input_buffer = get_buffer(self); auto result_nt = wrap_buffer(input_buffer.to(dtype, layout, device, pin_memory, non_blocking, copy, c10::nullopt), get_efficient_nested_size(self), get_efficient_nested_stride(self)); if (optional_memory_format) { return NestedTensor_contiguous(result_nt, *optional_memory_format); } return result_nt; } TORCH_LIBRARY_IMPL(aten, NestedTensor, m) { nt_impl(m, "contiguous", NestedTensor_contiguous); nt_impl(m, "copy_", NestedTensor_copy_); nt_impl(m, "is_pinned", NestedTensor_is_pinned); nt_impl(m, "select.int", NestedTensor_select); nt_impl(m, "size.int", NestedTensor_size_int); nt_impl(m, "slice.Tensor", NestedTensor_slice); nt_impl(m, "squeeze", NestedTensor_squeeze); nt_impl(m, "squeeze.dim", NestedTensor_squeeze_dim); nt_impl(m, "squeeze_", NestedTensor_squeeze_); nt_impl(m, "squeeze_.dim", NestedTensor_squeeze__dim); nt_impl(m, "unbind.int", NestedTensor_unbind); nt_impl(m, "unsqueeze", NestedTensor_unsqueeze); nt_impl(m, "to.dtype_layout", NestedTensor_to_dtype_layout); } }
return wrap_buffer(get_buffer(self_cont), get_efficient_nested_size(self), new_strides); } TORCH_CHECK(false, "Given memory format ", memory_format, " not supported by NestedTensor_contiguous."); return self; } bool NestedTensor_is_pinned(const Tensor& self, c10::optional<Device> device) { TORCH_CHECK( !device.has_value() || device->is_cuda(), "NestedTensor doesn't support non-CUDA pinned memory"); return get_nested_tensor_impl(self)->is_pinned(); } std::vector<at::Tensor> NestedTensor_unbind( const at::Tensor& self, int64_t dim) { auto _data = get_nested_tensor_impl(self); dim = at::maybe_wrap_dim(dim, get_dim(self)); auto node = _data->get_structure(); if (dim == 0) { return wrap_tensor_node(node.unbind()); } std::vector<std::vector<TensorNode>> unbound; for (auto child : node.unbind()) { std::vector<at::Tensor> tmp = at::unbind(wrap_tensor_node(std::move(child)), dim - 1); for (size_t j = 0; j < tmp.size(); j++) { if (j >= unbound.size()) { unbound.resize(j + 1); } unbound[j].push_back(TensorNode(std::move(tmp[j]))); } } std::vector<TensorNode> result; for (size_t i = 0; i < unbound.size(); i++) { result.push_back(TensorNode(std::move(unbound[i]))); } return wrap_tensor_node(result); } Tensor NestedTensor_select(const Tensor& self, int64_t dim, int64_t index) { int64_t ndim = get_dim(self); dim = maybe_wrap_dim(dim, ndim); if (dim != 0) { TORCH_CHECK_INDEX(false, "select() only supports dim == 0 for now."); } auto tmp = get_nested_tensor_structure(self).unbind()[index]; return wrap_tensor_node(std::move(tmp)); } Tensor NestedTensor_to_nested_tensor( at::Tensor input, c10::optional<int64_t> dim_) { int64_t dim = 0; if (dim_) { dim = *dim_; dim = maybe_wrap_dim(*dim_, get_dim(input) + 1); } TORCH_CHECK( dim <= get_dim(input), "target nested dimension needs to be equal or less than to input dimension"); if (is_nested_tensor_impl(input) && dim >= get_nested_dim(input)) { TensorNode unbound = _unbind_tensors(get_nested_tensor_structure(input)); for (int64_t i = 0; i < (dim - get_nested_dim(input)); i++) { unbound = _unbind_tensors(unbound); } return wrap_tensor_node(std::move(unbound)); } if (!is_nested_tensor_impl(input) && dim > 0) { std::vector<TensorNode> unbound_nodes; for (at::Tensor t : input.unbind()) { unbound_nodes.push_back(TensorNode(std::move(t))); } TensorNode unbound(std::move(unbound_nodes)); for (int64_t i = 1; i < dim; i++) { unbound = _unbind_tensors(unbound); } return wrap_tensor_node(std::move(unbound)); } return input; } Tensor NestedTensor_slice( const Tensor& self, int64_t dim, c10::optional<int64_t> start_, c10::optional<int64_t> end_, int64_t step) { int64_t start; if (start_) { start = *start_; } else { start = 0; } int64_t end; if (end_) { end = *end_; } else { end = 9223372036854775807; } int64_t ndim = get_dim(self); if (ndim == 0) { TORCH_CHECK_INDEX(false, "slice() cannot be applied to a 0-dim tensor."); } dim = maybe_wrap_dim(dim, ndim); if (dim != 0) { TORCH_CHECK_INDEX(false, "slice() only supports dim == 0 for now."); } TORCH_CHECK(step >= 1, "slice step must be positive for now."); int64_t sizes_0 = nt_size(self, 0); if (start < 0) { start += sizes_0; } if (end < 0) { end += sizes_0; } if (start < 0) { start = 0; } else if (start >= sizes_0) { start = sizes_0; } if (end < start) { end = start; } else if (end >= sizes_0) { end = sizes_0; } std::vector<at::Tensor> unbound = at::unbind(self, 0); std::vector<TensorNode> new_tensor_nodes; for (int64_t i = start; i < end; i += step) { if (is_nested_tensor_impl(unbound[i])) { new_tensor_nodes.push_back(get_nested_tensor_structure(unbound[i])); } else { new_tensor_nodes.push_back(TensorNode(std::move(unbound[i]))); } } auto result = wrap_tensor_node(TensorNode(std::move(new_tensor_nodes))); namedinference::propagate_names(result, self); return result; } Tensor& NestedTensor_copy_(Tensor& self, const Tensor& src, bool non_blocking) { apply_nested_tensor( [](at::Tensor& self, at::Tensor& source) { return self.copy_(source); }, self, src); return self; } Tensor _NestedTensor_squeeze_(Tensor self, c10::optional<int64_t> dim_) { auto self_impl = get_nested_tensor_impl(self); if (!dim_) { auto init_sizes = self_impl->opt_sizes(); for (size_t i = 0; i < init_sizes.size() - 1; i++) { int64_t index = init_sizes.size() - i - 1; c10::optional<int64_t> s = init_sizes[index]; if (s && ((*s) == 1)) { self = _NestedTensor_squeeze_(self, index); } } return self; } int64_t dim = at::maybe_wrap_dim(*dim_, get_dim(self)); TORCH_CHECK(dim > 0, "Cannot squeeze first dimension."); TORCH_CHECK( ((get_nested_tensor_impl(self)->opt_sizes()[dim]) && ((*(get_nested_tensor_impl(self)->opt_sizes()[dim])) == 1)), "Given dimension is either undefined or not a singleton."); if (dim < get_nested_tensor_impl(self)->nested_dim()) { return wrap_tensor_node( _squeeze_nested_dim(self_impl->get_structure(), dim)); } int64_t height = self_impl->get_structure().height(); return map_nested_tensor( [dim, height](at::Tensor tensor) { return tensor.squeeze(dim - height);
random
[ { "content": " int64_t height() const {\n\n return _height;\n", "file_path": "nestedtensor/csrc/storage/EfficientSizeNode.h", "rank": 0, "score": 146452.20706677216 }, { "content": " int64_t dim() const {\n\n return _sizes.dim() > 0 ? _height + _sizes.size(1) : _height;\n", "file...
C++
GDADPRG_Courseware/TextureManager.cpp
NeilDG/GDADPRG-GDPARCM_Courseware
771509ec7b3eb6d6375807819ca9da957dd22641
#include <stddef.h> #include <iostream> #include "TextureManager.h" TextureManager* TextureManager::sharedInstance = NULL; TextureManager* TextureManager::getInstance() { if (sharedInstance == NULL) { sharedInstance = new TextureManager(); } return sharedInstance; } void TextureManager::loadAll() { sf::Texture *texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0000.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0001.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0002.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0003.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0004.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0005.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0006.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0007.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0001.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0002.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0003.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0004.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0005.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0006.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0007.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0000.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0001.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0002.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0003.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0004.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0005.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0006.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0007.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0000.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0001.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0002.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0003.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0004.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0005.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0006.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0007.png"); this->textureMap[Coin].push_back(texture); } sf::Texture* TextureManager::getTextureAt(TextureManager::AssetType assetType, int index) { if (!this->textureMap[assetType].empty()) { return this->textureMap[assetType][index]; } else { cout << "No texture found for " << assetType; return NULL; } } int TextureManager::getTextureLength(TextureManager::AssetType assetType) { if (!this->textureMap[assetType].empty()) { return this->textureMap[assetType].size(); } else { cout << "No texture found for " << assetType; return 0; } } void TextureManager::testFunction() { std::cout << "Texture manager is a singleton!"; }
#include <stddef.h> #include <iostream> #include "TextureManager.h" TextureManager* TextureManager::sharedInstance = NULL; TextureManager* TextureManager::getInstance() { if (sharedInstance == NULL) { sharedInstance = new TextureManager(); } return sharedInstance; } void TextureManager::loadAll() { sf::Texture *texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0000.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0001.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0002.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0003.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0004.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0005.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0006.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bed0007.png"); this->textureMap[Bed].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0001.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0002.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0003.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0004.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0005.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0006.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/bench0007.png"); this->textureMap[Bench].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0000.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0001.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0002.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0003.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0004.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0005.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0006.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/boxGift_0007.png"); this->textureMap[Box].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0000.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0001.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0002.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0003.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0004.png"); this->textureMap[Coin].pus
sf::Texture* TextureManager::getTextureAt(TextureManager::AssetType assetType, int index) { if (!this->textureMap[assetType].empty()) { return this->textureMap[assetType][index]; } else { cout << "No texture found for " << assetType; return NULL; } } int TextureManager::getTextureLength(TextureManager::AssetType assetType) { if (!this->textureMap[assetType].empty()) { return this->textureMap[assetType].size(); } else { cout << "No texture found for " << assetType; return 0; } } void TextureManager::testFunction() { std::cout << "Texture manager is a singleton!"; }
h_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0005.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0006.png"); this->textureMap[Coin].push_back(texture); texture = new sf::Texture(); texture->loadFromFile("Media/Textures/coin0007.png"); this->textureMap[Coin].push_back(texture); }
function_block-function_prefixed
[ { "content": "class RenderTexture;\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/Texture.hpp", "rank": 0, "score": 96601.72563755105 }, { "content": " class RenderTextureImpl;\n\n}\n\n\n", "file_path": "SFML-2.5.1/include/SFML/Graphics/RenderTexture.hpp", "rank": 1, "scor...
C++
src/tests/test_fixedindexarray.cpp
P-Sc/Pirateers
440e477d33bbbcd79d291700c369f74fd0a6cc7d
#include "test_fixedindexarray.h" #include "utils/fixedindexarray.h" void Test_FixedIndexArray::test1() { currentTestCase = 1; log("Testing: add() and getSize()"); for (unsigned int i = 50; i < 150; i++) { fixArray1->add(i); fixArray2->add(i); } if (fixArray1->getSize() == 100 && fixArray2->getSize() == 100) reportSuccess(); else reportFailure(); } void Test_FixedIndexArray::test2() { currentTestCase = 2; log("Testing: erase()"); for (unsigned int i = 0; i < 500; i++) { fixArray1->add(i); fixArray2->add(i); } for (unsigned int i = 0; i < 250; i++) { fixArray1->erase(2*i); fixArray2->erase(2*i); } if (fixArray1->getSize() != 250 || fixArray2->getSize() != 250) reportFailure(); for (unsigned int i = 0; i < 50; i++) { fixArray1->add(i); fixArray2->add(i); } if (fixArray1->getSize() == 300 || fixArray2->getSize() == 300) reportSuccess(); else reportFailure(); } void Test_FixedIndexArray::test3() { currentTestCase = 3; log("Testing: get()"); for (unsigned int i = 100; i < 205; i++) { fixArray1->add(i); fixArray2->add(i); } for (unsigned int i = 0; i < 100; i++) { if (fixArray1->get(i) != i+100 || fixArray2->get(i) != i+100) { std::string message1 = "Error: Incorrect values received."; std::string message2 = "(Array1) Correct: " + std::to_string(i+100) + " - Got: " + std::to_string(fixArray1->get(i)); std::string message3 = "(Array2) Correct: " + std::to_string(i+100) + " - Got: " + std::to_string(fixArray2->get(i)); log(message1); log(message2); log(message3); reportFailure(); return; } } for (unsigned int i = 0; i < 50; i++) { fixArray1->erase(2*i); fixArray2->erase(2*i); } for (unsigned int i = 0; i < 50; i++) { if (fixArray1->get(2*i+1) != 2*i+101 || fixArray2->get(2*i+1) != 2*i+101) { std::string message1 = "Error: Incorrect values received."; std::string message2 = "(Array1) Correct: " + std::to_string(2*i+101) + " - Got: " + std::to_string(fixArray1->get(2*i+1)); std::string message3 = "(Array2) Correct: " + std::to_string(2*i+101) + " - Got: " + std::to_string(fixArray2->get(2*i+1)); log(message1); log(message2); log(message3); reportFailure(); return; } } reportSuccess(); } void Test_FixedIndexArray::test4() { currentTestCase = 4; log("Testing: getCapacity()"); if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } for (unsigned int i = 0; i < 100; i++) { fixArray1->add(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->add(i); } if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } for (unsigned int i = 0; i < 100; i++) { fixArray1->erase(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->erase(i); } for (unsigned int i = 0; i < 100; i++) { fixArray1->add(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->add(i); } if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } fixArray1->add(99); fixArray2->add(99); if (fixArray1->getCapacity() != 200 || fixArray2->getCapacity() != 6) reportFailure(); else reportSuccess(); } void Test_FixedIndexArray::startTests() { init(); test1(); cleanUp(); init(); test2(); cleanUp(); init(); test3(); cleanUp(); init(); test4(); cleanUp(); } void Test_FixedIndexArray::init() { fixArray1 = new FixedIndexArray(); fixArray2 = new FixedIndexArray(3); } void Test_FixedIndexArray::cleanUp() { delete(fixArray1); delete(fixArray2); } Test_FixedIndexArray::Test_FixedIndexArray(TestLogger * const logger) : UnitTest(logger) { unit = "FixedIndexArray"; testCaseCount = 4; }
#include "test_fixedindexarray.h" #include "utils/fixedindexarray.h" void Test_FixedIndexArray::test1() { currentTestCase = 1; log("Testing: add() and getSize()"); for (unsigned int i = 50; i < 150; i++) { fixArray1->add(i); fixArray2->add(i); } if (fixArray1->getSize() == 100 && fixArray2->getSize() == 100) reportSuccess(); else reportFailure(); } void Test_FixedIndexArray::test2() { currentTestCase = 2; log("Testing: erase()"); for (unsigned int i = 0; i < 500;
void Test_FixedIndexArray::test3() { currentTestCase = 3; log("Testing: get()"); for (unsigned int i = 100; i < 205; i++) { fixArray1->add(i); fixArray2->add(i); } for (unsigned int i = 0; i < 100; i++) { if (fixArray1->get(i) != i+100 || fixArray2->get(i) != i+100) { std::string message1 = "Error: Incorrect values received."; std::string message2 = "(Array1) Correct: " + std::to_string(i+100) + " - Got: " + std::to_string(fixArray1->get(i)); std::string message3 = "(Array2) Correct: " + std::to_string(i+100) + " - Got: " + std::to_string(fixArray2->get(i)); log(message1); log(message2); log(message3); reportFailure(); return; } } for (unsigned int i = 0; i < 50; i++) { fixArray1->erase(2*i); fixArray2->erase(2*i); } for (unsigned int i = 0; i < 50; i++) { if (fixArray1->get(2*i+1) != 2*i+101 || fixArray2->get(2*i+1) != 2*i+101) { std::string message1 = "Error: Incorrect values received."; std::string message2 = "(Array1) Correct: " + std::to_string(2*i+101) + " - Got: " + std::to_string(fixArray1->get(2*i+1)); std::string message3 = "(Array2) Correct: " + std::to_string(2*i+101) + " - Got: " + std::to_string(fixArray2->get(2*i+1)); log(message1); log(message2); log(message3); reportFailure(); return; } } reportSuccess(); } void Test_FixedIndexArray::test4() { currentTestCase = 4; log("Testing: getCapacity()"); if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } for (unsigned int i = 0; i < 100; i++) { fixArray1->add(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->add(i); } if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } for (unsigned int i = 0; i < 100; i++) { fixArray1->erase(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->erase(i); } for (unsigned int i = 0; i < 100; i++) { fixArray1->add(i); } for (unsigned int i = 0; i < 3; i++) { fixArray2->add(i); } if (fixArray1->getCapacity() != 100 || fixArray2->getCapacity() != 3) { reportFailure(); return; } fixArray1->add(99); fixArray2->add(99); if (fixArray1->getCapacity() != 200 || fixArray2->getCapacity() != 6) reportFailure(); else reportSuccess(); } void Test_FixedIndexArray::startTests() { init(); test1(); cleanUp(); init(); test2(); cleanUp(); init(); test3(); cleanUp(); init(); test4(); cleanUp(); } void Test_FixedIndexArray::init() { fixArray1 = new FixedIndexArray(); fixArray2 = new FixedIndexArray(3); } void Test_FixedIndexArray::cleanUp() { delete(fixArray1); delete(fixArray2); } Test_FixedIndexArray::Test_FixedIndexArray(TestLogger * const logger) : UnitTest(logger) { unit = "FixedIndexArray"; testCaseCount = 4; }
i++) { fixArray1->add(i); fixArray2->add(i); } for (unsigned int i = 0; i < 250; i++) { fixArray1->erase(2*i); fixArray2->erase(2*i); } if (fixArray1->getSize() != 250 || fixArray2->getSize() != 250) reportFailure(); for (unsigned int i = 0; i < 50; i++) { fixArray1->add(i); fixArray2->add(i); } if (fixArray1->getSize() == 300 || fixArray2->getSize() == 300) reportSuccess(); else reportFailure(); }
function_block-function_prefixed
[ { "content": "#include \"fixedindexarray.h\"\n\n#include <stdexcept>\n\n#include <cassert>\n\n\n\nusing std::list;\n\n\n\n/**\n\n * @brief Vergrößert das Array um stepSize (Standard: 100)\n\n */\n\nvoid FixedIndexArray::appendStepSize() {\n\n // unusedPosition anpassen\n\n for (unsigned int i = 0; i < ste...
C++
code/tool/edges-master/piotr_toolbox/matlab/private/dijkstra1.cpp
hyliang96/interpretableCNN_matlab
611e52a1aa25434ab058303c0287634767327da3
#if (_MSC_VER >= 1600) #define __STDC_UTF_16__ typedef unsigned short char16_t; #endif #include "mex.h" #include "fibheap.h" #define DIJKSTRA_CPP class HeapNode : public FibHeapNode { double N; long int IndexV; public: HeapNode() : FibHeapNode() { N = 0; }; virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); virtual void operator =(double NewKeyVal ); virtual void Print(); double GetKeyValue() { return N; }; void SetKeyValue(double n) { N = n; }; long int GetIndexValue() { return IndexV; }; void SetIndexValue( long int v) { IndexV = v; }; }; void HeapNode::Print() { FibHeapNode::Print(); mexPrintf( "%f (%d)" , N , IndexV ); } void HeapNode::operator =(double NewKeyVal) { HeapNode Tmp; Tmp.N = N = NewKeyVal; FHN_Assign(Tmp); } void HeapNode::operator =(FibHeapNode& RHS) { FHN_Assign(RHS); N = ((HeapNode&) RHS).N; } int HeapNode::operator ==(FibHeapNode& RHS) { if (FHN_Cmp(RHS)) return 0; return N == ((HeapNode&) RHS).N ? 1 : 0; } int HeapNode::operator <(FibHeapNode& RHS) { int X; if ((X=FHN_Cmp(RHS)) != 0) return X < 0 ? 1 : 0; return N < ((HeapNode&) RHS).N ? 1 : 0; }; void dijkstra1( long int n, long int s, double *D1, double *P1, double *Gpr, mwIndex *Gir, mwIndex *Gjc) { int finished; long int i, startInd, endInd, whichNeigh, nDone, closest; double closestD, arcLength, INF, SMALL, oldDist; HeapNode *A, *hnMin, hnTmp; FibHeap *heap; INF=mxGetInf(); SMALL=mxGetEps(); if ((heap = new FibHeap) == NULL || (A = new HeapNode[n+1]) == NULL ) mexErrMsgTxt( "Memory allocation failed-- ABORTING.\n" ); heap->ClearHeapOwnership(); for (i=0; i<n; i++) { if (i!=s) A[ i ] = (double) INF; else A[ i ] = (double) SMALL; if (i!=s) D1[ i ] = (double) INF; else D1[ i ] = (double) SMALL; P1[ i ] = -1; heap->Insert( &A[i] ); A[ i ].SetIndexValue( (long int) i ); } heap->Insert(&hnTmp); heap->ExtractMin(); finished = nDone = 0; while ((finished==0) && (nDone < n)) { hnMin = (HeapNode *) heap->ExtractMin(); closest = hnMin->GetIndexValue(); closestD = hnMin->GetKeyValue(); if ((closest<0) || (closest>=n)) mexErrMsgTxt( "Minimum Index out of bound..." ); D1[ closest ] = closestD; if (closestD == INF) finished=1; else { nDone++; startInd = Gjc[ closest ]; endInd = Gjc[ closest+1 ] - 1; if( startInd!=endInd+1 ) for( i=startInd; i<=endInd; i++ ) { whichNeigh = Gir[ i ]; arcLength = Gpr[ i ]; oldDist = D1[ whichNeigh ]; if ( oldDist > ( closestD + arcLength )) { D1[ whichNeigh ] = closestD + arcLength; P1[ whichNeigh ] = closest + 1; hnTmp = A[ whichNeigh ]; hnTmp.SetKeyValue( closestD + arcLength ); heap->DecreaseKey( &A[ whichNeigh ], hnTmp ); } } } } delete heap; delete[] A; } void dijkstra( long int n, long int nSrc, double *sources, double *D, double *P, const mxArray *G ) { double *Gpr = mxGetPr(G); mwIndex *Gir = mxGetIr(G); mwIndex *Gjc = mxGetJc(G); double *D1 = (double *) mxCalloc( n , sizeof( double )); double *P1 = (double *) mxCalloc( n , sizeof( double )); long int s, i, j; for( i=0; i<nSrc; i++ ) { s = (long int) *( sources + i ) - 1; if (s<0 || s > n-1) mexErrMsgTxt( "Source node(s) out of bound" ); dijkstra1( n, s, D1, P1, Gpr, Gir, Gjc ); for( j=0; j<n; j++ ) { *( D + j*nSrc + i ) = *( D1 + j ); *( P + j*nSrc + i ) = *( P1 + j ); } } } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *D, *P, *sources; long int n, mSrc, nSrc; if (nrhs != 2) mexErrMsgTxt( "Only 2 input arguments allowed." ); if (nlhs > 2) mexErrMsgTxt( "Only 2 output argument allowed." ); n = mxGetN( prhs[0] ); if (mxGetM( prhs[0] ) != n) mexErrMsgTxt( "Input matrix G needs to be square." ); sources = mxGetPr(prhs[1]); mSrc = mxGetM(prhs[1]); nSrc=mxGetN(prhs[1]); if ((mSrc==0) || (nSrc==0) || ((mSrc>1) && (nSrc>1))) mexErrMsgTxt( "Source nodes are specified in vector only" ); if(mSrc>nSrc) nSrc=mSrc; if(mxIsSparse(prhs[0])==0) mexErrMsgTxt( "Distance Matrix must be sparse" ); plhs[0] = mxCreateDoubleMatrix( nSrc, n, mxREAL ); plhs[1] = mxCreateDoubleMatrix( nSrc, n, mxREAL ); D = mxGetPr(plhs[0]); P = mxGetPr(plhs[1]) ; dijkstra( n, nSrc, sources, D, P, prhs[0] ); }
#if (_MSC_VER >= 1600) #define __STDC_UTF_16__ typedef unsigned short char16_t; #endif #include "mex.h" #include "fibheap.h" #define DIJKSTRA_CPP class HeapNode : public FibHeapNode { double N; long int IndexV; public: HeapNode() : FibHeapNode() { N = 0; }; virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); virtual void operator =(double NewKeyVal ); virtual void Print(); double GetKeyValue() { return N; }; void SetKeyValue(double n) { N = n; }; long int GetIndexValue() { return IndexV; }; void SetIndexValue( long int v) { IndexV = v; }; }; void HeapNode::Print() { FibHeapNode::Print(); mexPrintf( "%f (%d)" , N , IndexV ); } void HeapNode::operator =(double NewKeyVal) { HeapNode Tmp; Tmp.N = N = NewKeyVal; FHN_Assign(Tmp); } void HeapNode::operator =(FibHeapNode& RHS) { FHN_Assign(RHS); N = ((HeapNode&) RHS).N; } int HeapNode::operator ==(FibHeapNode& RHS) { if (FHN_Cmp(RHS)) return 0; return N == ((HeapNode&) RHS).N ? 1 : 0; } int HeapNode::operator <(FibHeapNode& RHS) { int X; if ((X=FHN_Cmp(RHS)) != 0) return X < 0 ? 1 : 0; return N < ((HeapNode&) RHS).N ? 1 : 0; };
void dijkstra( long int n, long int nSrc, double *sources, double *D, double *P, const mxArray *G ) { double *Gpr = mxGetPr(G); mwIndex *Gir = mxGetIr(G); mwIndex *Gjc = mxGetJc(G); double *D1 = (double *) mxCalloc( n , sizeof( double )); double *P1 = (double *) mxCalloc( n , sizeof( double )); long int s, i, j; for( i=0; i<nSrc; i++ ) { s = (long int) *( sources + i ) - 1; if (s<0 || s > n-1) mexErrMsgTxt( "Source node(s) out of bound" ); dijkstra1( n, s, D1, P1, Gpr, Gir, Gjc ); for( j=0; j<n; j++ ) { *( D + j*nSrc + i ) = *( D1 + j ); *( P + j*nSrc + i ) = *( P1 + j ); } } } void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *D, *P, *sources; long int n, mSrc, nSrc; if (nrhs != 2) mexErrMsgTxt( "Only 2 input arguments allowed." ); if (nlhs > 2) mexErrMsgTxt( "Only 2 output argument allowed." ); n = mxGetN( prhs[0] ); if (mxGetM( prhs[0] ) != n) mexErrMsgTxt( "Input matrix G needs to be square." ); sources = mxGetPr(prhs[1]); mSrc = mxGetM(prhs[1]); nSrc=mxGetN(prhs[1]); if ((mSrc==0) || (nSrc==0) || ((mSrc>1) && (nSrc>1))) mexErrMsgTxt( "Source nodes are specified in vector only" ); if(mSrc>nSrc) nSrc=mSrc; if(mxIsSparse(prhs[0])==0) mexErrMsgTxt( "Distance Matrix must be sparse" ); plhs[0] = mxCreateDoubleMatrix( nSrc, n, mxREAL ); plhs[1] = mxCreateDoubleMatrix( nSrc, n, mxREAL ); D = mxGetPr(plhs[0]); P = mxGetPr(plhs[1]) ; dijkstra( n, nSrc, sources, D, P, prhs[0] ); }
void dijkstra1( long int n, long int s, double *D1, double *P1, double *Gpr, mwIndex *Gir, mwIndex *Gjc) { int finished; long int i, startInd, endInd, whichNeigh, nDone, closest; double closestD, arcLength, INF, SMALL, oldDist; HeapNode *A, *hnMin, hnTmp; FibHeap *heap; INF=mxGetInf(); SMALL=mxGetEps(); if ((heap = new FibHeap) == NULL || (A = new HeapNode[n+1]) == NULL ) mexErrMsgTxt( "Memory allocation failed-- ABORTING.\n" ); heap->ClearHeapOwnership(); for (i=0; i<n; i++) { if (i!=s) A[ i ] = (double) INF; else A[ i ] = (double) SMALL; if (i!=s) D1[ i ] = (double) INF; else D1[ i ] = (double) SMALL; P1[ i ] = -1; heap->Insert( &A[i] ); A[ i ].SetIndexValue( (long int) i ); } heap->Insert(&hnTmp); heap->ExtractMin(); finished = nDone = 0; while ((finished==0) && (nDone < n)) { hnMin = (HeapNode *) heap->ExtractMin(); closest = hnMin->GetIndexValue(); closestD = hnMin->GetKeyValue(); if ((closest<0) || (closest>=n)) mexErrMsgTxt( "Minimum Index out of bound..." ); D1[ closest ] = closestD; if (closestD == INF) finished=1; else { nDone++; startInd = Gjc[ closest ]; endInd = Gjc[ closest+1 ] - 1; if( startInd!=endInd+1 ) for( i=startInd; i<=endInd; i++ ) { whichNeigh = Gir[ i ]; arcLength = Gpr[ i ]; oldDist = D1[ whichNeigh ]; if ( oldDist > ( closestD + arcLength )) { D1[ whichNeigh ] = closestD + arcLength; P1[ whichNeigh ] = closest + 1; hnTmp = A[ whichNeigh ]; hnTmp.SetKeyValue( closestD + arcLength ); heap->DecreaseKey( &A[ whichNeigh ], hnTmp ); } } } } delete heap; delete[] A; }
function_block-full_function
[ { "content": " class MexContext : public Context\n\n {\n\n public:\n\n MexContext() ;\n\n ~MexContext() ;\n\n\n\n protected:\n\n#if ENABLE_GPU\n\n vl::ErrorCode initGpu() ;\n\n vl::ErrorCode validateGpu() ;\n\n mxArray * canary ; // if it breathes, the GPU state is valid\n\n bool gpuIsInit...
C++
ios/samples/hello-ar/hello-ar/FilamentArView/FilamentApp.cpp
andykit/filament
f4f9f331c0882db6b58d1ec5ea2bb42ae9baf1d4
#include "FilamentApp.h" #include <filament/Camera.h> #include <filament/IndexBuffer.h> #include <filament/LightManager.h> #include <filament/Material.h> #include <filament/TransformManager.h> #include <filament/VertexBuffer.h> #include <filament/Viewport.h> #include <filameshio/MeshReader.h> #include <geometry/SurfaceOrientation.h> #include <ktxreader/Ktx1Reader.h> #include <sstream> #include "resources.h" using namespace filamesh; using namespace ktxreader; static constexpr float OBJECT_SCALE = 0.02f; FilamentApp::FilamentApp(void* nativeLayer, uint32_t width, uint32_t height) : nativeLayer(nativeLayer), width(width), height(height) { setupFilament(); setupCameraFeedTriangle(); setupIbl(); setupMaterial(); setupMesh(); setupView(); } void FilamentApp::render(const FilamentArFrame& frame) { app.cameraFeedTriangle->setCameraFeedTexture(frame.cameraImage); app.cameraFeedTriangle->setCameraFeedTransform(frame.cameraTextureTransform); camera->setModelMatrix(frame.view); camera->setCustomProjection(frame.projection, 0.01, 10); meshRotation *= quatf::fromAxisAngle(float3{1.0f, 0.5f, 0.2f}, 0.05); auto& tcm = engine->getTransformManager(); auto i = tcm.getInstance(app.renderable); tcm.setTransform(i, meshTransform * mat4f(meshRotation) * mat4f::scaling(OBJECT_SCALE)); if (renderer->beginFrame(swapChain)) { renderer->render(view); renderer->endFrame(); } } void FilamentApp::setObjectTransform(const mat4f& transform) { meshTransform = transform; } void FilamentApp::updatePlaneGeometry(const FilamentArPlaneGeometry& geometry) { auto& tcm = engine->getTransformManager(); if (!app.planeGeometry.isNull()) { scene->remove(app.planeGeometry); engine->destroy(app.planeGeometry); tcm.destroy(app.planeGeometry); EntityManager::get().destroy(1, &app.planeGeometry); } if (app.planeVertices) { engine->destroy(app.planeVertices); } if (app.planeIndices) { engine->destroy(app.planeIndices); } if (!app.shadowPlane) { app.shadowPlane = Material::Builder() .package(RESOURCES_SHADOW_PLANE_DATA, RESOURCES_SHADOW_PLANE_SIZE) .build(*engine); } const size_t vertexCount = geometry.vertexCount; const size_t indexCount = geometry.indexCount; quatf* quats = new quatf[vertexCount]; static float3 normals[1] = { float3(0, 1, 0) }; auto helper = geometry::SurfaceOrientation::Builder() .vertexCount(1) .normals(normals) .build(); helper->getQuats(quats, 1); delete helper; for (int i = 1; i < vertexCount; i++) { quats[i] = quats[0]; } float4* verts = (float4*) new uint8_t[vertexCount * sizeof(float4)]; uint16_t* indices = (uint16_t*) new uint8_t[indexCount * sizeof(uint16_t)]; std::copy(geometry.vertices, geometry.vertices + vertexCount, verts); std::copy(geometry.indices, geometry.indices + indexCount, indices); app.planeVertices = VertexBuffer::Builder() .vertexCount((uint32_t) vertexCount) .bufferCount(2) .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3, 0, sizeof(float4)) .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::FLOAT4, 0, sizeof(quatf)) .build(*engine); app.planeIndices = IndexBuffer::Builder() .indexCount((uint32_t) geometry.indexCount) .bufferType(IndexBuffer::IndexType::USHORT) .build(*engine); const auto deleter = [](void* buffer, size_t size, void* user) { delete (uint8_t*) buffer; }; VertexBuffer::BufferDescriptor positionBuffer(verts, vertexCount * sizeof(float4), deleter); VertexBuffer::BufferDescriptor tangentbuffer(quats, vertexCount * sizeof(quatf), deleter); IndexBuffer::BufferDescriptor indexBuffer(indices, indexCount * sizeof(uint16_t), deleter); app.planeVertices->setBufferAt(*engine, 0, std::move(positionBuffer)); app.planeVertices->setBufferAt(*engine, 1, std::move(tangentbuffer)); app.planeIndices->setBuffer(*engine, std::move(indexBuffer)); Box aabb = RenderableManager::computeAABB((float4*) geometry.vertices, (uint16_t*) geometry.indices, geometry.vertexCount); EntityManager::get().create(1, &app.planeGeometry); RenderableManager::Builder(1) .boundingBox(aabb) .receiveShadows(true) .material(0, app.shadowPlane->getDefaultInstance()) .geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.planeVertices, app.planeIndices, 0, geometry.indexCount) .build(*engine, app.planeGeometry); auto& rcm = engine->getRenderableManager(); rcm.setReceiveShadows(rcm.getInstance(app.planeGeometry), true); tcm.create(app.planeGeometry); auto i = tcm.getInstance(app.planeGeometry); tcm.setTransform(i, geometry.transform); scene->addEntity(app.planeGeometry); } FilamentApp::~FilamentApp() { delete app.cameraFeedTriangle; engine->destroy(app.materialInstance); engine->destroy(app.mat); engine->destroy(app.indirectLight); engine->destroy(app.iblTexture); engine->destroy(app.renderable); engine->destroy(app.sun); engine->destroy(app.shadowPlane); engine->destroy(renderer); engine->destroy(scene); engine->destroy(view); Entity c = camera->getEntity(); engine->destroyCameraComponent(c); EntityManager::get().destroy(c); engine->destroy(swapChain); engine->destroy(&engine); } void FilamentApp::setupFilament() { #if FILAMENT_APP_USE_OPENGL engine = Engine::create(filament::Engine::Backend::OPENGL); #elif FILAMENT_APP_USE_METAL engine = Engine::create(filament::Engine::Backend::METAL); #endif swapChain = engine->createSwapChain(nativeLayer); renderer = engine->createRenderer(); scene = engine->createScene(); Entity c = EntityManager::get().create(); camera = engine->createCamera(c); camera->setProjection(60, (float) width / height, 0.1, 10); } void FilamentApp::setupIbl() { image::Ktx1Bundle* iblBundle = new image::Ktx1Bundle(RESOURCES_VENETIAN_CROSSROADS_2K_IBL_DATA, RESOURCES_VENETIAN_CROSSROADS_2K_IBL_SIZE); float3 harmonics[9]; iblBundle->getSphericalHarmonics(harmonics); app.iblTexture = Ktx1Reader::createTexture(engine, iblBundle, false); app.indirectLight = IndirectLight::Builder() .reflections(app.iblTexture) .irradiance(3, harmonics) .intensity(30000) .build(*engine); scene->setIndirectLight(app.indirectLight); app.sun = EntityManager::get().create(); LightManager::Builder(LightManager::Type::SUN) .castShadows(true) .direction({0.0, -1.0, 0.0}) .build(*engine, app.sun); scene->addEntity(app.sun); } void FilamentApp::setupMaterial() { app.mat = Material::Builder() .package(RESOURCES_CLEAR_COAT_DATA, RESOURCES_CLEAR_COAT_SIZE) .build(*engine); app.materialInstance = app.mat->createInstance(); } void FilamentApp::setupMesh() { MeshReader::Mesh mesh = MeshReader::loadMeshFromBuffer(engine, RESOURCES_CUBE_DATA, nullptr, nullptr, app.materialInstance); app.materialInstance->setParameter("baseColor", RgbType::sRGB, {0.71f, 0.0f, 0.0f}); app.renderable = mesh.renderable; scene->addEntity(app.renderable); auto& rcm = engine->getRenderableManager(); rcm.setCastShadows(rcm.getInstance(app.renderable), true); auto& tcm = engine->getTransformManager(); tcm.create(app.renderable); auto i = tcm.getInstance(app.renderable); tcm.setTransform(i, mat4f::translation(float3{0.0f, 0.0f, -2.0f}) * mat4f::scaling(OBJECT_SCALE)); } void FilamentApp::setupView() { view = engine->createView(); view->setScene(scene); view->setCamera(camera); view->setViewport(Viewport(0, 0, width, height)); } void FilamentApp::setupCameraFeedTriangle() { app.cameraFeedTriangle = new FullScreenTriangle(engine); scene->addEntity(app.cameraFeedTriangle->getEntity()); }
#include "FilamentApp.h" #include <filament/Camera.h> #include <filament/IndexBuffer.h> #include <filament/LightManager.h> #include <filament/Material.h> #include <filament/TransformManager.h> #include <filament/VertexBuffer.h> #include <filament/Viewport.h> #include <filameshio/MeshReader.h> #include <geometry/SurfaceOrientation.h> #include <ktxreader/Ktx1Reader.h> #include <sstream> #include "resources.h" using namespace filamesh; using namespace ktxreader; static constexpr float OBJECT_SCALE = 0.02f; FilamentApp::FilamentApp(void* nativeLayer, uint32_t width, uint32_t height) : nativeLayer(nativeLayer), width(width), height(height) { setupFilament(); setupCameraFeedTriangle(); setupIbl(); setupMaterial(); setupMesh(); setupView(); } void FilamentApp::render(const FilamentArFrame& frame) { app.cameraFeedTriangle->setCameraFeedTexture(frame.cameraImage); app.cameraFeedTriangle->setCameraFeedTransform(frame.cameraTextureTransform); camera->setModelMatrix(frame.view); camera->setCustomProjection(frame.projection, 0.01, 10); meshRotation *= quatf::fromAxisAngle(float3{1.0f, 0.5f, 0.2f}, 0.05); auto& tcm = engine->getTransformManager(); auto i = tcm.getInstance(app.renderable); tcm.setTransform(i, meshTransform * mat4f(meshRotation) * mat4f::scaling(OBJECT_SCALE)); if (renderer->beginFrame(swapChain)) { renderer->render(view); renderer->endFrame(); } } void FilamentApp::setObjectTransform(const mat4f& transform) { meshTransform = transform; } void FilamentApp::updatePlaneGeometry(const FilamentArPlaneGeometry& geometry) { auto& tcm = engine->getTransformManager(); if (!app.planeGeometry.isNull()) { scene->remove(app.planeGeometry); engine->destroy(app.planeGeometry); tcm.destroy(app.planeGeometry); EntityManager::get().destroy(1, &app.planeGeometry); } if (app.planeVertices) { engine->destroy(app.planeVertices); } if (app.planeIndices) { engine->destroy(app.planeIndices); } if (!app.shadowPlane) { app.shadowPlane = Material::Builder() .package(RESOURCES_SHADOW_PLANE_DATA, RESOURCES_SHADOW_PLANE_SIZE) .build(*engine); } const size_t vertexCount = geometry.vertexCount; const size_t indexCount = geometry.indexCount; quatf* quats = new quatf[vertexCount]; static float3 normals[1] = { float3(0, 1, 0) }; auto helper = geometry::SurfaceOrientation::Builder() .vertexCount(1) .normals(normals) .build(); helper->getQuats(quats, 1); delete helper; for (int i = 1; i < vertexCount; i++) { quats[i] = quats[0]; } float4* verts = (float4*) new uint8_t[vertexCount * sizeof(float4)]; uint16_t* indices = (uint16_t*) new uint8_t[indexCount * sizeof(uint16_t)]; std::copy(geometry.vertices, geometry.vertices + vertexCount, verts); std::copy(geometry.indices, geometry.indices + indexCount, indices); app.planeVertices = VertexBuffer::Builder() .vertexCount((uint32_t) vertexCount) .bufferCount(2) .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3, 0, sizeof(float4)) .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::FLOAT4, 0, sizeof(quatf)) .build(*engine); app.planeIndices = IndexBuffer::Builder() .indexCount((uint32_t) geometry.indexCount) .bufferType(IndexBuffer::IndexType::USHORT) .build(*engine); const auto deleter = [](void* buffer, size_t size, void* user) { delete (uint8_t*) buffer; }; VertexBuffer::BufferDescriptor positionBuffer(verts, vertexCount * sizeof(float4), deleter); VertexBuffer::BufferDescriptor tangentbuffer(quats, vertexCount * sizeof(quatf), deleter); IndexBuffer::BufferDescriptor indexBuffer(indices, indexCount * sizeof(uint16_t), deleter); app.planeVertices->setBufferAt(*engine, 0, std::move(positionBuffer)); app.planeVertices->setBufferAt(*engine, 1, std::move(tangentbuffer)); app.planeIndices->setBuffer(*engine, std::move(indexBuffer)); Box aabb = RenderableManager::computeAABB((float4*) geometry.vertices, (uint16_t*) geometry.indices, geometry.vertexCount); EntityManager::get().create(1, &app.planeGeometry); RenderableManager::Builder(1) .boundingBox(aabb) .receiveShadows(true) .material(0, app.shadowPlane->getDefaultInstance()) .geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.planeVertices, app.planeIndices, 0, geometry.indexCount) .build(*engine, app.planeGeometry); auto& rcm = engine->getRenderableManager(); rcm.setReceiveShadows(rcm.getInstance(app.planeGeometry), true); tcm.create(app.planeGeometry); auto i = tcm.getInstance(app.planeGeometry); tcm.setTransform(i, geometry.transform); scene->addEntity(app.planeGeometry); } FilamentApp::~FilamentApp() { delete app.cameraFeedTriangle; engine->destroy(app.materialInstance); engine->destroy(app.mat); engine->destroy(app.indirectLight); engine->destroy(app.iblTexture); engine->destroy(app.renderable); engine->destroy(app.sun); engine->destroy(app.shadowPlane); engine->destroy(renderer); engine->destroy(scene); engine->destroy(view); Entity c = camera->getEntity(); engine->destroyCameraComponent(c); EntityManager::get().destroy(c); engine->destroy(swapChain); engine->destroy(&engine); } void FilamentApp::setupFilament() { #if FILAMENT_APP_USE_OPENGL engine = Engine::create(filament::Engine::Backend::OPENGL); #elif FILAMENT_APP_USE_METAL engine = Engine::create(filament::Engine::Backend::METAL); #endif swapChain = engine->createSwapChain(nativeLayer); renderer = engine->createRenderer(); scene = engine->createScene(); Entity c = EntityManager::get().create(); camera = engine->createCamera(c); camera->setProjection(60, (float) width / height, 0.1, 10); } void FilamentApp::setupIbl() { image::Ktx1Bundle* iblBundle = new image::Ktx1Bundle(RESOURCES_VENETIAN_CROSSROADS_2K_IBL_DATA, RESOURCES_VENETIAN_CROSSROADS_2K_IBL_SIZE); float3 harmonics[9]; iblBundle->getSphericalHarmonics(harmonics); app.iblTexture = Ktx1Reader::createTexture(engine, iblBundle, false); app.indirectLight = IndirectLight::Builder() .reflections(app.iblTexture) .irradiance(3, harmonics) .intensity(30000) .build(*engine); scene->setIndirectLight(app.indirectLight); app.sun = EntityManager::get().create(); LightManager::Builder(LightManager::Type::SUN) .castShadows(true) .direction({0.0, -1.0, 0.0}) .build(*engine, app.sun); scene->addEntity(app.sun); }
void FilamentApp::setupMesh() { MeshReader::Mesh mesh = MeshReader::loadMeshFromBuffer(engine, RESOURCES_CUBE_DATA, nullptr, nullptr, app.materialInstance); app.materialInstance->setParameter("baseColor", RgbType::sRGB, {0.71f, 0.0f, 0.0f}); app.renderable = mesh.renderable; scene->addEntity(app.renderable); auto& rcm = engine->getRenderableManager(); rcm.setCastShadows(rcm.getInstance(app.renderable), true); auto& tcm = engine->getTransformManager(); tcm.create(app.renderable); auto i = tcm.getInstance(app.renderable); tcm.setTransform(i, mat4f::translation(float3{0.0f, 0.0f, -2.0f}) * mat4f::scaling(OBJECT_SCALE)); } void FilamentApp::setupView() { view = engine->createView(); view->setScene(scene); view->setCamera(camera); view->setViewport(Viewport(0, 0, width, height)); } void FilamentApp::setupCameraFeedTriangle() { app.cameraFeedTriangle = new FullScreenTriangle(engine); scene->addEntity(app.cameraFeedTriangle->getEntity()); }
void FilamentApp::setupMaterial() { app.mat = Material::Builder() .package(RESOURCES_CLEAR_COAT_DATA, RESOURCES_CLEAR_COAT_SIZE) .build(*engine); app.materialInstance = app.mat->createInstance(); }
function_block-full_function
[]
C++
ReactNativeFrontend/ios/Pods/boost/boost/contract/detail/decl.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
#ifndef BOOST_CONTRACT_DETAIL_DECL_HPP_ #define BOOST_CONTRACT_DETAIL_DECL_HPP_ #include <boost/contract/detail/tvariadic.hpp> #if !BOOST_CONTRACT_DETAIL_TVARIADIC #include <boost/contract/core/config.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/preprocessor/tuple/elem.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #endif #include <boost/preprocessor/control/expr_iif.hpp> #include <boost/preprocessor/control/iif.hpp> #include <boost/preprocessor/punctuation/comma_if.hpp> #define BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ arity, is_friend, has_result, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ template< \ class O \ BOOST_PP_COMMA_IF(has_result) \ BOOST_PP_EXPR_IIF(has_result, typename VR) \ , typename F \ , class C \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(arity) \ BOOST_CONTRACT_DETAIL_TVARIADIC_TPARAMS_Z(z, arity, Args) \ > \ BOOST_PP_EXPR_IIF(is_friend, friend) \ boost::contract::specify_precondition_old_postcondition_except< \ BOOST_PP_EXPR_IIF(has_result, VR)> \ \ public_function( \ boost::contract::virtual_* v \ BOOST_PP_COMMA_IF(has_result) \ BOOST_PP_EXPR_IIF(has_result, VR& r) \ , F f \ , C* obj \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(arity) \ BOOST_CONTRACT_DETAIL_TVARIADIC_FPARAMS_Z(z, arity, Args, &, args) \ ) #if BOOST_CONTRACT_DETAIL_TVARIADIC #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTIONS_Z(z, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ ~, 1, 0, \ O, VR, F, C, Args, v, r, f, obj, args \ ); \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ ~, 1, 1, \ O, VR, F, C, Args, v, r, f, obj, args \ ); #else #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_( \ z, n, result_O_R_F_C_Args_v_r_f_obj_args) \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ n, \ 1, \ BOOST_PP_TUPLE_ELEM(11, 0, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 1, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 2, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 3, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 4, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 5, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 6, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 7, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 8, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 9, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 10, result_O_R_F_C_Args_v_r_f_obj_args) \ ); #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTIONS_Z(z, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ BOOST_PP_REPEAT_ ## z( \ BOOST_PP_INC(BOOST_CONTRACT_MAX_ARGS), \ BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_, \ ( 0, O, VR, F, C, Args, v, r, f, obj, args) \ ) \ BOOST_PP_REPEAT_ ## z( \ BOOST_PP_INC(BOOST_CONTRACT_MAX_ARGS), \ BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_, \ ( 1, O, VR, F, C, Args, v, r, f, obj, args) \ ) #endif #define BOOST_CONTRACT_DETAIL_DECL_DETAIL_COND_SUBCONTRACTING_Z( \ z, is_friend, O, VR, F, C, Args) \ template< \ class O, typename VR, typename F, class C \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(BOOST_CONTRACT_MAX_ARGS) \ BOOST_CONTRACT_DETAIL_TVARIADIC_TPARAMS_Z(z, \ BOOST_CONTRACT_MAX_ARGS, Args) \ > \ BOOST_PP_IIF(is_friend, \ friend class boost::contract::detail:: \ , \ class \ ) \ cond_subcontracting namespace boost { namespace contract { class virtual_; template<typename VR = void> class specify_precondition_old_postcondition_except; } } #endif
#ifndef BOOST_CONTRACT_DETAIL_DECL_HPP_ #define BOOST_CONTRACT_DETAIL_DECL_HPP_ #include <boost/contract/detail/tvariadic.hpp> #if !BOOST_CONTRACT_DETAIL_TVARIADIC #include <boost/contract/core/config.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/preprocessor/tuple/elem.hpp> #include <boost/preprocessor/arithmetic/inc.hpp> #endif #include <boost/preprocessor/control/expr_iif.hpp> #include <boost/preprocessor/control/iif.hpp> #include <boost/preprocessor/punctuation/comma_if.hpp> #define BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ arity, is_friend, has_result, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ template< \ class O \ BOOST_PP_COMMA_IF(has_result) \ BOOST_PP_EXPR_IIF(has_result, typename VR) \ , typename F \ , class C \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(arity) \ BOOST_CONTRACT_DETAIL_TVARIADIC_TPARAMS_Z(z, arity, Args) \ > \ BOOST_PP_EXPR_IIF(is_friend, friend) \ boost::contract::specify_precondition_old_postcondition_except< \ BOOST_PP_EXPR_IIF(has_result, VR)> \ \ public_function( \ boost::contract::virtual_* v \ BOOST_PP_COMMA_IF(has_result) \ BOOST_PP_EXPR_IIF(has_result, VR& r) \ , F f \ , C* obj \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(arity) \ BOOST_CONTRACT_DETAIL_TVARIADIC_FPARAMS_Z(z, arity, Args, &, args) \ ) #if BOOST_CONTRACT_DETAIL_TVARIADIC #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTIONS_Z(z, \ O, VR, F, C, Args, \ v, r, f, obj, args \ ) \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ ~, 1, 0, \ O, VR, F, C, Args, v, r, f, obj, args \ ); \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ ~, 1, 1, \ O, VR, F, C, Args, v, r, f, obj, args \ ); #else #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_( \ z, n, result_O_R_F_C_Args_v_r_f_obj_args) \ BOOST_CONTRACT_DETAIL_DECL_OVERRIDING_PUBLIC_FUNCTION_Z(z, \ n, \ 1, \ BOOST_PP_TUPLE_ELEM(11, 0, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 1, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 2, res
\ BOOST_PP_REPEAT_ ## z( \ BOOST_PP_INC(BOOST_CONTRACT_MAX_ARGS), \ BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_, \ ( 0, O, VR, F, C, Args, v, r, f, obj, args) \ ) \ BOOST_PP_REPEAT_ ## z( \ BOOST_PP_INC(BOOST_CONTRACT_MAX_ARGS), \ BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTION_, \ ( 1, O, VR, F, C, Args, v, r, f, obj, args) \ ) #endif #define BOOST_CONTRACT_DETAIL_DECL_DETAIL_COND_SUBCONTRACTING_Z( \ z, is_friend, O, VR, F, C, Args) \ template< \ class O, typename VR, typename F, class C \ BOOST_CONTRACT_DETAIL_TVARIADIC_COMMA(BOOST_CONTRACT_MAX_ARGS) \ BOOST_CONTRACT_DETAIL_TVARIADIC_TPARAMS_Z(z, \ BOOST_CONTRACT_MAX_ARGS, Args) \ > \ BOOST_PP_IIF(is_friend, \ friend class boost::contract::detail:: \ , \ class \ ) \ cond_subcontracting namespace boost { namespace contract { class virtual_; template<typename VR = void> class specify_precondition_old_postcondition_except; } } #endif
ult_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 3, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 4, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 5, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 6, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 7, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 8, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 9, result_O_R_F_C_Args_v_r_f_obj_args), \ BOOST_PP_TUPLE_ELEM(11, 10, result_O_R_F_C_Args_v_r_f_obj_args) \ ); #define BOOST_CONTRACT_DETAIL_DECL_FRIEND_OVERRIDING_PUBLIC_FUNCTIONS_Z(z, \ O, VR, F, C, Args, \ v, r, f, obj, args \ )
random
[]
C++
sdk/rms_sdk/Platform/Http/HttpClientQt.cpp
AzureAD/rms-sdk-for-cpp
0e5d54a030008c5c0f70d8d3d0695fa0722b6ab6
#ifdef QTFRAMEWORK #include "HttpClientQt.h" #include <QThread> #include <QMutex> #include <QEventLoop> #include <QCoreApplication> #include <QTimer> #include <QNetworkProxyFactory> #include "../Logger/Logger.h" #include "../../ModernAPI/RMSExceptions.h" #include "mscertificates.h" #include "HttpClientQt.h" using namespace std; using namespace rmscore::platform::logger; namespace rmscore { namespace platform { namespace http { common::ByteArray ReadAllBytes(QIODevice *from) { common::ByteArray result; auto bytesAvailable = from->bytesAvailable(); if (bytesAvailable > 0) { result.resize(static_cast<size_t>(bytesAvailable)); char *buf = reinterpret_cast<char *>(&result[0]); size_t offset = 0; while (bytesAvailable > 0) { auto read = from->read(&buf[offset], bytesAvailable); if (read <= 0) break; bytesAvailable -= read; offset += read; } } return result; } shared_ptr<IHttpClient> doCreate() { static bool initialized = false; if (!initialized) { QSslConfiguration SslConfiguration(QSslConfiguration::defaultConfiguration()); QList<QSslCertificate> certificates = SslConfiguration.caCertificates(); certificates.append(QSslCertificate::fromData(MicrosoftCertCA)); certificates.append(QSslCertificate::fromData(MicrosoftCertSubCA)); SslConfiguration.setCaCertificates(certificates); QSslConfiguration::setDefaultConfiguration(SslConfiguration); initialized = true; } return make_shared<HttpClientQt>(); } shared_ptr<IHttpClient> IHttpClient::Create() { if(!QCoreApplication::instance()) { int argc = 1; char name[] = "IHttpClient::Create"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doCreate(); } return doCreate(); } HttpClientQt::HttpClientQt() : lastReply_(nullptr) { this->request_.setSslConfiguration(QSslConfiguration::defaultConfiguration()); QNetworkProxyFactory::setUseSystemConfiguration(true); } HttpClientQt::~HttpClientQt() {} void HttpClientQt::AddAuthorizationHeader(const string& authToken) { this->AddHeader("Authorization", authToken); } void HttpClientQt::AddAcceptMediaTypeHeader(const string& mediaType) { this->AddHeader("Accept", mediaType); } void HttpClientQt::AddAcceptLanguageHeader(const string& language) { this->AddHeader("Accept-Language", language); } void HttpClientQt::AddHeader(const string& headerName, const string& headerValue) { this->request_.setRawHeader(headerName.c_str(), headerValue.c_str()); } StatusCode HttpClientQt::doPost(const string& url, const common::ByteArray& request, const string& mediaType, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { Logger::Info("==> PostWithCoreAppContext %s", url.data()); this->request_.setUrl(QUrl(url.c_str())); this->AddAcceptMediaTypeHeader(mediaType); Logger::Hidden("==> Request Headers:"); foreach(const QByteArray &hdrName, this->request_.rawHeaderList()) { QByteArray hdrValue = this->request_.rawHeader(hdrName); Logger::Hidden("%s : %s", hdrName.data(), hdrValue.data()); } std::string req(request.begin(), request.end()); Logger::Hidden("==> Request Body: %s", req.c_str()); lastReply_ = this->manager_.post( this->request_, QByteArray(reinterpret_cast<const char *>(request.data()), static_cast<int>(request.size()))); QTimer timer; QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(lastReply_, &QNetworkReply::sslErrors, [ = ](QList<QSslError>errorList) { for (auto& error : errorList) { Logger::Error("QSslError: %s", error.errorString().toStdString().c_str()); throw exceptions::RMSNetworkException( error.errorString().toStdString(), exceptions::RMSNetworkException::ServerError); } }); do { timer.start(500); loop.exec(); if ((cancelState != nullptr) && cancelState->load()) { throw exceptions::RMSNetworkException( "Network operation was cancelled by user", exceptions::RMSNetworkException::CancelledByUser); } } while (!timer.isActive() || !lastReply_->isFinished()); QVariant statusCode = lastReply_->attribute( QNetworkRequest::HttpStatusCodeAttribute); Logger::Info("Response StatusCode: %i", statusCode.toInt()); Logger::Hidden("--> Response Headers:"); foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) { Logger::Hidden("%s : %s", pair.first.data(), pair.second.data()); } response = ReadAllBytes(lastReply_); Logger::Hidden("--> Response Body:"); Logger::Hidden(string(response.begin(), response.end())); QNetworkReply::NetworkError error_type = lastReply_->error(); if (error_type != QNetworkReply::NoError) { Logger::Error(QString("error: %1").arg( lastReply_->errorString()).toStdString()); } return StatusCode(statusCode.toInt()); } StatusCode HttpClientQt::Post(const string& url, const common::ByteArray& request, const string& mediaType, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { if (!QCoreApplication::instance()) { int argc = 1; char name[] = "HttpClientQt::Post"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doPost(url, request, mediaType, response, cancelState); } return doPost(url, request, mediaType, response, cancelState); } StatusCode HttpClientQt::doGet(const string& url, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { Logger::Info("==> GetWithCoreAppContext %s", url.data()); this->request_.setUrl(QUrl(url.c_str())); Logger::Hidden("==> Request headers:"); foreach(const QByteArray &hdrName, this->request_.rawHeaderList()) { QByteArray hdrValue = this->request_.rawHeader(hdrName); Logger::Hidden("%s : %s", hdrName.data(), hdrValue.data()); } lastReply_ = this->manager_.get(this->request_); QTimer timer; QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(lastReply_, &QNetworkReply::sslErrors, [ = ](QList<QSslError>errorList) { for (auto& error : errorList) { Logger::Error("QSslError: %s", error.errorString().toStdString().c_str()); throw exceptions::RMSNetworkException( error.errorString().toStdString(), exceptions::RMSNetworkException::ServerError); } }); do { timer.start(500); loop.exec(); if ((cancelState != nullptr) && cancelState->load()) { throw exceptions::RMSNetworkException( "Network operation was cancelled by user", exceptions::RMSNetworkException::CancelledByUser); } } while (!timer.isActive() || !lastReply_->isFinished()); QVariant statusCode = lastReply_->attribute( QNetworkRequest::HttpStatusCodeAttribute); Logger::Info("Response StatusCode: %i", statusCode.toInt()); Logger::Hidden("--> Response Headers:"); foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) { Logger::Hidden("%s : %s", pair.first.data(), pair.second.data()); } response = ReadAllBytes(lastReply_); Logger::Hidden("--> Response Body:"); Logger::Hidden(string(response.begin(), response.end())); QNetworkReply::NetworkError error_type = lastReply_->error(); if (error_type != QNetworkReply::NoError) { Logger::Error(QString("error: %1").arg( lastReply_->errorString()).toStdString()); } return StatusCode(statusCode.toInt()); } StatusCode HttpClientQt::Get(const string& url, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { if (!QCoreApplication::instance()) { int argc = 1; char name[] = "HttpClientQt::Get"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doGet(url, response, cancelState); } return doGet(url, response, cancelState); } const string HttpClientQt::GetResponseHeader(const string& headerName) { return string(lastReply_->rawHeader(headerName.c_str()).data()); } void HttpClientQt::SetAllowUI(bool ) { throw exceptions::RMSNotFoundException("Not implemented"); } } } } #endif
#ifdef QTFRAMEWORK #include "HttpClientQt.h" #include <QThread> #include <QMutex> #include <QEventLoop> #include <QCoreApplication> #include <QTimer> #include <QNetworkProxyFactory> #include "../Logger/Logger.h" #include "../../ModernAPI/RMSExceptions.h" #include "mscertificates.h" #include "HttpClientQt.h" using namespace std; using namespace rmscore::platform::logger; namespace rmscore { namespace platform { namespace http { common::ByteArray ReadAllBytes(QIODevice *from) { common::ByteArray result; auto bytesAvailable = from->bytesAvailable(); if (bytesAvailable > 0) { result.resize(static_cast<size_t>(bytesAvailable)); char *buf = reinterpret_cast<char *>(&result[0]); size_t offset = 0; while (bytesAvailable > 0) { auto read = from->read(&buf[offset], bytesAvailable); if (read <= 0) break; bytesAvailable -= read; offset += read; } } return result; } shared_ptr<IHttpClient> doCreate() { static bool initialized = false; if (!initialized) { QSslConfiguration SslConfiguration(QSslConfiguration::defaultConfiguration()); QList<QSslCertificate> certificates = SslConfiguration.caCertificates(); certificates.append(QSslCertificate::fromData(MicrosoftCertCA)); certificates.append(QSslCertificate::fromData(MicrosoftCertSubCA)); SslConfiguration.setCaCertificates(certificates); QSslConfiguration::setDefaultConfiguration(SslConfiguration); initialized = true; } return make_shared<HttpClientQt>(); } shared_ptr<IHttpClient> IHttpClient::Create() { if(!QCoreApplication::instance()) { int argc = 1; char name[] = "IHttpClient::Create"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doCreate(); } return doCreate(); } HttpClientQt::HttpClientQt() : lastReply_(nullptr) { this->request_.setSslConfiguration(QSslConfiguration::defaultConfiguration()); QNetworkProxyFactory::setUseSystemConfiguration(true); } HttpClientQt::~HttpClientQt() {} void HttpClientQt::AddAuthorizationHeader(const string& authToken) { this->AddHeader("Authorization", authToken); } void HttpClientQt::AddAcceptMediaTypeHeader(const string& mediaType) { this->AddHeader("Accept", mediaType); } void HttpClientQt::AddAcceptLanguageHeader(const string& language) { this->AddHeader("Accept-Language", language); } void HttpClientQt::AddHeader(const string& headerName, const string& headerValue) { this->request_.setRawHeader(headerName.c_str(), headerValue.c_str()); } StatusCode HttpClientQt::doPost(const string& url, const common::ByteArray& request, const string& mediaType, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { Logger::Info("==> PostWithCoreAppContext %s", url.data()); this->request_.setUrl(QUrl(url.c_str())); this->AddAcceptMediaTypeHeader(mediaType); Logger::Hidden("==> Request Headers:"); foreach(const QByteArray &hdrName, this->request_.rawHeaderList()) { QByteArray hdrValue = this->request_.rawHeader(hdrName); Logger::Hidden("%s : %s", hdrName.data(), hdrValue.data()); } std::string req(request.begin(), request.end()); Logger::Hidden("==> Request Body: %s", req.c_str()); lastReply_ = this->manager_.post( this->request_, QByteArray(reinterpret_cast<const char *>(request.data()), static_cast<int>(request.size()))); QTimer timer; QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit())); QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(lastReply_, &QNetworkReply::sslErrors, [ = ](QList<QSslError>errorList) { for (auto& error : errorList) { Logger::Error("QSslError: %s", error.errorString().toStdString().c_str()); throw exceptions::RMSNetworkException( error.errorString().toStdString(), exceptions::RMSNetworkException::ServerError); } }); do { timer.start(500); loop.exec(); if ((cancelState != nullptr) && cancelState->load()) { throw exceptions::RMSNetworkException( "Network operation was cancelled by user", exceptions::RMSNetworkException::CancelledByUser); } } while (!timer.isActive() || !lastReply_->isFinished()); QVariant statusCode = lastReply_->attribute( QNetworkRequest::HttpStatusCodeAttribute); Logger::Info("Response StatusCode: %i", statusCode.toInt()); Logger::Hidden("--> Response Headers:"); foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) { Logger::Hidden("%s : %s", pair.first.data(), pair.second.data()); } response = ReadAllBytes(lastReply_); Logger::Hidden("--> Response Body:"); Logger::Hidden(string(response.begin(), response.end())); QNetworkReply::NetworkError error_type = lastReply_->error(); if (error_type != QNetworkReply::NoError) { Logger::Error(QString("error: %1").arg( lastReply_->errorString()).toStdString()); } return StatusCode(statusCode.toInt()); } StatusCode HttpClientQt::Post(const string& url, const common::ByteArray& request, const string& mediaType, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { if (!QCoreApplication::instance()) { int argc = 1; char name[] = "HttpClientQt::Post"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doPost(url, request, mediaType, response, cancelState); } return doPost(url, request, mediaType, response, cancelState); } StatusCode HttpClientQt::doGet(const string& url, common::ByteArray& response, std::
)); QObject::connect(lastReply_, SIGNAL(finished()), &loop, SLOT(quit())); QObject::connect(lastReply_, &QNetworkReply::sslErrors, [ = ](QList<QSslError>errorList) { for (auto& error : errorList) { Logger::Error("QSslError: %s", error.errorString().toStdString().c_str()); throw exceptions::RMSNetworkException( error.errorString().toStdString(), exceptions::RMSNetworkException::ServerError); } }); do { timer.start(500); loop.exec(); if ((cancelState != nullptr) && cancelState->load()) { throw exceptions::RMSNetworkException( "Network operation was cancelled by user", exceptions::RMSNetworkException::CancelledByUser); } } while (!timer.isActive() || !lastReply_->isFinished()); QVariant statusCode = lastReply_->attribute( QNetworkRequest::HttpStatusCodeAttribute); Logger::Info("Response StatusCode: %i", statusCode.toInt()); Logger::Hidden("--> Response Headers:"); foreach(const QNetworkReply::RawHeaderPair & pair, lastReply_->rawHeaderPairs()) { Logger::Hidden("%s : %s", pair.first.data(), pair.second.data()); } response = ReadAllBytes(lastReply_); Logger::Hidden("--> Response Body:"); Logger::Hidden(string(response.begin(), response.end())); QNetworkReply::NetworkError error_type = lastReply_->error(); if (error_type != QNetworkReply::NoError) { Logger::Error(QString("error: %1").arg( lastReply_->errorString()).toStdString()); } return StatusCode(statusCode.toInt()); } StatusCode HttpClientQt::Get(const string& url, common::ByteArray& response, std::shared_ptr<std::atomic<bool> >cancelState) { if (!QCoreApplication::instance()) { int argc = 1; char name[] = "HttpClientQt::Get"; char* argv = &name[0]; QCoreApplication a(argc, &argv); return doGet(url, response, cancelState); } return doGet(url, response, cancelState); } const string HttpClientQt::GetResponseHeader(const string& headerName) { return string(lastReply_->rawHeader(headerName.c_str()).data()); } void HttpClientQt::SetAllowUI(bool ) { throw exceptions::RMSNotFoundException("Not implemented"); } } } } #endif
shared_ptr<std::atomic<bool> >cancelState) { Logger::Info("==> GetWithCoreAppContext %s", url.data()); this->request_.setUrl(QUrl(url.c_str())); Logger::Hidden("==> Request headers:"); foreach(const QByteArray &hdrName, this->request_.rawHeaderList()) { QByteArray hdrValue = this->request_.rawHeader(hdrName); Logger::Hidden("%s : %s", hdrName.data(), hdrValue.data()); } lastReply_ = this->manager_.get(this->request_); QTimer timer; QEventLoop loop; QObject::connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()
random
[ { "content": "namespace rmscore { namespace restclients {\n\n\n\nvoid HandleRestClientError(platform::http::StatusCode httpStatusCode, rmscore::common::ByteArray &sResponse);\n\n\n\n} // namespace restclients\n", "file_path": "sdk/rms_sdk/RestClients/RestClientErrorHandling.h", "rank": 0, "score": 1...
C++
rocsolver/clients/gtest/getri_gtest.cpp
eidenyoshida/rocSOLVER
1240759207b63f8aeba51db259873141c72f9735
#include "testing_getri.hpp" using ::testing::Combine; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using namespace std; typedef vector<int> getri_tuple; const vector<vector<int>> matrix_size_range = { {0, 1}, {-1, 1}, {20, 5}, {32, 32}, {50, 50}, {70, 100}, {100, 150} }; const vector<vector<int>> large_matrix_size_range = { {192, 192}, {500, 600}, {640, 640}, {1000, 1024}, {1200, 1230} }; Arguments getri_setup_arguments(getri_tuple tup) { Arguments arg; arg.N = tup[0]; arg.lda = tup[1]; arg.timing = 0; arg.bsp = arg.N; arg.bsa = arg.lda * arg.N; return arg; } class GETRI : public ::TestWithParam<getri_tuple> { protected: GETRI() {} virtual void SetUp() {} virtual void TearDown() {} }; TEST_P(GETRI, __float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,float>(); arg.batch_count = 1; testing_getri<false,false,float>(arg); } TEST_P(GETRI, __double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,double>(); arg.batch_count = 1; testing_getri<false,false,double>(arg); } TEST_P(GETRI, __float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,rocblas_float_complex>(); arg.batch_count = 1; testing_getri<false,false,rocblas_float_complex>(arg); } TEST_P(GETRI, __double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,rocblas_double_complex>(); arg.batch_count = 1; testing_getri<false,false,rocblas_double_complex>(arg); } TEST_P(GETRI, batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,float>(); arg.batch_count = 3; testing_getri<true,true,float>(arg); } TEST_P(GETRI, batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,double>(); arg.batch_count = 3; testing_getri<true,true,double>(arg); } TEST_P(GETRI, batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<true,true,rocblas_float_complex>(arg); } TEST_P(GETRI, batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<true,true,rocblas_double_complex>(arg); } TEST_P(GETRI, strided_batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,float>(); arg.batch_count = 3; testing_getri<false,true,float>(arg); } TEST_P(GETRI, strided_batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,double>(); arg.batch_count = 3; testing_getri<false,true,double>(arg); } TEST_P(GETRI, strided_batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<false,true,rocblas_float_complex>(arg); } TEST_P(GETRI, strided_batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<false,true,rocblas_double_complex>(arg); } TEST_P(GETRI, outofplace_batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,float>(); arg.batch_count = 3; testing_getri<true,false,float>(arg); } TEST_P(GETRI, outofplace_batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,double>(); arg.batch_count = 3; testing_getri<true,false,double>(arg); } TEST_P(GETRI, outofplace_batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<true,false,rocblas_float_complex>(arg); } TEST_P(GETRI, outofplace_batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<true,false,rocblas_double_complex>(arg); } INSTANTIATE_TEST_SUITE_P(daily_lapack, GETRI, ValuesIn(large_matrix_size_range)); INSTANTIATE_TEST_SUITE_P(checkin_lapack, GETRI, ValuesIn(matrix_size_range));
#include "testing_getri.hpp" using ::testing::Combine; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using namespace std; typedef vector<int> getri_tuple; const vector<vector<int>> matrix_size_range = { {0, 1}, {-1, 1}, {20, 5}, {32, 32}, {50, 50}, {70, 100}, {100, 150} }; const vector<vector<int>> large_matrix_size_range = { {192, 192}, {500, 600}, {640, 640}, {1000, 1024}, {1200, 1230} }; Arguments getri_setup_arguments(getri_tuple tup) { Arguments arg; arg.N = tup[0]; arg.lda = tup[1]; arg.timing = 0; arg.bsp = arg.N; arg.bsa = arg.lda * arg.N; return arg; } class GETRI : public ::TestWithParam<getri_tuple> { protected: GETRI() {} virtual void SetUp() {} virtual void TearDown() {} }; TEST_P(GETRI, __float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,float>(); arg.batch_count = 1; testing_getri<false,false,float>(arg); }
TEST_P(GETRI, __float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,rocblas_float_complex>(); arg.batch_count = 1; testing_getri<false,false,rocblas_float_complex>(arg); } TEST_P(GETRI, __double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,rocblas_double_complex>(); arg.batch_count = 1; testing_getri<false,false,rocblas_double_complex>(arg); } TEST_P(GETRI, batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,float>(); arg.batch_count = 3; testing_getri<true,true,float>(arg); } TEST_P(GETRI, batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,double>(); arg.batch_count = 3; testing_getri<true,true,double>(arg); } TEST_P(GETRI, batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<true,true,rocblas_float_complex>(arg); } TEST_P(GETRI, batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,true,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<true,true,rocblas_double_complex>(arg); } TEST_P(GETRI, strided_batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,float>(); arg.batch_count = 3; testing_getri<false,true,float>(arg); } TEST_P(GETRI, strided_batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,double>(); arg.batch_count = 3; testing_getri<false,true,double>(arg); } TEST_P(GETRI, strided_batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<false,true,rocblas_float_complex>(arg); } TEST_P(GETRI, strided_batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,true,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<false,true,rocblas_double_complex>(arg); } TEST_P(GETRI, outofplace_batched__float) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,float>(); arg.batch_count = 3; testing_getri<true,false,float>(arg); } TEST_P(GETRI, outofplace_batched__double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,double>(); arg.batch_count = 3; testing_getri<true,false,double>(arg); } TEST_P(GETRI, outofplace_batched__float_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,rocblas_float_complex>(); arg.batch_count = 3; testing_getri<true,false,rocblas_float_complex>(arg); } TEST_P(GETRI, outofplace_batched__double_complex) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<true,false,rocblas_double_complex>(); arg.batch_count = 3; testing_getri<true,false,rocblas_double_complex>(arg); } INSTANTIATE_TEST_SUITE_P(daily_lapack, GETRI, ValuesIn(large_matrix_size_range)); INSTANTIATE_TEST_SUITE_P(checkin_lapack, GETRI, ValuesIn(matrix_size_range));
TEST_P(GETRI, __double) { Arguments arg = getri_setup_arguments(GetParam()); if (arg.N == 0) testing_getri_bad_arg<false,false,double>(); arg.batch_count = 1; testing_getri<false,false,double>(arg); }
function_block-full_function
[ { "content": "class RocBLAS_Test : public testing::TestWithParam<Arguments>\n\n{\n\nprotected:\n\n // This template functor returns true if the type arguments are valid.\n\n // It converts a FILTER specialization to bool to test type matching.\n\n template <typename... T>\n\n struct type_filter_func...
C++
Servers/ServerManager/vtkSMNewWidgetRepresentationProxy.cxx
utkarshayachit/ParaView
7bbb2aa16fdef9cfbcf4a3786cad905d6770771b
#include "vtkSMNewWidgetRepresentationProxy.h" #include "vtkAbstractWidget.h" #include "vtkClientServerInterpreter.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkProcessModule.h" #include "vtkPVGenericRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkSMIntVectorProperty.h" #include "vtkSMPropertyIterator.h" #include "vtkSMPropertyLink.h" #include "vtkSMProxyProperty.h" #include "vtkSMRenderViewProxy.h" #include "vtkSMViewProxy.h" #include "vtkWeakPointer.h" #include "vtkWidgetRepresentation.h" #include <vtkstd/list> vtkStandardNewMacro(vtkSMNewWidgetRepresentationProxy); class vtkSMNewWidgetRepresentationObserver : public vtkCommand { public: static vtkSMNewWidgetRepresentationObserver *New() { return new vtkSMNewWidgetRepresentationObserver; } virtual void Execute(vtkObject*, unsigned long event, void*) { if (this->Proxy) { this->Proxy->ExecuteEvent(event); } } vtkSMNewWidgetRepresentationObserver():Proxy(0) {} vtkSMNewWidgetRepresentationProxy* Proxy; }; struct vtkSMNewWidgetRepresentationInternals { typedef vtkstd::list<vtkSmartPointer<vtkSMLink> > LinksType; LinksType Links; vtkWeakPointer<vtkSMRenderViewProxy> ViewProxy; }; vtkSMNewWidgetRepresentationProxy::vtkSMNewWidgetRepresentationProxy() { this->RepresentationProxy = 0; this->WidgetProxy = 0; this->Widget = 0; this->Enabled = 0; this->Observer = vtkSMNewWidgetRepresentationObserver::New(); this->Observer->Proxy = this; this->Internal = new vtkSMNewWidgetRepresentationInternals; } vtkSMNewWidgetRepresentationProxy::~vtkSMNewWidgetRepresentationProxy() { this->RepresentationProxy = 0; this->WidgetProxy = 0; this->Widget = 0; this->Observer->Proxy = 0; this->Observer->Delete(); if (this->Internal) { delete this->Internal; } } bool vtkSMNewWidgetRepresentationProxy::AddToView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } vtkAbstractWidget* widget = this->Widget; if (widget) { widget->SetInteractor(renderView->GetInteractor()); } if (this->RepresentationProxy) { vtkSMProxyProperty* rendererProp = vtkSMProxyProperty::SafeDownCast( this->RepresentationProxy->GetProperty("Renderer")); if (rendererProp) { rendererProp->RemoveAllProxies(); rendererProp->AddProxy(renderView->GetRendererProxy()); this->RepresentationProxy->UpdateProperty("Renderer"); } if(this->GetSubProxy("Prop")) { renderView->AddPropToRenderer(this->RepresentationProxy); if (widget) { widget->SetCurrentRenderer(renderView->GetRenderer()); } } else if(this->GetSubProxy("Prop2D")) { renderView->AddPropToRenderer2D(this->RepresentationProxy); if (widget) { widget->SetCurrentRenderer(renderView->GetRenderer2D()); } } } this->Internal->ViewProxy = renderView; this->UpdateEnabled(); return true; } bool vtkSMNewWidgetRepresentationProxy::RemoveFromView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } if (this->Widget) { this->Widget->SetEnabled(0); this->Widget->SetCurrentRenderer(0); this->Widget->SetInteractor(0); } if (this->RepresentationProxy) { vtkSMProxyProperty* rendererProp = vtkSMProxyProperty::SafeDownCast( this->RepresentationProxy->GetProperty("Renderer")); if (rendererProp) { rendererProp->RemoveAllProxies(); rendererProp->AddProxy(0); this->RepresentationProxy->UpdateProperty("Renderer"); } if(this->GetSubProxy("Prop")) { renderView->RemovePropFromRenderer(this->RepresentationProxy); } else if(this->GetSubProxy("Prop2D")) { renderView->RemovePropFromRenderer2D(this->RepresentationProxy); } } this->Internal->ViewProxy = 0; return this->Superclass::RemoveFromView(view); } void vtkSMNewWidgetRepresentationProxy::SetEnabled(int enable) { if (this->Enabled != enable) { this->Enabled = enable; this->UpdateEnabled(); } } void vtkSMNewWidgetRepresentationProxy::UpdateEnabled() { if (this->Internal->ViewProxy && this->Widget) { if (this->Enabled) { if (this->GetSubProxy("Prop")) { this->Widget->SetCurrentRenderer(this->Internal->ViewProxy->GetRenderer()); } else if (this->GetSubProxy("Prop2D")) { this->Widget->SetCurrentRenderer(this->Internal->ViewProxy->GetRenderer2D()); } } this->Widget->SetEnabled(this->Enabled); } } void vtkSMNewWidgetRepresentationProxy::CreateVTKObjects() { if (this->ObjectsCreated) { return; } this->RepresentationProxy = this->GetSubProxy("Prop"); if (!this->RepresentationProxy) { this->RepresentationProxy = this->GetSubProxy("Prop2D"); } if (!this->RepresentationProxy) { vtkErrorMacro( "A representation proxy must be defined as a Prop (or Prop2D) sub-proxy"); return; } this->RepresentationProxy->SetServers( vtkProcessModule::RENDER_SERVER | vtkProcessModule::CLIENT); this->WidgetProxy = this->GetSubProxy("Widget"); if (this->WidgetProxy) { this->WidgetProxy->SetServers(vtkProcessModule::CLIENT); } this->Superclass::CreateVTKObjects(); if (!this->WidgetProxy) { return; } vtkSMProxyProperty* pp = vtkSMProxyProperty::SafeDownCast( this->WidgetProxy->GetProperty("Representation")); if (pp) { pp->AddProxy(this->RepresentationProxy); } this->WidgetProxy->UpdateVTKObjects(); vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); this->Widget = vtkAbstractWidget::SafeDownCast( pm->GetObjectFromID(this->WidgetProxy->GetID())); if (this->Widget) { this->Widget->AddObserver( vtkCommand::StartInteractionEvent, this->Observer); this->Widget->AddObserver( vtkCommand::EndInteractionEvent, this->Observer); this->Widget->AddObserver( vtkCommand::InteractionEvent, this->Observer); } this->UpdatePropertyInformation(); vtkSMPropertyIterator* piter = this->NewPropertyIterator(); for(piter->Begin(); !piter->IsAtEnd(); piter->Next()) { vtkSMProperty* prop = piter->GetProperty(); vtkSMProperty* info = prop->GetInformationProperty(); if (info) { info->Copy(prop); vtkSMPropertyLink* link = vtkSMPropertyLink::New(); link->AddLinkedProperty(this, piter->GetKey(), vtkSMLink::OUTPUT); link->AddLinkedProperty(this, this->GetPropertyName(info), vtkSMLink::INPUT); this->Internal->Links.push_back(link); link->Delete(); } } piter->Delete(); } void vtkSMNewWidgetRepresentationProxy::ExecuteEvent(unsigned long event) { this->InvokeEvent(event); if (event == vtkCommand::StartInteractionEvent) { vtkPVGenericRenderWindowInteractor* inter = vtkPVGenericRenderWindowInteractor::SafeDownCast( this->Widget->GetInteractor()); if (inter) { inter->InteractiveRenderEnabledOn(); } vtkSMProperty* startInt = this->RepresentationProxy->GetProperty("OnStartInteraction"); if (startInt) { startInt->Modified(); this->RepresentationProxy->UpdateProperty("OnStartInteraction"); } } else if (event == vtkCommand::InteractionEvent) { this->RepresentationProxy->UpdatePropertyInformation(); this->UpdateVTKObjects(); vtkSMProperty* interaction = this->RepresentationProxy->GetProperty("OnInteraction"); if (interaction) { interaction->Modified(); this->RepresentationProxy->UpdateProperty("OnInteraction"); } } else if (event == vtkCommand::EndInteractionEvent) { vtkPVGenericRenderWindowInteractor* inter = vtkPVGenericRenderWindowInteractor::SafeDownCast( this->Widget->GetInteractor()); if (inter) { inter->InteractiveRenderEnabledOff(); } vtkSMProperty* sizeHandles = this->RepresentationProxy->GetProperty("SizeHandles"); if (sizeHandles) { sizeHandles->Modified(); this->RepresentationProxy->UpdateProperty("SizeHandles"); } vtkSMProperty* endInt = this->RepresentationProxy->GetProperty("OnEndInteraction"); if (endInt) { endInt->Modified(); this->RepresentationProxy->UpdateProperty("OnEndInteraction"); } } } void vtkSMNewWidgetRepresentationProxy::UnRegister(vtkObjectBase* obj) { if ( this->GetSelfIDInternal().ID != 0 ) { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); if ( pm && obj != pm->GetInterpreter() && this->Internal ) { int size = this->Internal->Links.size(); if (size > 0 && this->ReferenceCount == 2 + 2*size) { vtkSMNewWidgetRepresentationInternals* aInternal = this->Internal; this->Internal = 0; delete aInternal; aInternal = 0; } } } this->Superclass::UnRegister(obj); } bool vtkSMNewWidgetRepresentationProxy::GetBounds(double bds[6]) { if (this->RepresentationProxy) { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); vtkWidgetRepresentation* repr = vtkWidgetRepresentation::SafeDownCast( pm->GetObjectFromID(this->RepresentationProxy->GetID())); if (repr) { double *propBds = repr->GetBounds(); if (propBds) { memcpy(bds, propBds, 6*sizeof(double)); return true; } } } return false; } void vtkSMNewWidgetRepresentationProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
#include "vtkSMNewWidgetRepresentationProxy.h" #include "vtkAbstractWidget.h" #include "vtkClientServerInterpreter.h" #include "vtkCommand.h" #include "vtkObjectFactory.h" #include "vtkProcessModule.h" #include "vtkPVGenericRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkSMIntVectorProperty.h" #include "vtkSMPropertyIterator.h" #include "vtkSMPropertyLink.h" #include "vtkSMProxyProperty.h" #include "vtkSMRenderViewProxy.h" #include "vtkSMViewProxy.
Prop2D"); } if (!this->RepresentationProxy) { vtkErrorMacro( "A representation proxy must be defined as a Prop (or Prop2D) sub-proxy"); return; } this->RepresentationProxy->SetServers( vtkProcessModule::RENDER_SERVER | vtkProcessModule::CLIENT); this->WidgetProxy = this->GetSubProxy("Widget"); if (this->WidgetProxy) { this->WidgetProxy->SetServers(vtkProcessModule::CLIENT); } this->Superclass::CreateVTKObjects(); if (!this->WidgetProxy) { return; } vtkSMProxyProperty* pp = vtkSMProxyProperty::SafeDownCast( this->WidgetProxy->GetProperty("Representation")); if (pp) { pp->AddProxy(this->RepresentationProxy); } this->WidgetProxy->UpdateVTKObjects(); vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); this->Widget = vtkAbstractWidget::SafeDownCast( pm->GetObjectFromID(this->WidgetProxy->GetID())); if (this->Widget) { this->Widget->AddObserver( vtkCommand::StartInteractionEvent, this->Observer); this->Widget->AddObserver( vtkCommand::EndInteractionEvent, this->Observer); this->Widget->AddObserver( vtkCommand::InteractionEvent, this->Observer); } this->UpdatePropertyInformation(); vtkSMPropertyIterator* piter = this->NewPropertyIterator(); for(piter->Begin(); !piter->IsAtEnd(); piter->Next()) { vtkSMProperty* prop = piter->GetProperty(); vtkSMProperty* info = prop->GetInformationProperty(); if (info) { info->Copy(prop); vtkSMPropertyLink* link = vtkSMPropertyLink::New(); link->AddLinkedProperty(this, piter->GetKey(), vtkSMLink::OUTPUT); link->AddLinkedProperty(this, this->GetPropertyName(info), vtkSMLink::INPUT); this->Internal->Links.push_back(link); link->Delete(); } } piter->Delete(); } void vtkSMNewWidgetRepresentationProxy::ExecuteEvent(unsigned long event) { this->InvokeEvent(event); if (event == vtkCommand::StartInteractionEvent) { vtkPVGenericRenderWindowInteractor* inter = vtkPVGenericRenderWindowInteractor::SafeDownCast( this->Widget->GetInteractor()); if (inter) { inter->InteractiveRenderEnabledOn(); } vtkSMProperty* startInt = this->RepresentationProxy->GetProperty("OnStartInteraction"); if (startInt) { startInt->Modified(); this->RepresentationProxy->UpdateProperty("OnStartInteraction"); } } else if (event == vtkCommand::InteractionEvent) { this->RepresentationProxy->UpdatePropertyInformation(); this->UpdateVTKObjects(); vtkSMProperty* interaction = this->RepresentationProxy->GetProperty("OnInteraction"); if (interaction) { interaction->Modified(); this->RepresentationProxy->UpdateProperty("OnInteraction"); } } else if (event == vtkCommand::EndInteractionEvent) { vtkPVGenericRenderWindowInteractor* inter = vtkPVGenericRenderWindowInteractor::SafeDownCast( this->Widget->GetInteractor()); if (inter) { inter->InteractiveRenderEnabledOff(); } vtkSMProperty* sizeHandles = this->RepresentationProxy->GetProperty("SizeHandles"); if (sizeHandles) { sizeHandles->Modified(); this->RepresentationProxy->UpdateProperty("SizeHandles"); } vtkSMProperty* endInt = this->RepresentationProxy->GetProperty("OnEndInteraction"); if (endInt) { endInt->Modified(); this->RepresentationProxy->UpdateProperty("OnEndInteraction"); } } } void vtkSMNewWidgetRepresentationProxy::UnRegister(vtkObjectBase* obj) { if ( this->GetSelfIDInternal().ID != 0 ) { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); if ( pm && obj != pm->GetInterpreter() && this->Internal ) { int size = this->Internal->Links.size(); if (size > 0 && this->ReferenceCount == 2 + 2*size) { vtkSMNewWidgetRepresentationInternals* aInternal = this->Internal; this->Internal = 0; delete aInternal; aInternal = 0; } } } this->Superclass::UnRegister(obj); } bool vtkSMNewWidgetRepresentationProxy::GetBounds(double bds[6]) { if (this->RepresentationProxy) { vtkProcessModule* pm = vtkProcessModule::GetProcessModule(); vtkWidgetRepresentation* repr = vtkWidgetRepresentation::SafeDownCast( pm->GetObjectFromID(this->RepresentationProxy->GetID())); if (repr) { double *propBds = repr->GetBounds(); if (propBds) { memcpy(bds, propBds, 6*sizeof(double)); return true; } } } return false; } void vtkSMNewWidgetRepresentationProxy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); }
h" #include "vtkWeakPointer.h" #include "vtkWidgetRepresentation.h" #include <vtkstd/list> vtkStandardNewMacro(vtkSMNewWidgetRepresentationProxy); class vtkSMNewWidgetRepresentationObserver : public vtkCommand { public: static vtkSMNewWidgetRepresentationObserver *New() { return new vtkSMNewWidgetRepresentationObserver; } virtual void Execute(vtkObject*, unsigned long event, void*) { if (this->Proxy) { this->Proxy->ExecuteEvent(event); } } vtkSMNewWidgetRepresentationObserver():Proxy(0) {} vtkSMNewWidgetRepresentationProxy* Proxy; }; struct vtkSMNewWidgetRepresentationInternals { typedef vtkstd::list<vtkSmartPointer<vtkSMLink> > LinksType; LinksType Links; vtkWeakPointer<vtkSMRenderViewProxy> ViewProxy; }; vtkSMNewWidgetRepresentationProxy::vtkSMNewWidgetRepresentationProxy() { this->RepresentationProxy = 0; this->WidgetProxy = 0; this->Widget = 0; this->Enabled = 0; this->Observer = vtkSMNewWidgetRepresentationObserver::New(); this->Observer->Proxy = this; this->Internal = new vtkSMNewWidgetRepresentationInternals; } vtkSMNewWidgetRepresentationProxy::~vtkSMNewWidgetRepresentationProxy() { this->RepresentationProxy = 0; this->WidgetProxy = 0; this->Widget = 0; this->Observer->Proxy = 0; this->Observer->Delete(); if (this->Internal) { delete this->Internal; } } bool vtkSMNewWidgetRepresentationProxy::AddToView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } vtkAbstractWidget* widget = this->Widget; if (widget) { widget->SetInteractor(renderView->GetInteractor()); } if (this->RepresentationProxy) { vtkSMProxyProperty* rendererProp = vtkSMProxyProperty::SafeDownCast( this->RepresentationProxy->GetProperty("Renderer")); if (rendererProp) { rendererProp->RemoveAllProxies(); rendererProp->AddProxy(renderView->GetRendererProxy()); this->RepresentationProxy->UpdateProperty("Renderer"); } if(this->GetSubProxy("Prop")) { renderView->AddPropToRenderer(this->RepresentationProxy); if (widget) { widget->SetCurrentRenderer(renderView->GetRenderer()); } } else if(this->GetSubProxy("Prop2D")) { renderView->AddPropToRenderer2D(this->RepresentationProxy); if (widget) { widget->SetCurrentRenderer(renderView->GetRenderer2D()); } } } this->Internal->ViewProxy = renderView; this->UpdateEnabled(); return true; } bool vtkSMNewWidgetRepresentationProxy::RemoveFromView(vtkSMViewProxy* view) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(view); if (!renderView) { vtkErrorMacro("View must be a vtkSMRenderViewProxy."); return false; } if (this->Widget) { this->Widget->SetEnabled(0); this->Widget->SetCurrentRenderer(0); this->Widget->SetInteractor(0); } if (this->RepresentationProxy) { vtkSMProxyProperty* rendererProp = vtkSMProxyProperty::SafeDownCast( this->RepresentationProxy->GetProperty("Renderer")); if (rendererProp) { rendererProp->RemoveAllProxies(); rendererProp->AddProxy(0); this->RepresentationProxy->UpdateProperty("Renderer"); } if(this->GetSubProxy("Prop")) { renderView->RemovePropFromRenderer(this->RepresentationProxy); } else if(this->GetSubProxy("Prop2D")) { renderView->RemovePropFromRenderer2D(this->RepresentationProxy); } } this->Internal->ViewProxy = 0; return this->Superclass::RemoveFromView(view); } void vtkSMNewWidgetRepresentationProxy::SetEnabled(int enable) { if (this->Enabled != enable) { this->Enabled = enable; this->UpdateEnabled(); } } void vtkSMNewWidgetRepresentationProxy::UpdateEnabled() { if (this->Internal->ViewProxy && this->Widget) { if (this->Enabled) { if (this->GetSubProxy("Prop")) { this->Widget->SetCurrentRenderer(this->Internal->ViewProxy->GetRenderer()); } else if (this->GetSubProxy("Prop2D")) { this->Widget->SetCurrentRenderer(this->Internal->ViewProxy->GetRenderer2D()); } } this->Widget->SetEnabled(this->Enabled); } } void vtkSMNewWidgetRepresentationProxy::CreateVTKObjects() { if (this->ObjectsCreated) { return; } this->RepresentationProxy = this->GetSubProxy("Prop"); if (!this->RepresentationProxy) { this->RepresentationProxy = this->GetSubProxy("
random
[ { "content": "def get_include():\n\n \"\"\"\n\n Return the directory in the package that contains header files.\n\n\n\n Extension modules that need to compile against mpi4py should use\n\n this function to locate the appropriate include directory. Using\n\n Python distutils (or perhaps NumPy dist...
C++
torch/lib/THD/master_worker/master/generic/THDStorage.cpp
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "master_worker/master/generic/THDStorage.cpp" #else using namespace thd; using namespace rpc; using namespace master; static THDStorage* THDStorage_(_alloc)() { THDStorage* new_storage = new THDStorage(); std::memset(reinterpret_cast<void*>(new_storage), 0, sizeof(new_storage)); new (&new_storage->refcount) std::atomic<int>(1); new_storage->storage_id = THDState::s_nextId++; new_storage->node_id = THDState::s_current_worker; new_storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE; return new_storage; } ptrdiff_t THDStorage_(size)(const THDStorage* storage) { return storage->size; } size_t THDStorage_(elementSize)(void) { return sizeof(real); } THDStorage* THDStorage_(new)() { THDStorage* storage = THDStorage_(_alloc)(); RPCType type = type_traits<real>::type; masterCommandChannel->sendMessage( packMessage( Functions::storageNew, type, storage ), THDState::s_current_worker ); return storage; } void THDStorage_(set)(THDStorage* storage, ptrdiff_t offset, real value) { masterCommandChannel->sendMessage( packMessage( Functions::storageSet, storage, offset, value ), THDState::s_current_worker ); } real THDStorage_(get)(const THDStorage* storage, ptrdiff_t offset) { masterCommandChannel->sendMessage( packMessage( Functions::storageGet, storage, offset, type_traits<real>::type ), THDState::s_current_worker ); return receiveValueFromWorker<real>(storage->node_id); } THDStorage* THDStorage_(newWithSize)(ptrdiff_t size) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = size; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize, type, storage, size ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize1)(real value) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 1; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize2)(real value1, real value2) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 2; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2 ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize3)(real value1, real value2, real value3) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 3; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2, value3 ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize4)(real value1, real value2, real value3, real value4) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 4; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2, value3, value4 ), THDState::s_current_worker ); return storage; } void THDStorage_(setFlag)(THDStorage *storage, const char flag) { storage->flag |= flag; } void THDStorage_(clearFlag)(THDStorage *storage, const char flag) { storage->flag &= ~flag; } void THDStorage_(retain)(THDStorage *storage) { if (storage && (storage->flag & TH_STORAGE_REFCOUNTED)) storage->refcount++; } void THDStorage_(swap)(THDStorage *storage1, THDStorage *storage2) { THDStorage dummy = *storage1; *storage1 = *storage2; *storage2 = dummy; } void THDStorage_(free)(THDStorage *storage) { if (!storage || !(storage->flag & TH_STORAGE_REFCOUNTED)) return; if (--storage->refcount == 0) { masterCommandChannel->sendMessage( packMessage( Functions::storageFree, storage ), THDState::s_current_worker ); delete storage; } } void THDStorage_(resize)(THDStorage *storage, ptrdiff_t size) { if (!(storage->flag & TH_STORAGE_RESIZABLE)) THError("Trying to resize storage that is not resizable"); if (size < storage->size) return; storage->size = size; masterCommandChannel->sendMessage( packMessage( Functions::storageResize, storage, size ), THDState::s_current_worker ); } void THDStorage_(fill)(THDStorage *storage, real value) { masterCommandChannel->sendMessage( packMessage( Functions::storageFill, storage, value ), THDState::s_current_worker ); } #endif
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "master_worker/master/generic/THDStorage.cpp" #else using namespace thd; using namespace rpc; using namespace master; static THDStorage* THDStorage_(_alloc)() { THDStorage* new_storage = new THDStorage(); std::memset(reinterpret_cast<void*>(new_storage), 0, sizeof(new_storage)); new (&new_storage->refcount) std::atomic<int>(1); new_storage->storage_id = THDState::s_nextId++; new_storage->node_id = THDState::s_current_worker; new_storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_RESIZABLE; return new_storage; } ptrdiff_t THDStorage_(size)(const THDStorage* storage) { return storage->size; } size_t THDStorage_(elementSize)(void) { return sizeof(real); } THDStorage* THDStorage_(new)() { THDStorage* storage = THDStorage_(_alloc)(); RPCType type = type_traits<real>::type; masterCommandChannel->sendMessage( packMessage( Functions::storageNew, type, storage ), THDState::s_current_worker ); return storage; } void THDStorage_(set)(THDStorage* storage, ptrdiff_t offset, real value) { masterCommandChannel->sendMessage( packMessage( Functions::storageSet, storage, offset, value ), THDState::s_current_worker ); } real THDStorage_(get)(const THDStorage* storage, ptrdiff_t offset) { masterCommandChannel->sendMessage( packMessage( Functions::storageGet, storage, offset, type_traits<real>::type ), THDState::s_current_worker ); return receiveValueFromWorker<real>(storage->node_id); } THDStorage* THDStorage_(newWithSize)(ptrdiff_t size) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = size; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize, type, storage, size ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize1)(real value) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 1; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize2)(real value1, real value2) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 2; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2 ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize3)(real value1, real value2, real value3) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 3; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2, value3 ), THDState::s_current_worker ); return storage; } THDStorage* THDStorage_(newWithSize4)(real value
void THDStorage_(setFlag)(THDStorage *storage, const char flag) { storage->flag |= flag; } void THDStorage_(clearFlag)(THDStorage *storage, const char flag) { storage->flag &= ~flag; } void THDStorage_(retain)(THDStorage *storage) { if (storage && (storage->flag & TH_STORAGE_REFCOUNTED)) storage->refcount++; } void THDStorage_(swap)(THDStorage *storage1, THDStorage *storage2) { THDStorage dummy = *storage1; *storage1 = *storage2; *storage2 = dummy; } void THDStorage_(free)(THDStorage *storage) { if (!storage || !(storage->flag & TH_STORAGE_REFCOUNTED)) return; if (--storage->refcount == 0) { masterCommandChannel->sendMessage( packMessage( Functions::storageFree, storage ), THDState::s_current_worker ); delete storage; } } void THDStorage_(resize)(THDStorage *storage, ptrdiff_t size) { if (!(storage->flag & TH_STORAGE_RESIZABLE)) THError("Trying to resize storage that is not resizable"); if (size < storage->size) return; storage->size = size; masterCommandChannel->sendMessage( packMessage( Functions::storageResize, storage, size ), THDState::s_current_worker ); } void THDStorage_(fill)(THDStorage *storage, real value) { masterCommandChannel->sendMessage( packMessage( Functions::storageFill, storage, value ), THDState::s_current_worker ); } #endif
1, real value2, real value3, real value4) { RPCType type = type_traits<real>::type; THDStorage *storage = THDStorage_(_alloc)(); storage->size = 4; masterCommandChannel->sendMessage( packMessage( Functions::storageNewWithSize1, type, storage, value1, value2, value3, value4 ), THDState::s_current_worker ); return storage; }
function_block-function_prefixed
[ { "content": " ptrdiff_t size;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDStorage.h", "rank": 0, "score": 379224.93917560467 }, { "content": " ptrdiff_t storageOffset;\n", "file_path": "torch/lib/THD/master_worker/master/generic/THDTensor.h", "rank": 1, "sc...
C++
cpp/fntest/pubnub_fntest_runner.cpp
mrtryhard/c-core
4c3c7009a133bf770c255243a2fc580f1629110e
#include "pubnub_fntest_basic.hpp" #include "pubnub_fntest_medium.hpp" #include <iostream> #include <functional> #include <condition_variable> #include <thread> #include <cstdlib> #include <cstring> #if defined _WIN32 #include "windows/console_subscribe_paint.h" #else #include "posix/console_subscribe_paint.h" #endif enum class TestResult { fail, pass, indeterminate }; using TestFN_T = std::function<void(std::string const&, std::string const&, std::string const&, bool const&)>; struct TestData { TestFN_T pf; char const *name; TestResult result; }; #define LIST_TEST(tstname) { pnfn_test_##tstname, #tstname, TestResult::indeterminate } static TestData m_aTest[] = { LIST_TEST(simple_connect_and_send_over_single_channel), LIST_TEST(connect_and_send_over_several_channels_simultaneously), LIST_TEST(simple_connect_and_send_over_single_channel_in_group), LIST_TEST(connect_and_send_over_several_channels_in_group_simultaneously), LIST_TEST(connect_and_send_over_channel_in_group_and_single_channel_simultaneously), LIST_TEST(connect_and_send_over_channel_in_group_and_multi_channel_simultaneously), LIST_TEST(simple_connect_and_receiver_over_single_channel), LIST_TEST(connect_and_receive_over_several_channels_simultaneously), LIST_TEST(simple_connect_and_receiver_over_single_channel_in_group), LIST_TEST(connect_and_receive_over_several_channels_in_group_simultaneously), LIST_TEST(connect_and_receive_over_channel_in_group_and_single_channel_simultaneously), LIST_TEST(connect_and_receive_over_channel_in_group_and_multi_channel_simultaneously), LIST_TEST(complex_send_and_receive_over_several_channels_simultaneously), LIST_TEST(complex_send_and_receive_over_channel_plus_group_simultaneously), LIST_TEST(connect_disconnect_and_connect_again), LIST_TEST(connect_disconnect_and_connect_again_group), LIST_TEST(connect_disconnect_and_connect_again_combo), LIST_TEST(wrong_api_usage), LIST_TEST(handling_errors_from_pubnub) }; #define TEST_COUNT (sizeof m_aTest / sizeof m_aTest[0]) static std::mutex m_mtx; static std::condition_variable m_cndvar; static unsigned m_running_tests; static bool is_pull_request_build(void) { #if !defined _WIN32 char const* tprb = getenv("TRAVIS_PULL_REQUEST"); return (tprb != NULL) && (0 != strcmp(tprb, "false")); #else return NULL != getenv("APPVEYOR_PULL_REQUEST_NUMBER"); #endif } static void notify(TestData &test,TestResult result) { { std::lock_guard<std::mutex> lk(m_mtx); --m_running_tests; test.result = result; } m_cndvar.notify_one(); } static int run_tests(TestData aTest[], unsigned test_count, unsigned max_conc_thread, std::string& pubkey, std::string& keysub, std::string& origin) { unsigned next_test = 0; std::vector<unsigned> failed; unsigned passed_count = 0; unsigned indete_count = 0; std::vector<std::thread> runners(test_count); bool cannot_do_chan_group; cannot_do_chan_group = is_pull_request_build(); std::cout << "Starting Run of " << test_count << " tests" << std::endl;; while (next_test < test_count) { unsigned i; unsigned in_this_pass = max_conc_thread; if (next_test + in_this_pass > test_count) { in_this_pass = test_count - next_test; } m_running_tests = in_this_pass; for (i = next_test; i < next_test+in_this_pass; ++i) { runners[i-next_test] = std::thread([i, pubkey, keysub, origin, aTest, cannot_do_chan_group] { try { using namespace std::chrono; system_clock::time_point tp = system_clock::now(); system_clock::duration dtn = tp.time_since_epoch(); srand(dtn.count()); aTest[i].pf(pubkey.c_str(), keysub.c_str(), origin.c_str(), cannot_do_chan_group); notify(aTest[i], TestResult::pass); } catch (std::exception &ex) { std::cout << std::endl; paint_text_white_with_background_red(); std::cout << " !! " << i+1 << ". test '" << aTest[i].name << "' failed!" << std::endl << "Error description: " << ex.what(); reset_text_paint(); std::cout << std::endl << std::endl; notify(aTest[i], TestResult::fail); } catch (pubnub::except_test &ex) { std::cout << std::endl; paint_text_yellow(); std::cout << " !! " << i+1 << ". test '" << aTest[i].name << "' indeterminate!" << std::endl << "Description: " << ex.what(); reset_text_paint(); std::cout << std::endl << std::endl; notify(aTest[i], TestResult::indeterminate); } }); std::this_thread::sleep_for(std::chrono::milliseconds(3)); } { std::unique_lock<std::mutex> lk(m_mtx); m_cndvar.wait(lk, []{ return m_running_tests == 0; }); } for (i = next_test; i < next_test+in_this_pass; ++i) { runners[i-next_test].join(); switch (aTest[i].result) { case TestResult::fail: failed.push_back(i); break; case TestResult::pass: ++passed_count; break; case TestResult::indeterminate: ++indete_count; break; } } next_test = i; } paint_text_white(); std::cout << "\nTest run over." << std::endl; if (passed_count == test_count) { paint_text_green(); std::cout << "All " << test_count << " tests passed" << std::endl; paint_text_white(); return 0; } else { paint_text_green(); std::cout << passed_count << " tests passed, "; reset_text_paint(); paint_text_white_with_background_red(); std::cout << failed.size() << " tests failed!"; reset_text_paint(); paint_text_white(); std::cout << ", "; paint_text_yellow(); std::cout << indete_count << " tests indeterminate" << std::endl; reset_text_paint(); if (!failed.empty()) { unsigned i; paint_text_white_with_background_red(); std::cout << "Failed tests:\n"; for (i = 0; i < failed.size() - 1 ; ++i) { std::cout << failed[i]+1 << ". " << aTest[failed[i]].name << std::endl; } std::cout << failed[i]+1 << ". " << aTest[failed[i]].name; reset_text_paint(); std::cout << std::endl; } paint_text_white(); return failed.size(); } } std::string getenv_ex(char const *env, char const *dflt) { char const* s = getenv(env); return (NULL == s) ? dflt : s; } int main(int argc, char *argv[]) { std::string pubkey = getenv_ex("PUBNUB_PUBKEY", (argc > 1) ? argv[1] : "demo"); std::string keysub = getenv_ex("PUBNUB_KEYSUB", (argc > 2) ? argv[2] : "demo"); std::string origin = getenv_ex("PUBNUB_ORIGIN", (argc > 3) ? argv[3] : "pubsub.pubnub.com"); unsigned max_conc_thread = (argc > 4) ? std::atoi(argv[4]) : 1; return run_tests(m_aTest, TEST_COUNT, max_conc_thread, pubkey, keysub, origin); }
#include "pubnub_fntest_basic.hpp" #include "pubnub_fntest_medium.hpp" #include <iostream> #include <functional> #include <condition_variable> #include <thread> #include <cstdlib> #include <cstring> #if defined _WIN32 #include "windows/console_subscribe_paint.h" #else #include "posix/console_subscribe_paint.h" #endif enum class TestResult { fail, pass, indeterminate }; using TestFN_T = std::function<void(std::string const&, std::string const&, std::string const&, bool const&)>; struct TestData { TestFN_T pf; char const *name; TestResult result; }; #define LIST_TEST(tstname) { pnfn_test_##tstname, #tstname, TestResult::indeterminate } static TestData m_aTest[] = { LIST_TEST(simple_connect_and_send_over_single_channel), LIST_TEST(connect_and_send_over_several_channels_simultaneously), LIST_TEST(simple_connect_and_send_over_single_channel_in_group), LIST_TEST(connect_and_send_over_several_channels_in_group_simultaneously), LIST_TEST(connect_and_send_over_channel_in_group_and_single_channel_simultaneously), LIST_TEST(connect_and_send_over_channel_in_group_and_multi_channel_simultaneously), LIST_TEST(simple_connect_and_receiver_over_single_channel), LIST_TEST(connect_and_receive_over_several_channels_simultaneously), LIST_TEST(simple_connect_and_receiver_over_single_channel_in_group), LIST_TEST(connect_and_receive_over_several_channels_in_group_simultaneously), LIST_TEST(connect_and_receive_over_channel_in_group_and_single_channel_simultaneously), LIST_TEST(connect_and_receive_over_channel_in_group_and_multi_channel_simultaneously), LIST_TEST(complex_send_and_receive_over_several_channels_simultaneously), LIST_TEST(complex_send_and_receive_over_channel_plus_group_simultaneously), LIST_TEST(connect_disconnect_and_connect_again), LIST_TEST(connect_disconnect_and_connect_again_group), LIST_TEST(connect_disconnect_and_connect_again_combo), LIST_TEST(wrong_api_usage), LIST_TEST(handling_errors_from_pubnub) }; #define TEST_COUNT (sizeof m_aTest / sizeof m_aTest[0]) static std::mutex m_mtx; static std::condition_variable m_cndvar; static unsigned m_running_tests; static bool is_pull_request_build(void) { #if !defined _WIN32 char const* tprb = getenv("TRAVIS_PULL_REQUEST"); return (tprb != NULL) && (0 != strcmp(tprb, "false")); #else return NULL != getenv("APPVEYOR_PULL_REQUEST_NUMBER"); #endif } static void notify(TestData &test,TestResult result) { { std::lock_guard<std::mutex> lk(m_mtx); --m_running_tests; test.result = result; } m_cndvar.notify_one(); } static int run_tests(TestData aTest[], unsigned test_count, unsigned max_conc_thread, std::string& pubkey, std::string& keysub, std::string& origin) { unsigned next_test = 0; std::vector<unsigned> failed; unsigned passed_count = 0; unsigned indete_count = 0; std::vector<std::thread> runners(test_count); bool cannot_do_chan_group; cannot_do_chan_group = is_pull_request_build(); std::cout << "Starting Run of " << test_count << " tests" << std::endl;; while (next_test < test_count) { unsigned i; unsigned in_this_pass = max_conc_thread; if (next_test + in_this_pass > test_count) { in_this_pass = test_count - next_test; } m_running_tests = in_this_pass; for (i = next_test; i < next_test+in_this_pass; ++i) { runners[i-next_test] = std::thread([i, pubkey, keysub, origin, aTest, cannot_do_chan_group] { try { using namespace std::chrono; system_clock::time_point tp = system_clock::now(); system_clock::duration dtn = tp.time_since_epoch(); srand(dtn.count());
; notify(aTest[i], TestResult::pass); } catch (std::exception &ex) { std::cout << std::endl; paint_text_white_with_background_red(); std::cout << " !! " << i+1 << ". test '" << aTest[i].name << "' failed!" << std::endl << "Error description: " << ex.what(); reset_text_paint(); std::cout << std::endl << std::endl; notify(aTest[i], TestResult::fail); } catch (pubnub::except_test &ex) { std::cout << std::endl; paint_text_yellow(); std::cout << " !! " << i+1 << ". test '" << aTest[i].name << "' indeterminate!" << std::endl << "Description: " << ex.what(); reset_text_paint(); std::cout << std::endl << std::endl; notify(aTest[i], TestResult::indeterminate); } }); std::this_thread::sleep_for(std::chrono::milliseconds(3)); } { std::unique_lock<std::mutex> lk(m_mtx); m_cndvar.wait(lk, []{ return m_running_tests == 0; }); } for (i = next_test; i < next_test+in_this_pass; ++i) { runners[i-next_test].join(); switch (aTest[i].result) { case TestResult::fail: failed.push_back(i); break; case TestResult::pass: ++passed_count; break; case TestResult::indeterminate: ++indete_count; break; } } next_test = i; } paint_text_white(); std::cout << "\nTest run over." << std::endl; if (passed_count == test_count) { paint_text_green(); std::cout << "All " << test_count << " tests passed" << std::endl; paint_text_white(); return 0; } else { paint_text_green(); std::cout << passed_count << " tests passed, "; reset_text_paint(); paint_text_white_with_background_red(); std::cout << failed.size() << " tests failed!"; reset_text_paint(); paint_text_white(); std::cout << ", "; paint_text_yellow(); std::cout << indete_count << " tests indeterminate" << std::endl; reset_text_paint(); if (!failed.empty()) { unsigned i; paint_text_white_with_background_red(); std::cout << "Failed tests:\n"; for (i = 0; i < failed.size() - 1 ; ++i) { std::cout << failed[i]+1 << ". " << aTest[failed[i]].name << std::endl; } std::cout << failed[i]+1 << ". " << aTest[failed[i]].name; reset_text_paint(); std::cout << std::endl; } paint_text_white(); return failed.size(); } } std::string getenv_ex(char const *env, char const *dflt) { char const* s = getenv(env); return (NULL == s) ? dflt : s; } int main(int argc, char *argv[]) { std::string pubkey = getenv_ex("PUBNUB_PUBKEY", (argc > 1) ? argv[1] : "demo"); std::string keysub = getenv_ex("PUBNUB_KEYSUB", (argc > 2) ? argv[2] : "demo"); std::string origin = getenv_ex("PUBNUB_ORIGIN", (argc > 3) ? argv[3] : "pubsub.pubnub.com"); unsigned max_conc_thread = (argc > 4) ? std::atoi(argv[4]) : 1; return run_tests(m_aTest, TEST_COUNT, max_conc_thread, pubkey, keysub, origin); }
aTest[i].pf(pubkey.c_str(), keysub.c_str(), origin.c_str(), cannot_do_chan_group)
call_expression
[ { "content": "enum class TestResult { fail, pass, indeterminate };\n\nQ_DECLARE_METATYPE(TestResult);\n\n\n\nusing TestFN_T =\n\n std::function<void(std::string const&, std::string const&, std::string const&, bool const&)>;\n\n\n", "file_path": "qt/fntest/pubnub_fntest_runner.cpp", "rank": 0, "sc...
C++
RecoEgamma/EgammaTools/plugins/HGCalPhotonIDValueMapProducer.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
#include <memory> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/StreamID.h" #include "DataFormats/Common/interface/ValueMap.h" #include "DataFormats/EgammaCandidates/interface/Photon.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" #include "RecoEgamma/EgammaTools/interface/HGCalEgammaIDHelper.h" #include "RecoEgamma/EgammaTools/interface/LongDeps.h" class HGCalPhotonIDValueMapProducer : public edm::stream::EDProducer<> { public: explicit HGCalPhotonIDValueMapProducer(const edm::ParameterSet&); ~HGCalPhotonIDValueMapProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void beginStream(edm::StreamID) override; void produce(edm::Event&, const edm::EventSetup&) override; void endStream() override; edm::EDGetTokenT<edm::View<reco::Photon>> photonsToken_; float radius_; static const std::vector<std::string> valuesProduced_; std::map<const std::string, std::vector<float>> maps_; std::unique_ptr<HGCalEgammaIDHelper> phoIDHelper_; }; const std::vector<std::string> HGCalPhotonIDValueMapProducer::valuesProduced_ = { "seedEt", "seedEnergy", "seedEnergyEE", "seedEnergyFH", "seedEnergyBH", "pcaEig1", "pcaEig2", "pcaEig3", "pcaSig1", "pcaSig2", "pcaSig3", "sigmaUU", "sigmaVV", "sigmaEE", "sigmaPP", "nLayers", "firstLayer", "lastLayer", "e4oEtot", "layerEfrac10", "layerEfrac90", "measuredDepth", "expectedDepth", "expectedSigma", "depthCompatibility", "caloIsoRing0", "caloIsoRing1", "caloIsoRing2", "caloIsoRing3", "caloIsoRing4", }; HGCalPhotonIDValueMapProducer::HGCalPhotonIDValueMapProducer(const edm::ParameterSet& iConfig) : photonsToken_(consumes<edm::View<reco::Photon>>(iConfig.getParameter<edm::InputTag>("photons"))), radius_(iConfig.getParameter<double>("pcaRadius")) { for(const auto& key : valuesProduced_) { maps_[key] = {}; produces<edm::ValueMap<float>>(key); } phoIDHelper_.reset(new HGCalEgammaIDHelper(iConfig, consumesCollector())); } HGCalPhotonIDValueMapProducer::~HGCalPhotonIDValueMapProducer() { } void HGCalPhotonIDValueMapProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; Handle<edm::View<reco::Photon>> photonsH; iEvent.getByToken(photonsToken_, photonsH); for(auto&& kv : maps_) { kv.second.clear(); kv.second.reserve(photonsH->size()); } phoIDHelper_->eventInit(iEvent,iSetup); for(const auto& pho : *photonsH) { if(pho.isEB()) { for(auto&& kv : maps_) { kv.second.push_back(0.); } } else { phoIDHelper_->computeHGCAL(pho, radius_); if (phoIDHelper_->sigmaUU() == -1){ for(auto&& kv : maps_) { kv.second.push_back(0.); } continue; } hgcal::LongDeps ld(phoIDHelper_->energyPerLayer(radius_, true)); float measuredDepth, expectedDepth, expectedSigma; float depthCompatibility = phoIDHelper_->clusterDepthCompatibility(ld, measuredDepth, expectedDepth, expectedSigma); float seed_tot_energy = ld.energyEE() + ld.energyFH() + ld.energyBH(); const double div_cosh_eta = pho.superCluster()->seed()->position().rho() / pho.superCluster()->seed()->position().r(); maps_["seedEt"].push_back(seed_tot_energy * div_cosh_eta ); maps_["seedEnergy"].push_back(seed_tot_energy); maps_["seedEnergyEE"].push_back(ld.energyEE()); maps_["seedEnergyFH"].push_back(ld.energyFH()); maps_["seedEnergyBH"].push_back(ld.energyBH()); maps_["pcaEig1"].push_back(phoIDHelper_->eigenValues()(0)); maps_["pcaEig2"].push_back(phoIDHelper_->eigenValues()(1)); maps_["pcaEig3"].push_back(phoIDHelper_->eigenValues()(2)); maps_["pcaSig1"].push_back(phoIDHelper_->sigmas()(0)); maps_["pcaSig2"].push_back(phoIDHelper_->sigmas()(1)); maps_["pcaSig3"].push_back(phoIDHelper_->sigmas()(2)); maps_["sigmaUU"].push_back(phoIDHelper_->sigmaUU()); maps_["sigmaVV"].push_back(phoIDHelper_->sigmaVV()); maps_["sigmaEE"].push_back(phoIDHelper_->sigmaEE()); maps_["sigmaPP"].push_back(phoIDHelper_->sigmaPP()); maps_["nLayers"].push_back(ld.nLayers()); maps_["firstLayer"].push_back(ld.firstLayer()); maps_["lastLayer"].push_back(ld.lastLayer()); maps_["e4oEtot"].push_back(ld.e4oEtot()); maps_["layerEfrac10"].push_back(ld.layerEfrac10()); maps_["layerEfrac90"].push_back(ld.layerEfrac90()); maps_["measuredDepth"].push_back(measuredDepth); maps_["expectedDepth"].push_back(expectedDepth); maps_["expectedSigma"].push_back(expectedSigma); maps_["depthCompatibility"].push_back(depthCompatibility); maps_["caloIsoRing0"].push_back(phoIDHelper_->getIsolationRing(0)); maps_["caloIsoRing1"].push_back(phoIDHelper_->getIsolationRing(1)); maps_["caloIsoRing2"].push_back(phoIDHelper_->getIsolationRing(2)); maps_["caloIsoRing3"].push_back(phoIDHelper_->getIsolationRing(3)); maps_["caloIsoRing4"].push_back(phoIDHelper_->getIsolationRing(4)); } } if ( maps_.size() != valuesProduced_.size() ) { throw cms::Exception("HGCalPhotonIDValueMapProducer") << "We have a miscoded value map producer, since map size changed"; } for(auto&& kv : maps_) { if ( kv.second.size() != photonsH->size() ) { throw cms::Exception("HGCalPhotonIDValueMapProducer") << "We have a miscoded value map producer, since the variable " << kv.first << " wasn't filled."; } auto out = std::make_unique<edm::ValueMap<float>>(); edm::ValueMap<float>::Filler filler(*out); filler.insert(photonsH, kv.second.begin(), kv.second.end()); filler.fill(); iEvent.put(std::move(out), kv.first); } } void HGCalPhotonIDValueMapProducer::beginStream(edm::StreamID) { } void HGCalPhotonIDValueMapProducer::endStream() { } void HGCalPhotonIDValueMapProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("photons", edm::InputTag("photonsFromMultiCl")); desc.add<double>("pcaRadius", 3.0); desc.add<std::vector<std::string>>("variables", valuesProduced_); desc.add<std::vector<double>>("dEdXWeights")->setComment("This must be copied from dEdX_weights in RecoLocalCalo.HGCalRecProducers.HGCalRecHit_cfi"); desc.add<unsigned int>("isoNRings", 5); desc.add<double>("isoDeltaR", 0.15); desc.add<double>("isoDeltaRmin", 0.0); desc.add<edm::InputTag>("EERecHits", edm::InputTag("HGCalRecHit","HGCEERecHits")); desc.add<edm::InputTag>("FHRecHits", edm::InputTag("HGCalRecHit","HGCHEFRecHits")); desc.add<edm::InputTag>("BHRecHits", edm::InputTag("HGCalRecHit","HGCHEBRecHits")); descriptions.add("hgcalPhotonIDValueMap", desc); } DEFINE_FWK_MODULE(HGCalPhotonIDValueMapProducer);
#include <memory> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/StreamID.h" #include "DataFormats/Common/interface/ValueMap.h" #include "DataFormats/EgammaCandidates/interface/Photon.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" #include "RecoEgamma/EgammaTools/interface/HGCalEgammaIDHelper.h" #include "RecoEgamma/EgammaTools/interface/LongDeps.h" class HGCalPhotonIDValueMapProducer : public edm::stream::EDProducer<> { public: explicit HGCalPhotonIDValueMapProducer(const edm::ParameterSet&); ~HGCalPhotonIDValueMapProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void beginStream(edm::StreamID) override; void produce(edm::Event&, const edm::EventSetup&) override; void endStream() override; edm::EDGetTokenT<edm::View<reco::Photon>> photonsToken_; float radius_; static const std::vector<std::string> valuesProduced_; std::map<const std::string, std::vector<float>> maps_; std::unique_ptr<HGCalEgammaIDHelper> phoIDHelper_; };
HGCalPhotonIDValueMapProducer::HGCalPhotonIDValueMapProducer(const edm::ParameterSet& iConfig) : photonsToken_(consumes<edm::View<reco::Photon>>(iConfig.getParameter<edm::InputTag>("photons"))), radius_(iConfig.getParameter<double>("pcaRadius")) { for(const auto& key : valuesProduced_) { maps_[key] = {}; produces<edm::ValueMap<float>>(key); } phoIDHelper_.reset(new HGCalEgammaIDHelper(iConfig, consumesCollector())); } HGCalPhotonIDValueMapProducer::~HGCalPhotonIDValueMapProducer() { } void HGCalPhotonIDValueMapProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; Handle<edm::View<reco::Photon>> photonsH; iEvent.getByToken(photonsToken_, photonsH); for(auto&& kv : maps_) { kv.second.clear(); kv.second.reserve(photonsH->size()); } phoIDHelper_->eventInit(iEvent,iSetup); for(const auto& pho : *photonsH) { if(pho.isEB()) { for(auto&& kv : maps_) { kv.second.push_back(0.); } } else { phoIDHelper_->computeHGCAL(pho, radius_); if (phoIDHelper_->sigmaUU() == -1){ for(auto&& kv : maps_) { kv.second.push_back(0.); } continue; } hgcal::LongDeps ld(phoIDHelper_->energyPerLayer(radius_, true)); float measuredDepth, expectedDepth, expectedSigma; float depthCompatibility = phoIDHelper_->clusterDepthCompatibility(ld, measuredDepth, expectedDepth, expectedSigma); float seed_tot_energy = ld.energyEE() + ld.energyFH() + ld.energyBH(); const double div_cosh_eta = pho.superCluster()->seed()->position().rho() / pho.superCluster()->seed()->position().r(); maps_["seedEt"].push_back(seed_tot_energy * div_cosh_eta ); maps_["seedEnergy"].push_back(seed_tot_energy); maps_["seedEnergyEE"].push_back(ld.energyEE()); maps_["seedEnergyFH"].push_back(ld.energyFH()); maps_["seedEnergyBH"].push_back(ld.energyBH()); maps_["pcaEig1"].push_back(phoIDHelper_->eigenValues()(0)); maps_["pcaEig2"].push_back(phoIDHelper_->eigenValues()(1)); maps_["pcaEig3"].push_back(phoIDHelper_->eigenValues()(2)); maps_["pcaSig1"].push_back(phoIDHelper_->sigmas()(0)); maps_["pcaSig2"].push_back(phoIDHelper_->sigmas()(1)); maps_["pcaSig3"].push_back(phoIDHelper_->sigmas()(2)); maps_["sigmaUU"].push_back(phoIDHelper_->sigmaUU()); maps_["sigmaVV"].push_back(phoIDHelper_->sigmaVV()); maps_["sigmaEE"].push_back(phoIDHelper_->sigmaEE()); maps_["sigmaPP"].push_back(phoIDHelper_->sigmaPP()); maps_["nLayers"].push_back(ld.nLayers()); maps_["firstLayer"].push_back(ld.firstLayer()); maps_["lastLayer"].push_back(ld.lastLayer()); maps_["e4oEtot"].push_back(ld.e4oEtot()); maps_["layerEfrac10"].push_back(ld.layerEfrac10()); maps_["layerEfrac90"].push_back(ld.layerEfrac90()); maps_["measuredDepth"].push_back(measuredDepth); maps_["expectedDepth"].push_back(expectedDepth); maps_["expectedSigma"].push_back(expectedSigma); maps_["depthCompatibility"].push_back(depthCompatibility); maps_["caloIsoRing0"].push_back(phoIDHelper_->getIsolationRing(0)); maps_["caloIsoRing1"].push_back(phoIDHelper_->getIsolationRing(1)); maps_["caloIsoRing2"].push_back(phoIDHelper_->getIsolationRing(2)); maps_["caloIsoRing3"].push_back(phoIDHelper_->getIsolationRing(3)); maps_["caloIsoRing4"].push_back(phoIDHelper_->getIsolationRing(4)); } } if ( maps_.size() != valuesProduced_.size() ) { throw cms::Exception("HGCalPhotonIDValueMapProducer") << "We have a miscoded value map producer, since map size changed"; } for(auto&& kv : maps_) { if ( kv.second.size() != photonsH->size() ) { throw cms::Exception("HGCalPhotonIDValueMapProducer") << "We have a miscoded value map producer, since the variable " << kv.first << " wasn't filled."; } auto out = std::make_unique<edm::ValueMap<float>>(); edm::ValueMap<float>::Filler filler(*out); filler.insert(photonsH, kv.second.begin(), kv.second.end()); filler.fill(); iEvent.put(std::move(out), kv.first); } } void HGCalPhotonIDValueMapProducer::beginStream(edm::StreamID) { } void HGCalPhotonIDValueMapProducer::endStream() { } void HGCalPhotonIDValueMapProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("photons", edm::InputTag("photonsFromMultiCl")); desc.add<double>("pcaRadius", 3.0); desc.add<std::vector<std::string>>("variables", valuesProduced_); desc.add<std::vector<double>>("dEdXWeights")->setComment("This must be copied from dEdX_weights in RecoLocalCalo.HGCalRecProducers.HGCalRecHit_cfi"); desc.add<unsigned int>("isoNRings", 5); desc.add<double>("isoDeltaR", 0.15); desc.add<double>("isoDeltaRmin", 0.0); desc.add<edm::InputTag>("EERecHits", edm::InputTag("HGCalRecHit","HGCEERecHits")); desc.add<edm::InputTag>("FHRecHits", edm::InputTag("HGCalRecHit","HGCHEFRecHits")); desc.add<edm::InputTag>("BHRecHits", edm::InputTag("HGCalRecHit","HGCHEBRecHits")); descriptions.add("hgcalPhotonIDValueMap", desc); } DEFINE_FWK_MODULE(HGCalPhotonIDValueMapProducer);
const std::vector<std::string> HGCalPhotonIDValueMapProducer::valuesProduced_ = { "seedEt", "seedEnergy", "seedEnergyEE", "seedEnergyFH", "seedEnergyBH", "pcaEig1", "pcaEig2", "pcaEig3", "pcaSig1", "pcaSig2", "pcaSig3", "sigmaUU", "sigmaVV", "sigmaEE", "sigmaPP", "nLayers", "firstLayer", "lastLayer", "e4oEtot", "layerEfrac10", "layerEfrac90", "measuredDepth", "expectedDepth", "expectedSigma", "depthCompatibility", "caloIsoRing0", "caloIsoRing1", "caloIsoRing2", "caloIsoRing3", "caloIsoRing4", };
assignment_statement
[]
C++
google/cloud/dialogflow_cx/internal/flows_logging_decorator.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
#include "google/cloud/dialogflow_cx/internal/flows_logging_decorator.h" #include "google/cloud/internal/log_wrapper.h" #include "google/cloud/status_or.h" #include <google/cloud/dialogflow/cx/v3/flow.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace dialogflow_cx_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN FlowsLogging::FlowsLogging(std::shared_ptr<FlowsStub> child, TracingOptions tracing_options, std::set<std::string> components) : child_(std::move(child)), tracing_options_(std::move(tracing_options)), components_(std::move(components)) {} StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::CreateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::CreateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::CreateFlowRequest const& request) { return child_->CreateFlow(context, request); }, context, request, __func__, tracing_options_); } Status FlowsLogging::DeleteFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::DeleteFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::DeleteFlowRequest const& request) { return child_->DeleteFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::ListFlowsResponse> FlowsLogging::ListFlows( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListFlowsRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListFlowsRequest const& request) { return child_->ListFlows(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::GetFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowRequest const& request) { return child_->GetFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::UpdateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::UpdateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::UpdateFlowRequest const& request) { return child_->UpdateFlow(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncTrainFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::TrainFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::TrainFlowRequest const& request) { return child_->AsyncTrainFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::FlowValidationResult> FlowsLogging::ValidateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ValidateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ValidateFlowRequest const& request) { return child_->ValidateFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::FlowValidationResult> FlowsLogging::GetFlowValidationResult( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowValidationResultRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3:: GetFlowValidationResultRequest const& request) { return child_->GetFlowValidationResult(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncImportFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ImportFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ImportFlowRequest const& request) { return child_->AsyncImportFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncExportFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ExportFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ExportFlowRequest const& request) { return child_->AsyncExportFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return child_->AsyncGetOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<Status> FlowsLogging::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return child_->AsyncCancelOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } } }
#include "google/cloud/dialogflow_cx/internal/flows_logging_decorator.h" #include "google/cloud/internal/log_wrapper.h" #include "google/cloud/status_or.h" #include <google/cloud/dialogflow/cx/v3/flow.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace dialogflow_cx_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN FlowsLogging::FlowsLogging(std::shared_ptr<FlowsStub> child, TracingOptions tracing_options, std::set<std::string> components) : child_(std::move(child)), tracing_options_(std::move(tracing_options)), components_(std::move(components)) {} StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::CreateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::CreateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::CreateFlowRequest const& request) { return child_->CreateFlow(context, request); }, context, request, __func__, tracing_options_); } Status FlowsLogging::DeleteFlow( grpc::ClientContext& co
text, google::cloud::dialogflow::cx::v3::ExportFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ExportFlowRequest const& request) { return child_->AsyncExportFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return child_->AsyncGetOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<Status> FlowsLogging::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return google::cloud::internal::LogWrapper( [this](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return child_->AsyncCancelOperation(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } } }
ntext, google::cloud::dialogflow::cx::v3::DeleteFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::DeleteFlowRequest const& request) { return child_->DeleteFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::ListFlowsResponse> FlowsLogging::ListFlows( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListFlowsRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ListFlowsRequest const& request) { return child_->ListFlows(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::GetFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowRequest const& request) { return child_->GetFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::Flow> FlowsLogging::UpdateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::UpdateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::UpdateFlowRequest const& request) { return child_->UpdateFlow(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncTrainFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::TrainFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::TrainFlowRequest const& request) { return child_->AsyncTrainFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::FlowValidationResult> FlowsLogging::ValidateFlow( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ValidateFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::ValidateFlowRequest const& request) { return child_->ValidateFlow(context, request); }, context, request, __func__, tracing_options_); } StatusOr<google::cloud::dialogflow::cx::v3::FlowValidationResult> FlowsLogging::GetFlowValidationResult( grpc::ClientContext& context, google::cloud::dialogflow::cx::v3::GetFlowValidationResultRequest const& request) { return google::cloud::internal::LogWrapper( [this](grpc::ClientContext& context, google::cloud::dialogflow::cx::v3:: GetFlowValidationResultRequest const& request) { return child_->GetFlowValidationResult(context, request); }, context, request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncImportFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ImportFlowRequest const& request) { return google::cloud::internal::LogWrapper( [this]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::cloud::dialogflow::cx::v3::ImportFlowRequest const& request) { return child_->AsyncImportFlow(cq, std::move(context), request); }, cq, std::move(context), request, __func__, tracing_options_); } future<StatusOr<google::longrunning::Operation>> FlowsLogging::AsyncExportFlow( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> con
random
[ { "content": "// A generic request. Fields with a \"testonly_\" prefix are used for testing but\n\n// are not used in the real code.\n\nstruct Request {\n\n std::string testonly_page_token;\n\n void set_page_token(std::string token) {\n\n testonly_page_token = std::move(token);\n\n }\n\n};\n\n\n", "fi...
C++
source/XMPFiles/FileHandlers/TIFF_Handler.cpp
maemo-foss/maemo-package-exempi
684c589c987a1b9f01a1d60114363ce8326c2be5
#include "TIFF_Handler.hpp" #include "TIFF_Support.hpp" #include "PSIR_Support.hpp" #include "IPTC_Support.hpp" #include "ReconcileLegacy.hpp" #include "MD5.h" using namespace std; bool TIFF_CheckFormat ( XMP_FileFormat format, XMP_StringPtr filePath, LFA_FileRef fileRef, XMPFiles * parent ) { IgnoreParam(format); IgnoreParam(filePath); IgnoreParam(parent); XMP_Assert ( format == kXMP_TIFFFile ); enum { kMinimalTIFFSize = 4+4+2+12+4 }; IOBuffer ioBuf; LFA_Seek ( fileRef, 0, SEEK_SET ); if ( ! CheckFileSpace ( fileRef, &ioBuf, kMinimalTIFFSize ) ) return false; bool leTIFF = CheckBytes ( ioBuf.ptr, "\x49\x49\x2A\x00", 4 ); bool beTIFF = CheckBytes ( ioBuf.ptr, "\x4D\x4D\x00\x2A", 4 ); return (leTIFF | beTIFF); } XMPFileHandler * TIFF_MetaHandlerCTor ( XMPFiles * parent ) { return new TIFF_MetaHandler ( parent ); } TIFF_MetaHandler::TIFF_MetaHandler ( XMPFiles * _parent ) : psirMgr(0), iptcMgr(0) { this->parent = _parent; this->handlerFlags = kTIFF_HandlerFlags; this->stdCharForm = kXMP_Char8Bit; } TIFF_MetaHandler::~TIFF_MetaHandler() { if ( this->psirMgr != 0 ) delete ( this->psirMgr ); if ( this->iptcMgr != 0 ) delete ( this->iptcMgr ); } void TIFF_MetaHandler::CacheFileData() { LFA_FileRef fileRef = this->parent->fileRef; XMP_PacketInfo & packetInfo = this->packetInfo; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; const bool checkAbort = (abortProc != 0); XMP_Assert ( (! this->containsXMP) && (! this->containsTNail) ); if ( checkAbort && abortProc(abortArg) ) { XMP_Throw ( "TIFF_MetaHandler::CacheFileData - User abort", kXMPErr_UserAbort ); } this->tiffMgr.ParseFileStream ( fileRef ); TIFF_Manager::TagInfo dngInfo; if ( this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_DNGVersion, &dngInfo ) ) { XMP_Uns8 majorVersion = *((XMP_Uns8*)dngInfo.dataPtr); if ( this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_DNGBackwardVersion, &dngInfo ) ) { majorVersion = *((XMP_Uns8*)dngInfo.dataPtr); } if ( majorVersion > 1 ) XMP_Throw ( "DNG version beyond 1.x", kXMPErr_BadTIFF ); } TIFF_Manager::TagInfo xmpInfo; bool found = this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_XMP, &xmpInfo ); if ( found ) { this->packetInfo.offset = this->tiffMgr.GetValueOffset ( kTIFF_PrimaryIFD, kTIFF_XMP ); this->packetInfo.length = xmpInfo.dataLen; this->packetInfo.padSize = 0; this->packetInfo.charForm = kXMP_CharUnknown; this->packetInfo.writeable = true; this->xmpPacket.assign ( (XMP_StringPtr)xmpInfo.dataPtr, xmpInfo.dataLen ); this->containsXMP = true; } } void TIFF_MetaHandler::ProcessTNail() { this->processedTNail = true; this->containsTNail = false; this->containsTNail = this->tiffMgr.GetTNailInfo ( &this->tnailInfo ); if ( this->containsTNail ) this->tnailInfo.fileFormat = this->parent->format; } void TIFF_MetaHandler::ProcessXMP() { this->processedXMP = true; bool found; RecJTP_LegacyPriority lastLegacy = kLegacyJTP_None; bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0); if ( readOnly ) { this->psirMgr = new PSIR_MemoryReader(); this->iptcMgr = new IPTC_Reader(); } else { this->psirMgr = new PSIR_FileWriter(); #if ! XMP_UNIXBuild this->iptcMgr = new IPTC_Writer(); #else this->iptcMgr = new IPTC_Reader(); #endif } TIFF_Manager & tiff = this->tiffMgr; PSIR_Manager & psir = *this->psirMgr; IPTC_Manager & iptc = *this->iptcMgr; TIFF_Manager::TagInfo psirInfo; bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo ); TIFF_Manager::TagInfo iptcInfo; bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); if ( havePSIR ) { psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen ); PSIR_Manager::ImgRsrcInfo buriedExif; found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif ); if ( found ) { tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen ); if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif ); } } if ( haveIPTC ) { iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); lastLegacy = kLegacyJTP_TIFF_IPTC; } if ( lastLegacy < kLegacyJTP_TIFF_TIFF_Tags ) { found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_ImageDescription, 0 ); if ( ! found ) found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_Artist, 0 ); if ( ! found ) found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_Copyright, 0 ); if ( found ) lastLegacy = kLegacyJTP_TIFF_TIFF_Tags; } if ( havePSIR ) { if ( lastLegacy < kLegacyJTP_PSIR_OldCaption ) { found = psir.GetImgRsrc ( kPSIR_OldCaption, 0 ); if ( ! found ) found = psir.GetImgRsrc ( kPSIR_OldCaptionPStr, 0 ); if ( found ) lastLegacy = kLegacyJTP_PSIR_OldCaption; } if ( ! haveIPTC ) { PSIR_Manager::ImgRsrcInfo iptcInfo; haveIPTC = psir.GetImgRsrc ( kPSIR_IPTC, &iptcInfo ); if ( haveIPTC ) { iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); if ( lastLegacy < kLegacyJTP_PSIR_IPTC ) lastLegacy = kLegacyJTP_PSIR_IPTC; } } } XMP_OptionBits options = k2XMP_FileHadExif; if ( this->containsXMP ) options |= k2XMP_FileHadXMP; if ( haveIPTC || (lastLegacy == kLegacyJTP_PSIR_OldCaption) ) options |= k2XMP_FileHadIPTC; if ( ! this->xmpPacket.empty() ) { XMP_Assert ( this->containsXMP ); XMP_StringPtr packetStr = this->xmpPacket.c_str(); XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size(); try { this->xmpObj.ParseFromBuffer ( packetStr, packetLen ); } catch ( ... ) { XMP_ClearOption ( options, k2XMP_FileHadXMP ); ImportJTPtoXMP ( kXMP_TIFFFile, lastLegacy, &tiff, psir, &iptc, &this->xmpObj, options ); throw; } } ImportJTPtoXMP ( kXMP_TIFFFile, lastLegacy, &tiff, psir, &iptc, &this->xmpObj, options ); this->containsXMP = true; } void TIFF_MetaHandler::UpdateFile ( bool doSafeUpdate ) { XMP_Assert ( ! doSafeUpdate ); LFA_FileRef destRef = this->parent->fileRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; ExportXMPtoJTP ( kXMP_TIFFFile, &this->xmpObj, &this->tiffMgr, this->psirMgr, this->iptcMgr ); XMP_Int64 oldPacketOffset = this->packetInfo.offset; XMP_Int32 oldPacketLength = this->packetInfo.length; if ( oldPacketOffset == kXMPFiles_UnknownOffset ) oldPacketOffset = 0; if ( oldPacketLength == kXMPFiles_UnknownLength ) oldPacketLength = 0; bool doInPlace = (this->xmpPacket.size() <= (size_t)this->packetInfo.length); if ( this->tiffMgr.IsLegacyChanged() ) doInPlace = false; if ( doInPlace ) { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", TIFF in-place update"; #endif if ( this->xmpPacket.size() < (size_t)this->packetInfo.length ) { size_t extraSpace = (size_t)this->packetInfo.length - this->xmpPacket.size(); this->xmpPacket.append ( extraSpace, ' ' ); } LFA_FileRef liveFile = this->parent->fileRef; XMP_Assert ( this->xmpPacket.size() == (size_t)oldPacketLength ); LFA_Seek ( liveFile, oldPacketOffset, SEEK_SET ); LFA_Write ( liveFile, this->xmpPacket.c_str(), (XMP_Int32)this->xmpPacket.size() ); } else { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", TIFF append update"; #endif this->xmpObj.SerializeToBuffer ( &this->xmpPacket, kXMP_UseCompactFormat ); this->packetInfo.offset = kXMPFiles_UnknownOffset; this->packetInfo.length = (XMP_Int32)this->xmpPacket.size(); FillPacketInfo ( this->xmpPacket, &this->packetInfo ); this->tiffMgr.SetTag ( kTIFF_PrimaryIFD, kTIFF_XMP, kTIFF_ByteType, (XMP_Uns32)this->xmpPacket.size(), this->xmpPacket.c_str() ); this->tiffMgr.UpdateFileStream ( destRef ); } this->needsUpdate = false; } void TIFF_MetaHandler::WriteFile ( LFA_FileRef sourceRef, const std::string & sourcePath ) { LFA_FileRef destRef = this->parent->fileRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; XMP_Int64 fileLen = LFA_Measure ( sourceRef ); if ( fileLen > 0xFFFFFFFFLL ) { XMP_Throw ( "TIFF fles can't exceed 4GB", kXMPErr_BadTIFF ); } LFA_Seek ( sourceRef, 0, SEEK_SET ); LFA_Truncate ( destRef, 0 ); LFA_Copy ( sourceRef, destRef, fileLen, abortProc, abortArg ); this->UpdateFile ( false ); }
#include "TIFF_Handler.hpp" #include "TIFF_Support.hpp" #include "PSIR_Support.hpp" #include "IPTC_Support.hpp" #include "ReconcileLegacy.hpp" #include "MD5.h" using namespace std; bool TIFF_CheckFormat ( XMP_FileFormat format, XMP_StringPtr filePath, LFA_FileRef fileRef, XMPFiles * parent ) { IgnoreParam(format); IgnoreParam(filePath); IgnoreParam(parent); XMP_Assert ( format == kXMP_TIFFFile ); enum { kMinimalTIFFSize = 4+4+2+12+4 }; IOBuffer ioBuf; LFA_Seek ( fileRef, 0, SEEK_SET ); if ( ! CheckFileSpace ( fileRef, &ioBuf, kMinimalTIFFSize ) ) return false; bool leTIFF = CheckBytes ( ioBuf.ptr, "\x49\x49\x2A\x00", 4 ); bool beTIFF = CheckBytes ( ioBuf.ptr, "\x4D\x4D\x00\x2A", 4 ); return (leTIFF | beTIFF); } XMPFileHandler * TIFF_MetaHandlerCTor ( XMPFiles * parent ) { return new TIFF_MetaHandler ( parent ); }
TIFF_MetaHandler::~TIFF_MetaHandler() { if ( this->psirMgr != 0 ) delete ( this->psirMgr ); if ( this->iptcMgr != 0 ) delete ( this->iptcMgr ); } void TIFF_MetaHandler::CacheFileData() { LFA_FileRef fileRef = this->parent->fileRef; XMP_PacketInfo & packetInfo = this->packetInfo; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; const bool checkAbort = (abortProc != 0); XMP_Assert ( (! this->containsXMP) && (! this->containsTNail) ); if ( checkAbort && abortProc(abortArg) ) { XMP_Throw ( "TIFF_MetaHandler::CacheFileData - User abort", kXMPErr_UserAbort ); } this->tiffMgr.ParseFileStream ( fileRef ); TIFF_Manager::TagInfo dngInfo; if ( this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_DNGVersion, &dngInfo ) ) { XMP_Uns8 majorVersion = *((XMP_Uns8*)dngInfo.dataPtr); if ( this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_DNGBackwardVersion, &dngInfo ) ) { majorVersion = *((XMP_Uns8*)dngInfo.dataPtr); } if ( majorVersion > 1 ) XMP_Throw ( "DNG version beyond 1.x", kXMPErr_BadTIFF ); } TIFF_Manager::TagInfo xmpInfo; bool found = this->tiffMgr.GetTag ( kTIFF_PrimaryIFD, kTIFF_XMP, &xmpInfo ); if ( found ) { this->packetInfo.offset = this->tiffMgr.GetValueOffset ( kTIFF_PrimaryIFD, kTIFF_XMP ); this->packetInfo.length = xmpInfo.dataLen; this->packetInfo.padSize = 0; this->packetInfo.charForm = kXMP_CharUnknown; this->packetInfo.writeable = true; this->xmpPacket.assign ( (XMP_StringPtr)xmpInfo.dataPtr, xmpInfo.dataLen ); this->containsXMP = true; } } void TIFF_MetaHandler::ProcessTNail() { this->processedTNail = true; this->containsTNail = false; this->containsTNail = this->tiffMgr.GetTNailInfo ( &this->tnailInfo ); if ( this->containsTNail ) this->tnailInfo.fileFormat = this->parent->format; } void TIFF_MetaHandler::ProcessXMP() { this->processedXMP = true; bool found; RecJTP_LegacyPriority lastLegacy = kLegacyJTP_None; bool readOnly = ((this->parent->openFlags & kXMPFiles_OpenForUpdate) == 0); if ( readOnly ) { this->psirMgr = new PSIR_MemoryReader(); this->iptcMgr = new IPTC_Reader(); } else { this->psirMgr = new PSIR_FileWriter(); #if ! XMP_UNIXBuild this->iptcMgr = new IPTC_Writer(); #else this->iptcMgr = new IPTC_Reader(); #endif } TIFF_Manager & tiff = this->tiffMgr; PSIR_Manager & psir = *this->psirMgr; IPTC_Manager & iptc = *this->iptcMgr; TIFF_Manager::TagInfo psirInfo; bool havePSIR = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_PSIR, &psirInfo ); TIFF_Manager::TagInfo iptcInfo; bool haveIPTC = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_IPTC, &iptcInfo ); if ( havePSIR ) { psir.ParseMemoryResources ( psirInfo.dataPtr, psirInfo.dataLen ); PSIR_Manager::ImgRsrcInfo buriedExif; found = psir.GetImgRsrc ( kPSIR_Exif, &buriedExif ); if ( found ) { tiff.IntegrateFromPShop6 ( buriedExif.dataPtr, buriedExif.dataLen ); if ( ! readOnly ) psir.DeleteImgRsrc ( kPSIR_Exif ); } } if ( haveIPTC ) { iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); lastLegacy = kLegacyJTP_TIFF_IPTC; } if ( lastLegacy < kLegacyJTP_TIFF_TIFF_Tags ) { found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_ImageDescription, 0 ); if ( ! found ) found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_Artist, 0 ); if ( ! found ) found = tiff.GetTag ( kTIFF_PrimaryIFD, kTIFF_Copyright, 0 ); if ( found ) lastLegacy = kLegacyJTP_TIFF_TIFF_Tags; } if ( havePSIR ) { if ( lastLegacy < kLegacyJTP_PSIR_OldCaption ) { found = psir.GetImgRsrc ( kPSIR_OldCaption, 0 ); if ( ! found ) found = psir.GetImgRsrc ( kPSIR_OldCaptionPStr, 0 ); if ( found ) lastLegacy = kLegacyJTP_PSIR_OldCaption; } if ( ! haveIPTC ) { PSIR_Manager::ImgRsrcInfo iptcInfo; haveIPTC = psir.GetImgRsrc ( kPSIR_IPTC, &iptcInfo ); if ( haveIPTC ) { iptc.ParseMemoryDataSets ( iptcInfo.dataPtr, iptcInfo.dataLen ); if ( lastLegacy < kLegacyJTP_PSIR_IPTC ) lastLegacy = kLegacyJTP_PSIR_IPTC; } } } XMP_OptionBits options = k2XMP_FileHadExif; if ( this->containsXMP ) options |= k2XMP_FileHadXMP; if ( haveIPTC || (lastLegacy == kLegacyJTP_PSIR_OldCaption) ) options |= k2XMP_FileHadIPTC; if ( ! this->xmpPacket.empty() ) { XMP_Assert ( this->containsXMP ); XMP_StringPtr packetStr = this->xmpPacket.c_str(); XMP_StringLen packetLen = (XMP_StringLen)this->xmpPacket.size(); try { this->xmpObj.ParseFromBuffer ( packetStr, packetLen ); } catch ( ... ) { XMP_ClearOption ( options, k2XMP_FileHadXMP ); ImportJTPtoXMP ( kXMP_TIFFFile, lastLegacy, &tiff, psir, &iptc, &this->xmpObj, options ); throw; } } ImportJTPtoXMP ( kXMP_TIFFFile, lastLegacy, &tiff, psir, &iptc, &this->xmpObj, options ); this->containsXMP = true; } void TIFF_MetaHandler::UpdateFile ( bool doSafeUpdate ) { XMP_Assert ( ! doSafeUpdate ); LFA_FileRef destRef = this->parent->fileRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; ExportXMPtoJTP ( kXMP_TIFFFile, &this->xmpObj, &this->tiffMgr, this->psirMgr, this->iptcMgr ); XMP_Int64 oldPacketOffset = this->packetInfo.offset; XMP_Int32 oldPacketLength = this->packetInfo.length; if ( oldPacketOffset == kXMPFiles_UnknownOffset ) oldPacketOffset = 0; if ( oldPacketLength == kXMPFiles_UnknownLength ) oldPacketLength = 0; bool doInPlace = (this->xmpPacket.size() <= (size_t)this->packetInfo.length); if ( this->tiffMgr.IsLegacyChanged() ) doInPlace = false; if ( doInPlace ) { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", TIFF in-place update"; #endif if ( this->xmpPacket.size() < (size_t)this->packetInfo.length ) { size_t extraSpace = (size_t)this->packetInfo.length - this->xmpPacket.size(); this->xmpPacket.append ( extraSpace, ' ' ); } LFA_FileRef liveFile = this->parent->fileRef; XMP_Assert ( this->xmpPacket.size() == (size_t)oldPacketLength ); LFA_Seek ( liveFile, oldPacketOffset, SEEK_SET ); LFA_Write ( liveFile, this->xmpPacket.c_str(), (XMP_Int32)this->xmpPacket.size() ); } else { #if GatherPerformanceData sAPIPerf->back().extraInfo += ", TIFF append update"; #endif this->xmpObj.SerializeToBuffer ( &this->xmpPacket, kXMP_UseCompactFormat ); this->packetInfo.offset = kXMPFiles_UnknownOffset; this->packetInfo.length = (XMP_Int32)this->xmpPacket.size(); FillPacketInfo ( this->xmpPacket, &this->packetInfo ); this->tiffMgr.SetTag ( kTIFF_PrimaryIFD, kTIFF_XMP, kTIFF_ByteType, (XMP_Uns32)this->xmpPacket.size(), this->xmpPacket.c_str() ); this->tiffMgr.UpdateFileStream ( destRef ); } this->needsUpdate = false; } void TIFF_MetaHandler::WriteFile ( LFA_FileRef sourceRef, const std::string & sourcePath ) { LFA_FileRef destRef = this->parent->fileRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; XMP_Int64 fileLen = LFA_Measure ( sourceRef ); if ( fileLen > 0xFFFFFFFFLL ) { XMP_Throw ( "TIFF fles can't exceed 4GB", kXMPErr_BadTIFF ); } LFA_Seek ( sourceRef, 0, SEEK_SET ); LFA_Truncate ( destRef, 0 ); LFA_Copy ( sourceRef, destRef, fileLen, abortProc, abortArg ); this->UpdateFile ( false ); }
TIFF_MetaHandler::TIFF_MetaHandler ( XMPFiles * _parent ) : psirMgr(0), iptcMgr(0) { this->parent = _parent; this->handlerFlags = kTIFF_HandlerFlags; this->stdCharForm = kXMP_Char8Bit; }
function_block-full_function
[ { "content": "\tclass ScanError : public std::logic_error {\n\n\tpublic:\n\n\t\tScanError() throw() : std::logic_error ( \"\" ) {}\n\n\t\texplicit ScanError ( const char * message ) throw() : std::logic_error ( message ) {}\n\n\t\tvirtual ~ScanError() throw() {}\n\n\t};\n\n\n\nprivate:\t// XMPScanner\n\n\t\n", ...
C++
tests/test_cases/one_hot_gpu_test.cpp
intel/clDNN
c4ef3bd7b707fc386655cccf90e6c0420d1efec7
#include <gtest/gtest.h> #include <api/CPP/engine.hpp> #include <api/CPP/input_layout.hpp> #include <api/CPP/memory.hpp> #include <api/CPP/one_hot.hpp> #include <api/CPP/topology.hpp> #include <api/CPP/network.hpp> #include "test_utils/test_utils.h" #include <cstddef> using namespace cldnn; using namespace ::tests; template <typename T> VVVVF<T> one_hot_cpu(VVVVF<T> &input, uint16_t axis, int32_t one_hot_limit, int input_padding_y = 0, int input_padding_x = 0, int output_padding_y = 0, int output_padding_x = 0) { size_t padding_y = input_padding_y + output_padding_y; size_t padding_x = input_padding_x + output_padding_x; size_t out_sizes[4]; out_sizes[0] = input.size(); out_sizes[1] = input[0].size(); out_sizes[2] = input[0][0].size() + 2 * padding_y; out_sizes[3] = input[0][0][0].size() + 2 * padding_x; for (uint16_t i = 0; i < axis; ++i) out_sizes[i] = out_sizes[i + 1]; out_sizes[axis] = one_hot_limit; VVVVF<T> output(out_sizes[0], VVVF<T>(out_sizes[1], VVF<T>(out_sizes[2], VF<T>(out_sizes[3])))); switch (axis) { case 0: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][f][y][x] == (T)b ? 1 : 0; break; case 1: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][y][x] == (T)f ? 1 : 0; break; case 2: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][f][x] == (T)y ? 1 : 0; break; case 3: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][f][y] == (T)x ? 1 : 0; break; default: break; } return output; } template <typename T> void generic_one_hot_test_int(cldnn::format test_input_fmt, int input_b, int input_f, int input_y, int input_x, tensor shape, uint16_t one_hot_axis, int input_padding_y = 0, int input_padding_x = 0, int output_padding_y = 0, int output_padding_x = 0) { std::vector<tensor::value_type> output_dims = { shape.batch[0], shape.feature[0], shape.spatial[1], shape.spatial[0] }; int32_t one_hot_limit = output_dims[one_hot_axis]; int min_random = -2, max_random = one_hot_limit + 2; VVVVF<T> input_rnd = generate_random_4d<T>(input_b, input_f, input_y, input_x, min_random, max_random); VF<T> input_rnd_vec = flatten_4d<T>(test_input_fmt, input_rnd); const auto& engine = get_test_engine(); tensor input_tensor(input_b, input_f, input_x, input_y); auto input = memory::allocate(engine, { type_to_data_type<T>::value, test_input_fmt, input_tensor }); set_values(input, input_rnd_vec); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", shape, one_hot_axis)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "output"); auto output_memory = outputs.at("output").get_memory(); auto output_layout = output_memory.get_layout(); auto output_ptr = output_memory.pointer<T>(); VVVVF<T> output_cpu = one_hot_cpu<T>(input_rnd, one_hot_axis, one_hot_limit, input_padding_y, input_padding_x, output_padding_y, output_padding_x); EXPECT_EQ(output_layout.format.value, test_input_fmt.value); tensor output_tensor = output_layout.get_buffer_size(); int y_size = output_tensor.spatial[1]; int x_size = output_tensor.spatial[0]; int f_size = output_tensor.feature[0]; int b_size = output_tensor.batch[0]; EXPECT_EQ(y_size, (int)output_cpu[0][0].size()); EXPECT_EQ(x_size, (int)output_cpu[0][0][0].size()); EXPECT_EQ(f_size, (int)output_cpu[0].size()); EXPECT_EQ(b_size, (int)output_cpu.size()); bool test_is_correct = true; VF<T> output_cpu_vec = flatten_4d<T>(test_input_fmt, output_cpu); for (size_t i = 0; i < output_cpu_vec.size(); ++i) { if (output_cpu_vec[i] != output_ptr[i]) { test_is_correct = false; break; } } EXPECT_EQ(test_is_correct, true) << std::endl << "failing test parameters:" << std::endl << "input_b = " << input_b << std::endl << "input_f = " << input_f << std::endl << "input_y = " << input_y << std::endl << "input_x = " << input_x << std::endl << "one_hot_limit = " << one_hot_limit << std::endl << "one_hot_axis = " << one_hot_axis << std::endl << "input_padding_y = " << input_padding_y << std::endl << "input_padding_x = " << input_padding_x << std::endl << "output_padding_y = " << output_padding_y << std::endl << "output_padding_x = " << output_padding_x << std::endl; } TEST(one_hot_gpu_i32, generic_y_in10_oh5) { generic_one_hot_test_int<int32_t>(format::bfyx, 1, 10, 10, 10, tensor(10, 10, 10, 5), 2); } TEST(one_hot_error, basic_error_wrong_batch_size) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx, { 10, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(10, 1, 1, 50), 2)); std::string msg_to_find = "Incorrect parameters configuration: input batch size should be equal to 1."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); } TEST(one_hot_error, basic_error_wrong_axis) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx,{ 1, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(1, 1, 1, 50), 4)); std::string msg_to_find = "Incorrect parameters configuration: one_hot_axis should be less or equal to 3."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); } TEST(one_hot_error, basic_error_bad_shape) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx,{ 1, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(1, 5, 1, 50), 2)); std::string msg_to_find = "Incorrect parameters configuration: shape does not fit input size."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); }
#include <gtest/gtest.h> #include <api/CPP/engine.hpp> #include <api/CPP/input_layout.hpp> #include <api/CPP/memory.hpp> #include <api/CPP/one_hot.hpp> #include <api/CPP/topology.hpp> #include <api/CPP/network.hpp> #include "test_utils/test_utils.h" #include <cstddef> using namespace cldnn; using namespace ::tests; template <typename T> VVVVF<T> one_hot_cpu(VVVVF<T> &input, uint16_t axis, int32_t one_hot_limit, int input_padding_y = 0, int input_padding_x = 0, int output_padding_y = 0, int output_padding_x = 0) { size_t padding_y = input_padding_y + output_padding_y; size_t padding_x = input_padding_x + output_padding_x; size_t out_sizes[4]; out_sizes[0] = input.size(); out_sizes[1] = input[0].size(); out_sizes[2] = input[0][0].size() + 2 * padding_y; out_sizes[3] = input[0][0][0].size() + 2 * padding_x; for (uint16_t i = 0; i < axis; ++i) out_sizes[i] = out_sizes[i + 1]; out_sizes[axis] = one_hot_limit; VVVVF<T> output(out_sizes[0], VVVF<T>(out_sizes[1], VVF<T>(out_sizes[2], VF<T>(out_sizes[3])))); switch (axis) { case 0: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][f][y][x] == (T)b ? 1 : 0; break; case 1: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][y][x] == (T)f ? 1 : 0; break; case 2: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][f][x] == (T)y ? 1 : 0; break; case 3: for (size_t b = 0; b < out_sizes[0]; ++b) for (size_t f = 0; f < out_sizes[1]; ++f) for (size_t y = 0; y < out_sizes[2]; ++y) for (size_t x = 0; x < out_sizes[3]; ++x) output[b][f][y][x] = input[0][b][f][y] == (T)x ? 1 : 0; break; default: break; } return output; } template <typename T> void generic_one_hot_test_int(cldnn::format test_input_fmt, int input_b, int input_f, int input_y, int input_x, tensor shape, uint16_t one_hot_axis, int input_padding_y = 0, int input_padding_x = 0, int output_padding_y = 0, int output_padding_x = 0) { std::vector<tensor::value_type> output_dims = { shape.batch[0], shape.feature[0], shape.spatial[1], shape.spatial[0] }; int32_t one_hot_limit = output_dims[one_hot_axis]; int min_random = -2, max_random = one_hot_limit + 2; VVVVF<T> input_rnd = generate_random_4d<T>(input_b, input_f, input_y, input_x, min_random, max_random); VF<T> input_rnd_vec = flatten_4d<T>(test_input_fmt, input_rnd); const auto& engine = get_test_engine(); tensor input_tensor(input_b, input_f, input_x, input_y); auto input = memory::allocate(engine, { type_to_data_type<T>::value, test_input_fmt, input_tensor }); set_values(input, input_rnd_vec); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", shape, one_hot_axis)); network network(engine, topology); network.set_input_data("input", input); auto outputs = network.execute(); EXPECT_EQ(outputs.size(), size_t(1)); EXPECT_EQ(outputs.begin()->first, "output"); auto output_memory = outputs.at("output").get_memory(); auto output_layout = output_memory.get_layout(); auto output_ptr = output_memory.pointer<T>(); VVVVF<T> output_cpu = one_hot_cpu<T>(input_rnd, one_hot_axis, one_hot_limit, input_padding_y, input_padding_x, output_padding_y, output_padding_x); EXPECT_EQ(output_layout.format.value, test_input_fmt.value); tensor output_tensor = output_layout.get_buffer_size(); int y_size = output_tensor.spatial[1]; int x_size = output_tensor.spatial[0]; int f_size = output_tensor.feature[0]; int b_size = output_tensor.batch[0]; EXPECT_EQ(y_size, (int)output_cpu[0][0].size()); EXPECT_EQ(x_size, (int)output_cpu[0][0][0].size()); EXPECT_EQ(f_size, (int)output_cpu[0].size()); EXPECT_EQ(b_size, (int)output_cpu.size()); bool test_is_correct = true; VF<T> output_cpu_vec = flatten_4d<T>(test_input_fmt, output_cpu); for (size_t i = 0; i < output_cpu_vec.size(); ++i) { if (output_cpu_vec[i] != output_ptr[i]) { test_is_correct = false; break; } } EXPECT_EQ(test_is_correct, true) << std::endl << "failing test parameters:" << std::endl << "input_b = " << input_b << std::endl << "input_f = " << input_f << std::endl << "input_y = " << input_y << std::endl << "input_x = " << input_x << std::endl << "one_hot_limit = " << one_hot_limit << std::endl << "one_hot_axis = " << one_hot_axis << std::endl << "input_padding_y = " << input_padding_y << std::endl << "input_padding_x = " << input_padding_x << std::endl << "output_padding_y = " << output_padding_y << std::endl << "output_padding_x = " << output_padding_x << std::endl; } TEST(one_hot_gpu_i32, generic_y_in10_oh5) { generic_one_hot_test_int<int32_t>(format::bfyx, 1, 10, 10, 10, tensor(10, 10, 10, 5), 2); } TEST(one_hot_error, basic_error_wrong_batch_size) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx, { 10, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_
TEST(one_hot_error, basic_error_wrong_axis) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx,{ 1, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(1, 1, 1, 50), 4)); std::string msg_to_find = "Incorrect parameters configuration: one_hot_axis should be less or equal to 3."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); } TEST(one_hot_error, basic_error_bad_shape) { const auto& engine = get_test_engine(); auto input = memory::allocate(engine, { data_types::i32, format::bfyx,{ 1, 1, 1, 1 } }); topology topology; topology.add(input_layout("input", input.get_layout())); topology.add(one_hot("output", "input", tensor(1, 5, 1, 50), 2)); std::string msg_to_find = "Incorrect parameters configuration: shape does not fit input size."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); }
layout())); topology.add(one_hot("output", "input", tensor(10, 1, 1, 50), 2)); std::string msg_to_find = "Incorrect parameters configuration: input batch size should be equal to 1."; EXPECT_ANY_THROW(check_exception_massage(engine, topology, msg_to_find)); }
function_block-function_prefixed
[ { "content": "#include \"api/CPP/scale_grad_input.hpp\"\n\n#include <api/CPP/topology.hpp>\n\n#include <api/CPP/network.hpp>\n\n#include <api/CPP/engine.hpp>\n\n#include \"test_utils/test_utils.h\"\n\n\n\n#include <iostream>\n\n\n\nusing namespace cldnn;\n\nusing namespace tests;\n\n\n\nTEST(scale_grad_input_gp...
C++
qt-creator-opensource-src-4.6.1/src/libs/qmljs/qmljsutils.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
#include "qmljsutils.h" #include "parser/qmljsast_p.h" #include <QColor> #include <QDir> #include <QRegularExpression> using namespace QmlJS; using namespace QmlJS::AST; namespace { class SharedData { public: SharedData() { validBuiltinPropertyNames.insert(QLatin1String("action")); validBuiltinPropertyNames.insert(QLatin1String("bool")); validBuiltinPropertyNames.insert(QLatin1String("color")); validBuiltinPropertyNames.insert(QLatin1String("date")); validBuiltinPropertyNames.insert(QLatin1String("double")); validBuiltinPropertyNames.insert(QLatin1String("enumeration")); validBuiltinPropertyNames.insert(QLatin1String("font")); validBuiltinPropertyNames.insert(QLatin1String("int")); validBuiltinPropertyNames.insert(QLatin1String("list")); validBuiltinPropertyNames.insert(QLatin1String("point")); validBuiltinPropertyNames.insert(QLatin1String("real")); validBuiltinPropertyNames.insert(QLatin1String("rect")); validBuiltinPropertyNames.insert(QLatin1String("size")); validBuiltinPropertyNames.insert(QLatin1String("string")); validBuiltinPropertyNames.insert(QLatin1String("time")); validBuiltinPropertyNames.insert(QLatin1String("url")); validBuiltinPropertyNames.insert(QLatin1String("var")); validBuiltinPropertyNames.insert(QLatin1String("variant")); validBuiltinPropertyNames.insert(QLatin1String("vector2d")); validBuiltinPropertyNames.insert(QLatin1String("vector3d")); validBuiltinPropertyNames.insert(QLatin1String("vector4d")); validBuiltinPropertyNames.insert(QLatin1String("quaternion")); validBuiltinPropertyNames.insert(QLatin1String("matrix4x4")); validBuiltinPropertyNames.insert(QLatin1String("alias")); } QSet<QString> validBuiltinPropertyNames; }; } Q_GLOBAL_STATIC(SharedData, sharedData) QColor QmlJS::toQColor(const QString &qmlColorString) { QColor color; if (qmlColorString.size() == 9 && qmlColorString.at(0) == QLatin1Char('#')) { bool ok; const int alpha = qmlColorString.midRef(1, 2).toInt(&ok, 16); if (ok) { const QString name = qmlColorString.at(0) + qmlColorString.right(6); if (QColor::isValidColor(name)) { color.setNamedColor(name); color.setAlpha(alpha); } } } else { if (QColor::isValidColor(qmlColorString)) color.setNamedColor(qmlColorString); } return color; } QString QmlJS::toString(UiQualifiedId *qualifiedId, QChar delimiter) { QString result; for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) { if (iter != qualifiedId) result += delimiter; result += iter->name; } return result; } SourceLocation QmlJS::locationFromRange(const SourceLocation &start, const SourceLocation &end) { return SourceLocation(start.offset, end.end() - start.begin(), start.startLine, start.startColumn); } SourceLocation QmlJS::fullLocationForQualifiedId(AST::UiQualifiedId *qualifiedId) { SourceLocation start = qualifiedId->identifierToken; SourceLocation end = qualifiedId->identifierToken; for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) { if (iter->identifierToken.isValid()) end = iter->identifierToken; } return locationFromRange(start, end); } QString QmlJS::idOfObject(Node *object, UiScriptBinding **idBinding) { if (idBinding) *idBinding = 0; UiObjectInitializer *initializer = initializerOfObject(object); if (!initializer) { initializer = cast<UiObjectInitializer *>(object); if (!initializer) return QString(); } for (UiObjectMemberList *iter = initializer->members; iter; iter = iter->next) { if (UiScriptBinding *script = cast<UiScriptBinding*>(iter->member)) { if (!script->qualifiedId) continue; if (script->qualifiedId->next) continue; if (script->qualifiedId->name != QLatin1String("id")) continue; if (ExpressionStatement *expstmt = cast<ExpressionStatement *>(script->statement)) { if (IdentifierExpression *idexp = cast<IdentifierExpression *>(expstmt->expression)) { if (idBinding) *idBinding = script; return idexp->name.toString(); } } } } return QString(); } UiObjectInitializer *QmlJS::initializerOfObject(Node *object) { if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(object)) return definition->initializer; if (UiObjectBinding *binding = cast<UiObjectBinding *>(object)) return binding->initializer; return 0; } UiQualifiedId *QmlJS::qualifiedTypeNameId(Node *node) { if (UiObjectBinding *binding = AST::cast<UiObjectBinding *>(node)) return binding->qualifiedTypeNameId; else if (UiObjectDefinition *binding = AST::cast<UiObjectDefinition *>(node)) return binding->qualifiedTypeNameId; return 0; } DiagnosticMessage QmlJS::errorMessage(const AST::SourceLocation &loc, const QString &message) { return DiagnosticMessage(Severity::Error, loc, message); } namespace { const QString undefinedVersion = QLatin1String("-1.-1"); } bool QmlJS::maybeModuleVersion(const QString &version) { QRegularExpression re(QLatin1String("^\\d+\\.\\d+$")); return version.isEmpty() || version == undefinedVersion || re.match(version).hasMatch(); } QString QmlJS::modulePath(const QString &name, const QString &version, const QStringList &importPaths) { Q_ASSERT(maybeModuleVersion(version)); if (importPaths.isEmpty()) return QString(); const QString sanitizedVersion = version == undefinedVersion ? QString() : version; const QStringList parts = name.split(QLatin1Char('.'), QString::SkipEmptyParts); auto mkpath = [] (const QStringList &xs) -> QString { return xs.join(QLatin1Char('/')); }; const QRegularExpression re("\\.?\\d+$"); QString candidate; for (QString ver = sanitizedVersion; !ver.isEmpty(); ver.remove(re)) { for (const QString &path: importPaths) { for (int i = parts.count() - 1; i >= 0; --i) { candidate = QDir::cleanPath( QString::fromLatin1("%1/%2.%3/%4").arg(path, mkpath(parts.mid(0, i + 1)), ver, mkpath(parts.mid(i + 1)))); if (QDir(candidate).exists()) return candidate; } } } for (const QString &path: importPaths) { candidate = QDir::cleanPath(QString::fromLatin1("%1/%2").arg(path, mkpath(parts))); if (QDir(candidate).exists()) return candidate; } return QString(); } bool QmlJS::isValidBuiltinPropertyType(const QString &name) { return sharedData()->validBuiltinPropertyNames.contains(name); }
#include "qmljsutils.h" #include "parser/qmljsast_p.h" #include <QColor> #include <QDir> #include <QRegularExpression> using namespace QmlJS; using namespace QmlJS::AST; namespace { class SharedData { public: SharedData() { validBuiltinPropertyNames.insert(QLatin1String("action")); validBuiltinPropertyNames.insert(QLatin1String("bool")); validBuiltinPropertyNames.insert(QLatin1String("color")); validBuiltinPropertyNames.insert(QLatin1String("date")); validBuiltinPropertyNames.insert(QLatin1String("double")); validBuiltinPropertyNames.insert(QLatin1String("enumeration")); validBuiltinPropertyNames.insert(QLatin1String("font")); validBuiltinPropertyNames.insert(QLatin1String("int")); validBuiltinPropertyNames.insert(QLatin1String("list")); validBuiltinPropertyNames.insert(QLatin1String("point")); validBuiltinPropertyNames.insert(QLatin1String("real")); validBuiltinPropertyNames.insert(QLatin1String("rect")); validBuiltinPropertyNames.insert(QLatin1String("size")); validBuiltinPropertyNames.insert(QLatin1String("string")); validBuiltinPropertyNames.insert(QLatin1String("time")); validBuiltinPropertyNames.insert(QLatin1String("url")); validBuiltinPropertyNames.insert(QLatin1String("var")); validBuiltinPropertyNames.insert(QLatin1String("variant")); validBuiltinPropertyNames.insert(QLatin1String("vector2d")); validBuiltinPropertyNames.insert(QLatin1String("vector3d")); validBuiltinPropertyNames.insert(QLatin1String("vector4d")); validBuiltinPropertyNames.insert(QLatin1String("quaternion")); validBuiltinPropertyNames.insert(QLatin1String("matrix4x4")); validBuiltinPropertyNames.insert(QLatin1String("alias")); } QSet<QString> validBuiltinPropertyNames; }; } Q_GLOBAL_STATIC(SharedData, sharedData) QColor QmlJS::toQColor(const QString &qmlColorString) { QColor color; if (qmlColorString.size() == 9 && qmlColorString.at(0) == QLatin1Char('#')) { bool ok; const int alpha = qmlColorString.midRef(1, 2).toInt(&ok, 16); if (ok) { const QString name = qmlColorString.at(0) + qmlColorString.right(6); if (QColor::isValidColor(name)) { color.setNamedColor(name); color.setAlpha(alpha); } } } else { if (QColor::isValidColor(qmlColorString)) color.setNamedColor(qmlColorString); } return color; } QString QmlJS::toString(UiQualifiedId *qualifiedId, QChar delimiter) { QString result; for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) { if (iter != qualifiedId) result += delimiter; result += iter->name; } return result; } SourceLocation QmlJS::locationFromRange(const SourceLocation &start, const SourceLocation &end) { return SourceLocation(start.offset, end.end() - start.begin(), start.startLine, start.startColumn); } SourceLocation QmlJS::fullLocationForQualifiedId(AST::UiQualifiedId *qualifiedId) { SourceLocation start = qualifiedId->identifierToken; SourceLocation end = qualifiedId->identifierToken; for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) { if (iter->identifierToken.isValid()) end = iter->identifierToken; } return locationFromRange(start, end); } QString QmlJS::idOfObject(Node *object, UiScriptBinding **idBinding) { if (idBinding) *idBinding = 0; UiObjectInitializer *initializer = initializerOfObject(object);
for (UiObjectMemberList *iter = initializer->members; iter; iter = iter->next) { if (UiScriptBinding *script = cast<UiScriptBinding*>(iter->member)) { if (!script->qualifiedId) continue; if (script->qualifiedId->next) continue; if (script->qualifiedId->name != QLatin1String("id")) continue; if (ExpressionStatement *expstmt = cast<ExpressionStatement *>(script->statement)) { if (IdentifierExpression *idexp = cast<IdentifierExpression *>(expstmt->expression)) { if (idBinding) *idBinding = script; return idexp->name.toString(); } } } } return QString(); } UiObjectInitializer *QmlJS::initializerOfObject(Node *object) { if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(object)) return definition->initializer; if (UiObjectBinding *binding = cast<UiObjectBinding *>(object)) return binding->initializer; return 0; } UiQualifiedId *QmlJS::qualifiedTypeNameId(Node *node) { if (UiObjectBinding *binding = AST::cast<UiObjectBinding *>(node)) return binding->qualifiedTypeNameId; else if (UiObjectDefinition *binding = AST::cast<UiObjectDefinition *>(node)) return binding->qualifiedTypeNameId; return 0; } DiagnosticMessage QmlJS::errorMessage(const AST::SourceLocation &loc, const QString &message) { return DiagnosticMessage(Severity::Error, loc, message); } namespace { const QString undefinedVersion = QLatin1String("-1.-1"); } bool QmlJS::maybeModuleVersion(const QString &version) { QRegularExpression re(QLatin1String("^\\d+\\.\\d+$")); return version.isEmpty() || version == undefinedVersion || re.match(version).hasMatch(); } QString QmlJS::modulePath(const QString &name, const QString &version, const QStringList &importPaths) { Q_ASSERT(maybeModuleVersion(version)); if (importPaths.isEmpty()) return QString(); const QString sanitizedVersion = version == undefinedVersion ? QString() : version; const QStringList parts = name.split(QLatin1Char('.'), QString::SkipEmptyParts); auto mkpath = [] (const QStringList &xs) -> QString { return xs.join(QLatin1Char('/')); }; const QRegularExpression re("\\.?\\d+$"); QString candidate; for (QString ver = sanitizedVersion; !ver.isEmpty(); ver.remove(re)) { for (const QString &path: importPaths) { for (int i = parts.count() - 1; i >= 0; --i) { candidate = QDir::cleanPath( QString::fromLatin1("%1/%2.%3/%4").arg(path, mkpath(parts.mid(0, i + 1)), ver, mkpath(parts.mid(i + 1)))); if (QDir(candidate).exists()) return candidate; } } } for (const QString &path: importPaths) { candidate = QDir::cleanPath(QString::fromLatin1("%1/%2").arg(path, mkpath(parts))); if (QDir(candidate).exists()) return candidate; } return QString(); } bool QmlJS::isValidBuiltinPropertyType(const QString &name) { return sharedData()->validBuiltinPropertyNames.contains(name); }
if (!initializer) { initializer = cast<UiObjectInitializer *>(object); if (!initializer) return QString(); }
if_condition
[]
C++
MouseToVJoy/cInputDevices.cpp
R1PeR/MouseToVJoy
c5487f6bf6e3db8ac41478a612a6c2642c69b7af
#include "input.h" void CInputDevices::getData(LPARAM lParam) { UINT bufferSize; GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof(RAWINPUTHEADER)); if (bufferSize <= 40) GetRawInputData((HRAWINPUT)lParam, RID_INPUT, (LPVOID)_buffer, &bufferSize, sizeof(RAWINPUTHEADER)); RAWINPUT *raw = (RAWINPUT*)_buffer; _mouseXChange = raw->data.mouse.lLastX; _mouseYChange = raw->data.mouse.lLastY; _mouseZChange = (short)raw->data.mouse.usButtonData; if (_mouseZChange / 120 == 1) { _isMouseWheelUp = true; } else { _isMouseWheelUp = false; }; if (_mouseZChange / -120 == 1) { _isMouseWheelDown = true; } else { _isMouseWheelDown = false; }; if (raw->header.dwType == RIM_TYPEMOUSE) { bool bStateDown = raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN; bool bStateUp = raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP; if (bStateDown == true && bStateUp == false) { _isLeftMouseButtonPressed = true; _isKeyboardButtonPressed[0x01] = true; } if (bStateUp == true) { _isLeftMouseButtonPressed = false; _isKeyboardButtonPressed[0x01] = false; } bool bStateDownTwo = raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN; bool bStateUpTwo = raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP; if (bStateDownTwo == true && bStateUpTwo == false) { _isRightMouseButtonPressed = true; _isKeyboardButtonPressed[0x02] = true; } if (bStateUpTwo == true) { _isRightMouseButtonPressed = false; _isKeyboardButtonPressed[0x02] = false; } } if (raw->header.dwType == RIM_TYPEKEYBOARD) { USHORT keyCode = raw->data.keyboard.VKey; bool keyUp = raw->data.keyboard.Flags & RI_KEY_BREAK; bool* pbToKey = NULL; for (int i = 0; i < 165; ++i) { if (keyCode == i + 0x01) { pbToKey = &_isKeyboardButtonPressed[i + 0x01]; break; } } if (pbToKey != NULL) { *pbToKey = checkKeyPress(*pbToKey, keyUp); return; } } } bool CInputDevices::checkKeyPress(bool isLastKeyState, bool isThisKeyState) { if (isThisKeyState == false) { if (isLastKeyState == true) { return true; } else { return true; } } else if (isThisKeyState == true) { if (isLastKeyState == false) { return false; } else return false; } }
#include "input.h" void CInputDevices::getData(LPARAM lParam) { UINT bufferSize; GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof(RAWINPUTHEADER)); if (bufferSize <= 40) GetRawInputData((HRAWINPUT)lParam, RID_INPUT, (LPVOID)_buffer, &bufferSize, sizeof(RAWINPUTHEADER)); RAWINPUT *raw = (RAWINPUT*)_buffer; _mouseXChange = raw->data.mouse.lLastX; _mouseYChange = raw->data.mouse.lLastY; _mouseZChange = (short)raw->data.mouse.usButtonData; if (_mouseZChange / 120 == 1) { _isMouseWheelUp = true; } else { _isMouseWheelUp = false; }; if (_mouseZChange / -120 == 1) { _isMouseWheelDown = true; } else { _isMouseWheelDown = false; }; if (raw->header.dwType == RIM_TYPEMOUSE) { bool bStateDown = raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_DOWN; bool bStateUp = raw->data.mouse.usButtonFlags & RI_MOUSE_LEFT_BUTTON_UP; if (bStateDown == true
yState == false) { if (isLastKeyState == true) { return true; } else { return true; } } else if (isThisKeyState == true) { if (isLastKeyState == false) { return false; } else return false; } }
&& bStateUp == false) { _isLeftMouseButtonPressed = true; _isKeyboardButtonPressed[0x01] = true; } if (bStateUp == true) { _isLeftMouseButtonPressed = false; _isKeyboardButtonPressed[0x01] = false; } bool bStateDownTwo = raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_DOWN; bool bStateUpTwo = raw->data.mouse.usButtonFlags & RI_MOUSE_RIGHT_BUTTON_UP; if (bStateDownTwo == true && bStateUpTwo == false) { _isRightMouseButtonPressed = true; _isKeyboardButtonPressed[0x02] = true; } if (bStateUpTwo == true) { _isRightMouseButtonPressed = false; _isKeyboardButtonPressed[0x02] = false; } } if (raw->header.dwType == RIM_TYPEKEYBOARD) { USHORT keyCode = raw->data.keyboard.VKey; bool keyUp = raw->data.keyboard.Flags & RI_KEY_BREAK; bool* pbToKey = NULL; for (int i = 0; i < 165; ++i) { if (keyCode == i + 0x01) { pbToKey = &_isKeyboardButtonPressed[i + 0x01]; break; } } if (pbToKey != NULL) { *pbToKey = checkKeyPress(*pbToKey, keyUp); return; } } } bool CInputDevices::checkKeyPress(bool isLastKeyState, bool isThisKeyState) { if (isThisKe
random
[ { "content": "#include <windows.h>\n\n#include <string>\n\n#include \"forcefeedback.h\"\n\n\n\nusing namespace std;\n\n// Convert Packet type to String\n\nBOOL ForceFeedBack::packetType2Str(FFBPType type, LPTSTR outStr)\n\n{\n\n\tBOOL stat = TRUE;\n\n\tLPTSTR Str = \"\";\n\n\n\n\tswitch (type)\n\n\t{\n\n\tcase ...
C++
include/bunsan/config/traits.hpp
sarum9in/bunsan_common
1d113259e2e53de025ba28bd9df485d75f437921
#pragma once #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include <deque> #include <list> #include <map> #include <set> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> namespace bunsan { namespace config { namespace traits { template <typename T> struct is_direct_assignable : std::integral_constant<bool, std::is_arithmetic<T>::value || std::is_enum<T>::value> {}; template <typename T> struct is_random_access_sequence : std::integral_constant<bool, false> {}; template <typename T> struct is_sequence : std::integral_constant<bool, false> {}; template <typename T> struct is_set : std::integral_constant<bool, false> {}; template <typename T> struct is_map : std::integral_constant<bool, false> {}; template <typename T> struct is_recursive : std::integral_constant<bool, !is_direct_assignable<T>::value && !is_random_access_sequence<T>::value && !is_sequence<T>::value && !is_set<T>::value && !is_map<T>::value> { }; template <typename Parent, typename Derived> struct type_key { static constexpr const char *call() { return nullptr; } }; template <typename T> struct serializer { template <typename Archive> static void load(T &obj, Archive &ar, const unsigned int version) { obj.serialize(ar, version); } template <typename Archive> static void save(const T &obj, Archive &ar, const unsigned int version) { const_cast<T &>(obj).serialize(ar, version); } }; } } } namespace bunsan { namespace config { namespace traits { template <typename Char, typename Traits, typename Alloc> struct is_direct_assignable<std::basic_string<Char, Traits, Alloc>> : std::integral_constant<bool, true> {}; template <typename Tp, typename Alloc> struct is_random_access_sequence<std::vector<Tp, Alloc>> : std::integral_constant<bool, true> {}; template <typename Tp, typename Alloc> struct is_sequence<std::list<Tp, Alloc>> : std::integral_constant<bool, true> { }; template <typename Tp, typename Alloc> struct is_sequence<std::deque<Tp, Alloc>> : std::integral_constant<bool, true> { }; template <typename Key, typename Compare, typename Alloc> struct is_set<std::set<Key, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Compare, typename Alloc> struct is_set<std::multiset<Key, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Compare, typename Alloc> struct is_map<std::map<Key, Tp, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Compare, typename Alloc> struct is_map<std::multimap<Key, Tp, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<std::unordered_set<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<std::unordered_multiset<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<std::unordered_map<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<std::unordered_multimap<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<boost::unordered_set<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<boost::unordered_multiset<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<boost::unordered_map<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<boost::unordered_multimap<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; } } } #define BUNSAN_CONFIG_EXPORT(PARENT, DERIVED, FIELD) \ namespace bunsan { \ namespace config { \ namespace traits { \ template <> \ struct type_key<PARENT, DERIVED> { \ static constexpr const char *call() { return FIELD; } \ }; \ } \ } \ }
#pragma once #include <boost/unordered_map.hpp> #include <boost/unordered_set.hpp> #include <deque> #include <list> #include <map> #include <set> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> namespace bunsan { namespace config { namespace traits { template <typename T> struct is_direct_assignable : std::integral_constant<bool, std::is_arithmetic<T>::value || std::is_enum<T>::value> {}; template <typename T> struct is_random_access_sequence : std::integral_constant<bool, false> {}; template <typename T> struct is_sequence : std::integral_constant<bool, false> {}; template <typename T> struct is_set : std::integral_constant<bool, false> {}; template <typename T> struct is_map : std::integral_constant<bool, false> {}; template <typename T> struct is_recursive : std::integral_constant<bool, !is_direct_assignable<T>::value && !is_random_access_sequence<T>::value && !is_sequence<T>::value && !is_set<T>::value && !is_map<T>::value> { }; template <typename Parent, typename Derived> struct type_key { static constexpr const char *call() { return nullptr; } }; template <typename T> struct serializer { template <typename Archive> static void load(T &obj, Archive &ar, const unsigned int version) { obj.serialize(ar, version); } template <typename Archive> static void save(const T &obj, Archive &ar, const unsigned int version) { const_cast<T &>(obj).serialize(ar, version); } }; } } } namespace bunsan { namespace config { namespace traits { template <typename Char, typename Traits, typename Alloc> struct is_direct_assignable<std::basic_string<Char, Traits, Alloc>> : std::integral_constant<bool, true> {}; template <typename Tp, typename Alloc> struct is_random_access_sequence<std::vector<Tp, Alloc>> : std::integral_constant<bool, true> {}; template <typename Tp, typename Alloc> struct is_sequence<std::list<Tp, Alloc>> : std::integral_constant<bool, true> { }; template <typename Tp, typename Alloc> struct is_sequence<std::deque<Tp, Alloc>> : std::integral_constant<bool, true> { }; template <typename Key, typename Compare, typename Alloc> struct is_set<std::set<Key, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typenam
: std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Compare, typename Alloc> struct is_map<std::multimap<Key, Tp, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<std::unordered_set<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<std::unordered_multiset<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<std::unordered_map<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<std::unordered_multimap<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<boost::unordered_set<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Value, typename Hash, typename Pred, typename Alloc> struct is_set<boost::unordered_multiset<Value, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<boost::unordered_map<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Hash, typename Pred, typename Alloc> struct is_map<boost::unordered_multimap<Key, Tp, Hash, Pred, Alloc>> : std::integral_constant<bool, true> {}; } } } #define BUNSAN_CONFIG_EXPORT(PARENT, DERIVED, FIELD) \ namespace bunsan { \ namespace config { \ namespace traits { \ template <> \ struct type_key<PARENT, DERIVED> { \ static constexpr const char *call() { return FIELD; } \ }; \ } \ } \ }
e Compare, typename Alloc> struct is_set<std::multiset<Key, Compare, Alloc>> : std::integral_constant<bool, true> {}; template <typename Key, typename Tp, typename Compare, typename Alloc> struct is_map<std::map<Key, Tp, Compare, Alloc>>
random
[ { "content": "struct load_variant;\n\n\n\n/// Implementation.\n\ntemplate <typename Arg, typename... Args>\n", "file_path": "include/bunsan/config/input_archive.hpp", "rank": 22, "score": 164930.03404454674 }, { "content": "struct load_variant<> {\n\n template <typename Archive, typename Va...
C++
components/agro_mesh/net/resources/app.cpp
rnascunha/agro_mesh
f4d1c49cdbd3d61086c1dcd79143d30ec54d4871
#include "esp_log.h" #include <stdio.h> #include <string.h> #include "../coap_engine.hpp" #include "../../modules/app/app.hpp" extern const char* RESOURCE_TAG; static char* make_name(char* name, const void* data, unsigned name_size) noexcept { std::memcpy(name, data, name_size); name[name_size] = '\0'; return name; } static void get_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called get app handler"); std::uint8_t buffer[engine::packet_size]; char name[app_max_name_size]; const void* value = nullptr; unsigned length; if(CoAP::Message::query_by_key(request, "name", &value, length) || !length) { app mapp; app_status status = get_app(mapp, make_name(name, value, length)); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::content) .payload(static_cast<const void*>(&mapp), sizeof(app)); return; } unsigned size; app_status status = get_app_list(buffer, engine::packet_size, size); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::content) .payload(buffer, size) .serialize(); } static void post_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called post app handler"); if(!request.payload || !request.payload_len || request.payload_len <= 32) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defiend") .serialize(); return; } if((request.payload_len - 32) > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } char name[app_max_name_size + 1]; if(!init_app_task(make_name(name, static_cast<const unsigned char*>(request.payload) + 32, request.payload_len - 32), static_cast<const std::uint8_t*>(request.payload))) { response .code(CoAP::Message::code::internal_server_error) .payload("app other loading") .serialize(); return; } response .code(CoAP::Message::code::changed) .serialize(); } static void put_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called put app handler"); if(!request.payload || !request.payload_len || request.payload_len <= sizeof(std::int32_t)) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defined") .serialize(); return; } if((request.payload_len - sizeof(int32_t)) > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } std::int32_t arg = *static_cast<const int*>(request.payload); int ret; char name[app_max_name_size + 1]; app_status status = execute_app(make_name(name, static_cast<const char*>(request.payload) + sizeof(std::int32_t), request.payload_len - sizeof(std::int32_t)), arg, ret); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } ESP_LOGI(RESOURCE_TAG, "Returned %d", ret); response .code(CoAP::Message::code::success) .payload(&ret, sizeof(ret)) .serialize(); } static void delete_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called delete app handler"); if(!request.payload || !request.payload_len) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defined") .serialize(); return; } if(request.payload_len > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } char name[app_max_name_size + 1]; app_status status = delete_app(make_name(name, request.payload, request.payload_len)); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::success) .serialize(); } engine::resource_node res_app("app", get_app_handler, post_app_handler, put_app_handler, delete_app_handler);
#include "esp_log.h" #include <stdio.h> #include <string.h> #include "../coap_engine.hpp" #include "../../modules/app/app.hpp" extern const char* RESOURCE_TAG; static char* make_name(char* name, const void* data, unsigned name_size) noexcept { std::memcpy(name, data, name_size); name[name_size] = '\0'; return name; } static void get_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called get app handler"); std::uint8_t buffer[engine::packet_size]; char name[app_max_name_size]; const void* value = nullptr; unsigned length; if(CoAP::Message::query_by_key(request, "name", &value, length) || !length) { app mapp; app_status status = get_app(mapp, make_name(name, value, length)); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::content) .payload(static_cast<const void*>(&mapp), sizeof(app)); return; } unsigned size; app_status status = get_app_list(buffer, engine::packet_size, size); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::content) .payload(buffer, size) .serialize(); } static void post_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called post app handler"); if(!request.payload || !request.payload_len || request.payload_len <= 32) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defiend") .serialize(); return; } if((request.payload_len - 32) > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } char name[app_max_name_size + 1]; if(!init_app_task(make_name(name, static_cast<const unsigned char*>(request.payload) + 32, request.payload_le
static void put_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called put app handler"); if(!request.payload || !request.payload_len || request.payload_len <= sizeof(std::int32_t)) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defined") .serialize(); return; } if((request.payload_len - sizeof(int32_t)) > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } std::int32_t arg = *static_cast<const int*>(request.payload); int ret; char name[app_max_name_size + 1]; app_status status = execute_app(make_name(name, static_cast<const char*>(request.payload) + sizeof(std::int32_t), request.payload_len - sizeof(std::int32_t)), arg, ret); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } ESP_LOGI(RESOURCE_TAG, "Returned %d", ret); response .code(CoAP::Message::code::success) .payload(&ret, sizeof(ret)) .serialize(); } static void delete_app_handler(engine::message const& request, engine::response& response, void*) noexcept { ESP_LOGD(RESOURCE_TAG, "Called delete app handler"); if(!request.payload || !request.payload_len) { response .code(CoAP::Message::code::precondition_failed) .payload("app not defined") .serialize(); return; } if(request.payload_len > app_max_name_size) { response .code(CoAP::Message::code::precondition_failed) .payload("file name too long") .serialize(); return; } char name[app_max_name_size + 1]; app_status status = delete_app(make_name(name, request.payload, request.payload_len)); if(status != app_status::success) { response .code(CoAP::Message::code::not_found) .payload(app_error_string(status)) .serialize(); return; } response .code(CoAP::Message::code::success) .serialize(); } engine::resource_node res_app("app", get_app_handler, post_app_handler, put_app_handler, delete_app_handler);
n - 32), static_cast<const std::uint8_t*>(request.payload))) { response .code(CoAP::Message::code::internal_server_error) .payload("app other loading") .serialize(); return; } response .code(CoAP::Message::code::changed) .serialize(); }
function_block-function_prefixed
[ { "content": "struct app{\n\n\tchar\t\tname[app_max_name_size + 1];\n\n\tunsigned \tsize = 0;\n\n};\n\n\n", "file_path": "components/agro_mesh/modules/app/app.hpp", "rank": 0, "score": 77485.24550976587 }, { "content": "const char* get_scheduler_status_string(Scheduler::status_t status);\n",...
C++
ccl/src/dev/Morpheus_Ccl_DenseVector.hpp
morpheus-org/morpheus-interoperability
66161199fa1926914e16c1feb02eb910ffef5ed4
#ifndef MORPHEUS_CCL_DEV_DENSEVECTOR_HPP #define MORPHEUS_CCL_DEV_DENSEVECTOR_HPP #include <Morpheus_Ccl_Types.hpp> #include <dev/fwd/Morpheus_Ccl_Fwd_DenseVector.hpp> #ifdef __cplusplus extern "C" { #endif void ccl_dvec_dense_v_create_default(ccl_dvec_dense_v** v); void ccl_dvec_dense_v_create(ccl_dvec_dense_v** v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_create_from_dvec_dense_v(ccl_dvec_dense_v* src, ccl_dvec_dense_v** dst); void ccl_dvec_dense_v_allocate_from_dvec_dense_v(ccl_dvec_dense_v* src, ccl_dvec_dense_v* dst); void ccl_dvec_dense_v_assign(ccl_dvec_dense_v* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_resize(ccl_dvec_dense_v* v, ccl_index_t n); void ccl_dvec_dense_v_resize_fill(ccl_dvec_dense_v* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_destroy(ccl_dvec_dense_v** v); ccl_index_t ccl_dvec_dense_v_size(ccl_dvec_dense_v* v); ccl_value_t* ccl_dvec_dense_v_data(ccl_dvec_dense_v* v); ccl_value_t ccl_dvec_dense_v_values_at(ccl_dvec_dense_v* v, ccl_index_t i); void ccl_dvec_dense_v_set_values_at(ccl_dvec_dense_v* v, ccl_index_t i, ccl_value_t val); void ccl_dvec_dense_i_create_default(ccl_dvec_dense_i** v); void ccl_dvec_dense_i_create(ccl_dvec_dense_i** v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_create_from_dvec_dense_i(ccl_dvec_dense_i* src, ccl_dvec_dense_i** dst); void ccl_dvec_dense_i_allocate_from_dvec_dense_i(ccl_dvec_dense_i* src, ccl_dvec_dense_i* dst); void ccl_dvec_dense_i_assign(ccl_dvec_dense_i* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_resize(ccl_dvec_dense_i* v, ccl_index_t n); void ccl_dvec_dense_i_resize_fill(ccl_dvec_dense_i* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_destroy(ccl_dvec_dense_i** v); ccl_index_t ccl_dvec_dense_i_size(ccl_dvec_dense_i* v); ccl_index_t* ccl_dvec_dense_i_data(ccl_dvec_dense_i* v); void ccl_dvec_dense_v_hostmirror_create_default( ccl_dvec_dense_v_hostmirror** v); void ccl_dvec_dense_v_hostmirror_create(ccl_dvec_dense_v_hostmirror** v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_create_from_dvec_dense_v_hostmirror( ccl_dvec_dense_v_hostmirror* src, ccl_dvec_dense_v_hostmirror** dst); void ccl_dvec_dense_v_hostmirror_allocate_from_dvec_dense_v_hostmirror( ccl_dvec_dense_v_hostmirror* src, ccl_dvec_dense_v_hostmirror* dst); void ccl_dvec_dense_v_hostmirror_assign(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_resize(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n); void ccl_dvec_dense_v_hostmirror_resize_fill(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_destroy(ccl_dvec_dense_v_hostmirror** v); ccl_index_t ccl_dvec_dense_v_hostmirror_size(ccl_dvec_dense_v_hostmirror* v); ccl_value_t* ccl_dvec_dense_v_hostmirror_data(ccl_dvec_dense_v_hostmirror* v); ccl_value_t ccl_dvec_dense_v_hostmirror_values_at( ccl_dvec_dense_v_hostmirror* v, ccl_index_t i); void ccl_dvec_dense_v_hostmirror_set_values_at(ccl_dvec_dense_v_hostmirror* v, ccl_index_t i, ccl_value_t val); void ccl_dvec_dense_i_hostmirror_create_default( ccl_dvec_dense_i_hostmirror** v); void ccl_dvec_dense_i_hostmirror_create(ccl_dvec_dense_i_hostmirror** v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_create_from_dvec_dense_i_hostmirror( ccl_dvec_dense_i_hostmirror* src, ccl_dvec_dense_i_hostmirror** dst); void ccl_dvec_dense_i_hostmirror_allocate_from_dvec_dense_i_hostmirror( ccl_dvec_dense_i_hostmirror* src, ccl_dvec_dense_i_hostmirror* dst); void ccl_dvec_dense_i_hostmirror_assign(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_resize(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n); void ccl_dvec_dense_i_hostmirror_resize_fill(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_destroy(ccl_dvec_dense_i_hostmirror** v); ccl_index_t ccl_dvec_dense_i_hostmirror_size(ccl_dvec_dense_i_hostmirror* v); ccl_index_t* ccl_dvec_dense_i_hostmirror_data(ccl_dvec_dense_i_hostmirror* v); ccl_index_t ccl_dvec_dense_i_hostmirror_values_at( ccl_dvec_dense_i_hostmirror* v, ccl_index_t i); void ccl_dvec_dense_i_hostmirror_set_values_at(ccl_dvec_dense_i_hostmirror* v, ccl_index_t i, ccl_index_t val); #ifdef __cplusplus } #endif #endif
#ifndef MORPHEUS_CCL_DEV_DENSEVECTOR_HPP #define MORPHEUS_CCL_DEV_DENSEVECTOR_HPP #include <Morpheus_Ccl_Types.hpp> #include <dev/fwd/Morpheus_Ccl_Fwd_DenseVector.hpp> #ifdef __cplusplus extern "C" { #endif void ccl_dvec_dense_v_create_default(ccl_dvec_dense_v** v); void ccl_dvec_dense_v_create(ccl_dvec_dense_v** v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_create_from_dvec_dense_v(ccl_dvec_dense_v* src,
_dvec_dense_v_hostmirror_values_at( ccl_dvec_dense_v_hostmirror* v, ccl_index_t i); void ccl_dvec_dense_v_hostmirror_set_values_at(ccl_dvec_dense_v_hostmirror* v, ccl_index_t i, ccl_value_t val); void ccl_dvec_dense_i_hostmirror_create_default( ccl_dvec_dense_i_hostmirror** v); void ccl_dvec_dense_i_hostmirror_create(ccl_dvec_dense_i_hostmirror** v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_create_from_dvec_dense_i_hostmirror( ccl_dvec_dense_i_hostmirror* src, ccl_dvec_dense_i_hostmirror** dst); void ccl_dvec_dense_i_hostmirror_allocate_from_dvec_dense_i_hostmirror( ccl_dvec_dense_i_hostmirror* src, ccl_dvec_dense_i_hostmirror* dst); void ccl_dvec_dense_i_hostmirror_assign(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_resize(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n); void ccl_dvec_dense_i_hostmirror_resize_fill(ccl_dvec_dense_i_hostmirror* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_hostmirror_destroy(ccl_dvec_dense_i_hostmirror** v); ccl_index_t ccl_dvec_dense_i_hostmirror_size(ccl_dvec_dense_i_hostmirror* v); ccl_index_t* ccl_dvec_dense_i_hostmirror_data(ccl_dvec_dense_i_hostmirror* v); ccl_index_t ccl_dvec_dense_i_hostmirror_values_at( ccl_dvec_dense_i_hostmirror* v, ccl_index_t i); void ccl_dvec_dense_i_hostmirror_set_values_at(ccl_dvec_dense_i_hostmirror* v, ccl_index_t i, ccl_index_t val); #ifdef __cplusplus } #endif #endif
ccl_dvec_dense_v** dst); void ccl_dvec_dense_v_allocate_from_dvec_dense_v(ccl_dvec_dense_v* src, ccl_dvec_dense_v* dst); void ccl_dvec_dense_v_assign(ccl_dvec_dense_v* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_resize(ccl_dvec_dense_v* v, ccl_index_t n); void ccl_dvec_dense_v_resize_fill(ccl_dvec_dense_v* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_destroy(ccl_dvec_dense_v** v); ccl_index_t ccl_dvec_dense_v_size(ccl_dvec_dense_v* v); ccl_value_t* ccl_dvec_dense_v_data(ccl_dvec_dense_v* v); ccl_value_t ccl_dvec_dense_v_values_at(ccl_dvec_dense_v* v, ccl_index_t i); void ccl_dvec_dense_v_set_values_at(ccl_dvec_dense_v* v, ccl_index_t i, ccl_value_t val); void ccl_dvec_dense_i_create_default(ccl_dvec_dense_i** v); void ccl_dvec_dense_i_create(ccl_dvec_dense_i** v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_create_from_dvec_dense_i(ccl_dvec_dense_i* src, ccl_dvec_dense_i** dst); void ccl_dvec_dense_i_allocate_from_dvec_dense_i(ccl_dvec_dense_i* src, ccl_dvec_dense_i* dst); void ccl_dvec_dense_i_assign(ccl_dvec_dense_i* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_resize(ccl_dvec_dense_i* v, ccl_index_t n); void ccl_dvec_dense_i_resize_fill(ccl_dvec_dense_i* v, ccl_index_t n, ccl_index_t val); void ccl_dvec_dense_i_destroy(ccl_dvec_dense_i** v); ccl_index_t ccl_dvec_dense_i_size(ccl_dvec_dense_i* v); ccl_index_t* ccl_dvec_dense_i_data(ccl_dvec_dense_i* v); void ccl_dvec_dense_v_hostmirror_create_default( ccl_dvec_dense_v_hostmirror** v); void ccl_dvec_dense_v_hostmirror_create(ccl_dvec_dense_v_hostmirror** v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_create_from_dvec_dense_v_hostmirror( ccl_dvec_dense_v_hostmirror* src, ccl_dvec_dense_v_hostmirror** dst); void ccl_dvec_dense_v_hostmirror_allocate_from_dvec_dense_v_hostmirror( ccl_dvec_dense_v_hostmirror* src, ccl_dvec_dense_v_hostmirror* dst); void ccl_dvec_dense_v_hostmirror_assign(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_resize(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n); void ccl_dvec_dense_v_hostmirror_resize_fill(ccl_dvec_dense_v_hostmirror* v, ccl_index_t n, ccl_value_t val); void ccl_dvec_dense_v_hostmirror_destroy(ccl_dvec_dense_v_hostmirror** v); ccl_index_t ccl_dvec_dense_v_hostmirror_size(ccl_dvec_dense_v_hostmirror* v); ccl_value_t* ccl_dvec_dense_v_hostmirror_data(ccl_dvec_dense_v_hostmirror* v); ccl_value_t ccl
random
[ { "content": "#ifdef __cplusplus\n\nextern \"C\" {\n\n#endif\n\n\n\nvoid ccl_initialize(int* argc, char** argv[]);\n\nvoid ccl_initialize_without_args(void);\n\nvoid ccl_finalize(void);\n\nvoid ccl_print_configuration(const char* prepend_name_in,\n\n const char* file_name_in);\n\n\n\...
C++
CC2500.cpp
RoXXoR/CC2500
7a07566dd2342a1b21bcdc9beb30b0ff3e6cdba6
#include "CC2500.h" CC2500::CC2500() { CC2500(DEVADDR, CHANNEL); } CC2500::CC2500(uint8_t deviceAddress) { CC2500(deviceAddress, CHANNEL); } CC2500::CC2500(uint8_t deviceAddress, uint8_t channel) { _deviceAddress = deviceAddress; _channel = channel; _gdo0 = GDO0; } void CC2500::setDeviceAddress(uint8_t deviceAddress) { _deviceAddress = deviceAddress; } void CC2500::setChannel(uint8_t channel) { _channel = channel; } void CC2500::begin() { SPI.begin(); SPI.setClockDivider(SPI_CLOCK_DIV2); SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE0); digitalWrite(SS,HIGH); pinMode(SS,OUTPUT); resetDevice(); delay(100); configureDeviceSettings(); execStrobeCommand(CC2500_CMD_SRX); } void CC2500::writeRegister(uint8_t addr, uint8_t data) { digitalWrite(SS,LOW); SPI.transfer(addr|CC2500_WRITE_SINGLE); SPI.transfer(data); digitalWrite(SS,HIGH); } void CC2500::writeRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) { digitalWrite(SS,LOW); SPI.transfer(saddr|CC2500_WRITE_BURST); while (size > 0) { SPI.transfer(*data++); size--; } digitalWrite(SS,HIGH); } uint8_t CC2500::readRegister(uint8_t addr) { uint8_t recv; digitalWrite(SS,LOW); SPI.transfer(addr|CC2500_READ_SINGLE); recv = SPI.transfer(0x00); digitalWrite(SS,HIGH); return recv; } void CC2500::readRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) { digitalWrite(SS,LOW); SPI.transfer(saddr|CC2500_READ_BURST); while (size > 0) { *data++ = SPI.transfer(0x00); size--; } digitalWrite(SS,HIGH); } void CC2500::execStrobeCommand(uint8_t command) { digitalWrite(SS,LOW); SPI.transfer(command); digitalWrite(SS,HIGH); } uint8_t CC2500::readStatusRegister(uint8_t addr) { return readRegister(addr|CC2500_READ_STATUS); } void CC2500::configureDeviceSettings() { uint8_t paTable[] = {0xFB}; writeRegister(CC2500_IOCFG0, 0x06); writeRegister(CC2500_IOCFG2, 0x0B); writeRegister(CC2500_PKTCTRL0, 0x05); writeRegister(CC2500_PKTCTRL1, 0x05); writeRegister(CC2500_PKTLEN, 0xFF); writeRegister(CC2500_ADDR, _deviceAddress); writeRegister(CC2500_CHANNR, _channel); writeRegister(CC2500_FSCTRL1, 0x07); writeRegister(CC2500_FSCTRL0, 0x00); writeRegister(CC2500_FREQ2, 0x5D); writeRegister(CC2500_FREQ1, 0x93); writeRegister(CC2500_FREQ0, 0xB1); writeRegister(CC2500_MDMCFG4, 0x2D); writeRegister(CC2500_MDMCFG3, 0x3B); writeRegister(CC2500_MDMCFG2, 0x73); writeRegister(CC2500_MDMCFG1, 0x22); writeRegister(CC2500_MDMCFG0, 0xF8); writeRegister(CC2500_DEVIANT, 0x00); writeRegister(CC2500_MCSM1, 0x3F); writeRegister(CC2500_MCSM0, 0x18); writeRegister(CC2500_FOCCFG, 0x1D); writeRegister(CC2500_BSCFG, 0x1C); writeRegister(CC2500_AGCCTRL2, 0xC7); writeRegister(CC2500_AGCCTRL1, 0x00); writeRegister(CC2500_AGCCTRL0, 0xB2); writeRegister(CC2500_FREND1, 0xB6); writeRegister(CC2500_FREND0, 0x10); writeRegister(CC2500_FSCAL3, 0xEA); writeRegister(CC2500_FSCAL2, 0x0A); writeRegister(CC2500_FSCAL1, 0x00); writeRegister(CC2500_FSCAL0, 0x11); writeRegisterBurst(CC2500_PATABLE, paTable, sizeof(paTable)); } void CC2500::sendTxBuffer(uint8_t *txBuffer, uint8_t size) { writeRegisterBurst(CC2500_TX_FIFO, txBuffer, size); execStrobeCommand(CC2500_CMD_STX); delay(200); } int8_t CC2500::receiveRxBuffer(uint8_t *rxBuffer, uint8_t size) { uint8_t pktLength; uint8_t rxInfo[2]; if (readStatusRegister(CC2500_RXBYTES)&CC2500_NUM_RXBYTES) { pktLength = readRegister(CC2500_RX_FIFO); if (pktLength <= size) { readRegisterBurst(CC2500_RX_FIFO, rxBuffer, pktLength); } else { readRegisterBurst(CC2500_RX_FIFO, rxBuffer, size); pktLength -= size; while (pktLength > 0) { readRegister(CC2500_RX_FIFO); pktLength--; } } readRegisterBurst(CC2500_RX_FIFO, rxInfo, sizeof(rxInfo)); } return rxInfo[1]; } uint8_t CC2500::getChipVersion() { return readStatusRegister(CC2500_REG_VERSION); } uint8_t CC2500::getStatusByte() { uint8_t recv; digitalWrite(SS,LOW); recv = SPI.transfer(CC2500_CMD_SNOP|CC2500_READ_SINGLE); digitalWrite(SS,HIGH); return recv; } void CC2500::resetDevice() { execStrobeCommand(CC2500_CMD_SRES); }
#include "CC2500.h" CC2500::CC2500() { CC2500(DEVADDR, CHANNEL); } CC2500::CC2500(uint8_t deviceAddress) { CC2500(deviceAddress, CHANNEL); } CC2500::CC2500(uint8_t deviceAddress, uint8_t channel) { _deviceAddress = deviceAddress; _channel = channel; _gdo0 = GDO0; } void CC2500::setDeviceAddress(uint8_t deviceAddress) { _deviceAddress = deviceAddress; } void CC2500::setChannel(uint8_t channel) { _channel = channel; } void CC2500::begin() { SPI.begin(); SPI.setClockDivider(SPI_CLOCK_DIV2); SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE0); digitalWrite(SS,HIGH); pinMode(SS,OUTPUT); resetDevice(); delay(100); configureDeviceSettings(); execStrobeCommand(CC2500_CMD_SRX); } void CC2500::writeRegister(uint8_t addr, uint8_t data) { digitalWrite(SS,LOW); SPI.transfer(addr|CC2500_WRITE_SINGLE); SPI.transfer(data); digitalWrite(SS,HIGH); } void CC2500::writeRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) { digitalWrite(SS,LOW); SPI.transfer(saddr|CC2500_WRITE_BURST); while (size > 0) { SPI.transfer(*data++); size--; } digitalWrite(SS,HIGH); } uint8_t CC2500::readRegister(uint8_t addr) { uint8_t recv; digitalWrite(SS,LOW); SPI.transfer(addr|CC2500_READ_SINGLE); recv = SPI.transfer(0x00); digitalWrite(SS,H
8_t *rxBuffer, uint8_t size) { uint8_t pktLength; uint8_t rxInfo[2]; if (readStatusRegister(CC2500_RXBYTES)&CC2500_NUM_RXBYTES) { pktLength = readRegister(CC2500_RX_FIFO); if (pktLength <= size) { readRegisterBurst(CC2500_RX_FIFO, rxBuffer, pktLength); } else { readRegisterBurst(CC2500_RX_FIFO, rxBuffer, size); pktLength -= size; while (pktLength > 0) { readRegister(CC2500_RX_FIFO); pktLength--; } } readRegisterBurst(CC2500_RX_FIFO, rxInfo, sizeof(rxInfo)); } return rxInfo[1]; } uint8_t CC2500::getChipVersion() { return readStatusRegister(CC2500_REG_VERSION); } uint8_t CC2500::getStatusByte() { uint8_t recv; digitalWrite(SS,LOW); recv = SPI.transfer(CC2500_CMD_SNOP|CC2500_READ_SINGLE); digitalWrite(SS,HIGH); return recv; } void CC2500::resetDevice() { execStrobeCommand(CC2500_CMD_SRES); }
IGH); return recv; } void CC2500::readRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size) { digitalWrite(SS,LOW); SPI.transfer(saddr|CC2500_READ_BURST); while (size > 0) { *data++ = SPI.transfer(0x00); size--; } digitalWrite(SS,HIGH); } void CC2500::execStrobeCommand(uint8_t command) { digitalWrite(SS,LOW); SPI.transfer(command); digitalWrite(SS,HIGH); } uint8_t CC2500::readStatusRegister(uint8_t addr) { return readRegister(addr|CC2500_READ_STATUS); } void CC2500::configureDeviceSettings() { uint8_t paTable[] = {0xFB}; writeRegister(CC2500_IOCFG0, 0x06); writeRegister(CC2500_IOCFG2, 0x0B); writeRegister(CC2500_PKTCTRL0, 0x05); writeRegister(CC2500_PKTCTRL1, 0x05); writeRegister(CC2500_PKTLEN, 0xFF); writeRegister(CC2500_ADDR, _deviceAddress); writeRegister(CC2500_CHANNR, _channel); writeRegister(CC2500_FSCTRL1, 0x07); writeRegister(CC2500_FSCTRL0, 0x00); writeRegister(CC2500_FREQ2, 0x5D); writeRegister(CC2500_FREQ1, 0x93); writeRegister(CC2500_FREQ0, 0xB1); writeRegister(CC2500_MDMCFG4, 0x2D); writeRegister(CC2500_MDMCFG3, 0x3B); writeRegister(CC2500_MDMCFG2, 0x73); writeRegister(CC2500_MDMCFG1, 0x22); writeRegister(CC2500_MDMCFG0, 0xF8); writeRegister(CC2500_DEVIANT, 0x00); writeRegister(CC2500_MCSM1, 0x3F); writeRegister(CC2500_MCSM0, 0x18); writeRegister(CC2500_FOCCFG, 0x1D); writeRegister(CC2500_BSCFG, 0x1C); writeRegister(CC2500_AGCCTRL2, 0xC7); writeRegister(CC2500_AGCCTRL1, 0x00); writeRegister(CC2500_AGCCTRL0, 0xB2); writeRegister(CC2500_FREND1, 0xB6); writeRegister(CC2500_FREND0, 0x10); writeRegister(CC2500_FSCAL3, 0xEA); writeRegister(CC2500_FSCAL2, 0x0A); writeRegister(CC2500_FSCAL1, 0x00); writeRegister(CC2500_FSCAL0, 0x11); writeRegisterBurst(CC2500_PATABLE, paTable, sizeof(paTable)); } void CC2500::sendTxBuffer(uint8_t *txBuffer, uint8_t size) { writeRegisterBurst(CC2500_TX_FIFO, txBuffer, size); execStrobeCommand(CC2500_CMD_STX); delay(200); } int8_t CC2500::receiveRxBuffer(uint
random
[ { "content": "#define CC2500_ADDR\t\t0x09\t// Device Address\n", "file_path": "cc2500_defines.h", "rank": 0, "score": 19030.082185654213 }, { "content": "\tvoid writeRegisterBurst(uint8_t saddr, uint8_t *data, uint8_t size);\n\n\tuint8_t readRegister(uint8_t addr);\n\n\tvoid readRegisterBurs...
C++
rcnn/backbone.hpp
GaoLon/tensorrtx
67bd89f27c4bcaf99c3ff50317c035b60bdce58e
#pragma once #include <vector> #include <map> #include <string> #include "common.hpp" enum RESNETTYPE { R18 = 0, R34, R50, R101, R152 }; const std::map<RESNETTYPE, std::vector<int>> num_blocks_per_stage = { {R18, {2, 2, 2, 2}}, {R34, {3, 4, 6, 3}}, {R50, {3, 4, 6, 3}}, {R101, {3, 4, 23, 3}}, {R152, {3, 8, 36, 3}} }; ILayer* BasicStem(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int out_channels, int group_num = 1) { IConvolutionLayer* conv1 = network->addConvolutionNd(input, out_channels, DimsHW{ 7, 7 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]); assert(conv1); conv1->setStrideNd(DimsHW{ 2, 2 }); conv1->setPaddingNd(DimsHW{ 3, 3 }); conv1->setNbGroups(group_num); auto r1 = network->addActivation(*conv1->getOutput(0), ActivationType::kRELU); assert(r1); auto max_pool2d = network->addPoolingNd(*r1->getOutput(0), PoolingType::kMAX, DimsHW{ 3, 3 }); max_pool2d->setStrideNd(DimsHW{ 2, 2 }); max_pool2d->setPaddingNd(DimsHW{ 1, 1 }); auto mp_dim = max_pool2d->getOutput(0)->getDimensions(); return max_pool2d; } ITensor* BottleneckBlock(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int in_channels, int bottleneck_channels, int out_channels, int stride = 1, int dilation = 1, int group_num = 1) { IConvolutionLayer* conv1 = network->addConvolutionNd(input, bottleneck_channels, DimsHW{ 1, 1 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]); assert(conv1); conv1->setStrideNd(DimsHW{ stride, stride }); conv1->setNbGroups(group_num); auto r1 = network->addActivation(*conv1->getOutput(0), ActivationType::kRELU); assert(r1); IConvolutionLayer* conv2 = network->addConvolutionNd(*r1->getOutput(0), bottleneck_channels, DimsHW{ 3, 3 }, weightMap[lname + ".conv2.weight"], weightMap[lname + ".conv2.bias"]); assert(conv2); conv2->setStrideNd(DimsHW{ 1, 1 }); conv2->setPaddingNd(DimsHW{ 1 * dilation, 1 * dilation }); conv2->setDilationNd(DimsHW{ dilation, dilation }); conv2->setNbGroups(group_num); auto r2 = network->addActivation(*conv2->getOutput(0), ActivationType::kRELU); assert(r2); IConvolutionLayer* conv3 = network->addConvolutionNd(*r2->getOutput(0), out_channels, DimsHW{ 1, 1 }, weightMap[lname + ".conv3.weight"], weightMap[lname + ".conv3.bias"]); assert(conv3); conv3->setStrideNd(DimsHW{ 1, 1 }); conv3->setNbGroups(group_num); ITensor* shortcut_value = nullptr; if (in_channels != out_channels) { auto shortcut = network->addConvolutionNd(input, out_channels, DimsHW{ 1, 1 }, weightMap[lname + ".shortcut.weight"], weightMap[lname + ".shortcut.bias"]); assert(shortcut); shortcut->setStrideNd(DimsHW{stride, stride}); shortcut->setNbGroups(group_num); shortcut_value = shortcut->getOutput(0); } else { shortcut_value = &input; } auto ew = network->addElementWise(*conv3->getOutput(0), *shortcut_value, ElementWiseOperation::kSUM); assert(ew); auto r3 = network->addActivation(*ew->getOutput(0), ActivationType::kRELU); assert(r3); return r3->getOutput(0); } ITensor* MakeStage(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int stage, int in_channels, int bottleneck_channels, int out_channels, int first_stride = 1, int dilation = 1) { ITensor* out = &input; for (int i = 0; i < stage; i++) { if (i == 0) out = BottleneckBlock(network, weightMap, lname + "." + std::to_string(i), *out, in_channels, bottleneck_channels, out_channels, first_stride, dilation); else out = BottleneckBlock(network, weightMap, lname + "." + std::to_string(i), *out, in_channels, bottleneck_channels, out_channels, 1, dilation); in_channels = out_channels; } return out; } ITensor* BuildResNet(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor& input, RESNETTYPE resnet_type, int stem_out_channels, int bottleneck_channels, int res2_out_channels, int res5_dilation = 1) { assert(res5_dilation == 1 || res5_dilation == 2); if (resnet_type == R18 || resnet_type == R34) { assert(res2_out_channels == 64); assert(res5_dilation == 1); } int out_channels = res2_out_channels; ITensor* out = nullptr; auto stem = BasicStem(network, weightMap, "backbone.stem", input, stem_out_channels); out = stem->getOutput(0); for (int i = 0; i < 3; i++) { int dilation = (i == 3) ? res5_dilation : 1; int first_stride = (i == 0 || (i == 3 && dilation == 2)) ? 1 : 2; out = MakeStage(network, weightMap, "backbone.res" + std::to_string(i + 2), *out, num_blocks_per_stage.at(resnet_type)[i], stem_out_channels, bottleneck_channels, out_channels, first_stride, dilation); stem_out_channels = out_channels; bottleneck_channels *= 2; out_channels *= 2; } return out; }
#pragma once #include <vector> #include <map> #include <string> #include "common.hpp" enum RESNETTYPE { R18 = 0, R34, R50, R101, R152 }; const std::map<RESNETTYPE, std::vector<int>> num_blocks_per_stage = { {R18, {2, 2, 2, 2}}, {R34, {3, 4, 6, 3}}, {R50, {3, 4, 6, 3}}, {R101, {3, 4, 23, 3}}, {R152, {3, 8, 36, 3}} }; ILayer* BasicStem(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int out_channels, int group_num = 1) { IConvolutionLayer* conv1 = network->addConvolutionNd(input, out_channels, DimsHW{ 7, 7 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]); assert(conv1); conv1->setStrideNd(DimsHW{ 2, 2 }); conv1->setPaddingNd(DimsHW{ 3, 3 }); conv1->setNbGroups(group_num); auto r1 = network->addActivation(*conv1->getOutput(0), ActivationType::kRELU); assert(r1); auto max_pool2d = network->addPoolingNd(*r1->getOutput(0), PoolingType::kMAX, DimsHW{ 3, 3 }); max_pool2d->setStrideNd(DimsHW{ 2, 2 }); max_pool2d->setPaddingNd(DimsHW{ 1, 1 }); auto mp_dim = max_pool2d->getOutput(0)->getDimensions(); return max_pool2d; } ITensor* BottleneckBlock(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int in_channels, int bottleneck_channels, int out_channels, int stride = 1, int dilation = 1, int group_num = 1) { IConvolutionLayer* conv1 = network->addConvolutionNd(input, bottleneck_channels, DimsHW{ 1, 1 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]); assert(conv1); conv1->setStrideNd(DimsHW{ stride, stride }); conv1->setNbGroups(group_num); auto r1 = network->addActivation(*conv1->getOutput(0), ActivationType::kRELU); assert(r1); IConvolutionLayer* conv2 = network->addConvolutionNd(*r1->getOutput(0), bottleneck_channels, DimsHW{ 3, 3 }, weightMap[lname + ".conv2.weight"], weightMap[lname + ".conv2.bias"]); assert(conv2); conv2->setStrideNd(DimsHW{ 1, 1 }); conv2->setPaddingNd(DimsHW{ 1 * dilation, 1 * dilation }); conv2->setDilationNd(DimsHW{ dilation, dilation }); conv2->setNbGroups(group_num); auto r2 = network->addActivation(*conv2->getOutput(0), ActivationType::kRELU); assert(r2); IConvolutionLayer* conv3 = network->addConvolutionNd(*r2->getOutput(0), out_channels, DimsHW{ 1, 1 }, weightMap[lname + ".conv3.weight"], weightMap[lname + ".conv3.bias"]); assert(conv3); conv3->setStrideNd(DimsHW{ 1, 1 }); conv3->setNbGroups(group_num); ITensor* shortcut_value = nullptr; if (in_channels != out_channels) { auto shortcut = network->addConvolutionNd(input, out_channels, DimsHW{ 1, 1 }, weightMap[lname + ".shortcut.weight"], weightMap[lname + ".shortcut.bias"]); assert(shortcut); shortcut->setStrideNd(DimsHW{stride, stride}); shortcut->setNbGroups(group_num); shortcut_value = shortcut->getOutput(0); } else { shortcut_value = &input; } auto ew = network->addElementWise(*conv3->getOutput(0), *shortcut_value, ElementWiseOperation::kSUM); assert(ew); auto r3 = network->addActivation(*ew->getOutput(0), ActivationType::kRELU); assert(r3); return r3->getOutput(0); } ITensor* MakeStage(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, const std::string& lname, ITensor& input, int stage, int in_channels, int bottleneck_channels, int out_channels, int first_stride = 1, int dilation = 1) { ITensor* out = &input; for (int i = 0; i < stage; i++) { if (i == 0) out = BottleneckBlock(network, weightMap, lname + "." + std::to_string(i), *out, in_channels, bottleneck_channels, out_channels, first_stride, dilation); else out = BottleneckBlock(network, weightMap, lname + "." + std::to_string(i), *out, in_channels, bottleneck_channels, out_channels, 1, dilation); in_channels = out_channels; } return out; } ITensor* BuildResNet(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor& input, RESNETTYPE resnet_type, int stem_out_channels, int bottleneck_channels, int res2_out_channels, int res5_dilation = 1) { assert(res5_dilation == 1 || res5_dilation == 2);
int out_channels = res2_out_channels; ITensor* out = nullptr; auto stem = BasicStem(network, weightMap, "backbone.stem", input, stem_out_channels); out = stem->getOutput(0); for (int i = 0; i < 3; i++) { int dilation = (i == 3) ? res5_dilation : 1; int first_stride = (i == 0 || (i == 3 && dilation == 2)) ? 1 : 2; out = MakeStage(network, weightMap, "backbone.res" + std::to_string(i + 2), *out, num_blocks_per_stage.at(resnet_type)[i], stem_out_channels, bottleneck_channels, out_channels, first_stride, dilation); stem_out_channels = out_channels; bottleneck_channels *= 2; out_channels *= 2; } return out; }
if (resnet_type == R18 || resnet_type == R34) { assert(res2_out_channels == 64); assert(res5_dilation == 1); }
if_condition
[]
C++
media/jni/audioeffect/android_media_SourceDefaultEffect.cpp
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
#define LOG_TAG "SourceDefaultEffect-JNI" #include <utils/Errors.h> #include <utils/Log.h> #include <jni.h> #include <nativehelper/JNIHelp.h> #include <android_runtime/AndroidRuntime.h> #include "media/AudioEffect.h" #include <nativehelper/ScopedUtfChars.h> #include "android_media_AudioEffect.h" using namespace android; static const char* const kClassPathName = "android/media/audiofx/SourceDefaultEffect"; static jint android_media_SourceDefaultEffect_native_setup(JNIEnv *env, jobject , jstring type, jstring uuid, jint priority, jint source, jstring opPackageName, jintArray jId) { ALOGV("android_media_SourceDefaultEffect_native_setup"); status_t lStatus = NO_ERROR; jint* nId = NULL; const char *typeStr = NULL; const char *uuidStr = NULL; ScopedUtfChars opPackageNameStr(env, opPackageName); if (type != NULL) { typeStr = env->GetStringUTFChars(type, NULL); if (typeStr == NULL) { lStatus = NO_MEMORY; jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); goto setup_exit; } } if (uuid != NULL) { uuidStr = env->GetStringUTFChars(uuid, NULL); if (uuidStr == NULL) { lStatus = NO_MEMORY; jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); goto setup_exit; } } if (typeStr == NULL && uuidStr == NULL) { lStatus = BAD_VALUE; goto setup_exit; } nId = reinterpret_cast<jint *>(env->GetPrimitiveArrayCritical(jId, NULL)); if (nId == NULL) { ALOGE("setup: Error retrieving id pointer"); lStatus = BAD_VALUE; goto setup_exit; } audio_unique_id_t id; lStatus = AudioEffect::addSourceDefaultEffect(typeStr, String16(opPackageNameStr.c_str()), uuidStr, priority, static_cast<audio_source_t>(source), &id); if (lStatus != NO_ERROR) { ALOGE("setup: Error adding SourceDefaultEffect"); goto setup_exit; } nId[0] = static_cast<jint>(id); setup_exit: if (nId != NULL) { env->ReleasePrimitiveArrayCritical(jId, nId, 0); nId = NULL; } if (uuidStr != NULL) { env->ReleaseStringUTFChars(uuid, uuidStr); uuidStr = NULL; } if (typeStr != NULL) { env->ReleaseStringUTFChars(type, typeStr); typeStr = NULL; } return AudioEffectJni::translateNativeErrorToJava(lStatus); } static void android_media_SourceDefaultEffect_native_release(JNIEnv *, jobject , jint id) { status_t lStatus = AudioEffect::removeSourceDefaultEffect(id); if (lStatus != NO_ERROR) { ALOGW("Error releasing SourceDefaultEffect: %d", lStatus); } } static const JNINativeMethod gMethods[] = { {"native_setup", "(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;[I)I", (void *)android_media_SourceDefaultEffect_native_setup}, {"native_release", "(I)V", (void *)android_media_SourceDefaultEffect_native_release}, }; int register_android_media_SourceDefaultEffect(JNIEnv *env) { return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); }
#define LOG_TAG "SourceDefaultEffect-JNI" #include <utils/Errors.h> #include <utils/Log.h> #include <jni.h> #include <nativehelper/JNIHelp.h> #include <android_runtime/AndroidRuntime.h> #include "media/AudioEffect.h" #include <nativehelper/ScopedUtfChars.h> #include "android_media_AudioEffect.h" using namespace android; static const char* const kClassPathName = "android/media/audiofx/SourceDefaultEffect"; static jint android_media_SourceDefaultEffect_native_setup(JNIEnv *env, jobject , jstring type, jstring uuid, jint priority, jint source, jstring opPackageName, jintArray jId) { ALOGV("android_media_SourceDefaultEffect_native_setup"); status_t lStatus = NO_ERROR; jint* nId = NULL; const char *typeStr = NULL; const char *uuidStr = NULL; ScopedUtfChars opPackageNameStr(env, opPackageName); if (type != NULL) { typeStr = env->GetStringUTFChars(type, NULL); if (typeStr == NULL) { lStatus = NO_MEMORY; jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); goto setup_exit; } } if (uuid != NULL) { uuidStr = env->GetStringUTFChars(uuid, NULL); if (uuidStr == NULL) { lStatus = NO_MEMORY; jniThrowException(env, "java/lang/RuntimeException", "Out of memory"); goto setup_exit; } } if (typeStr == NULL && uuidStr == NULL) { lStatus = BAD_VALUE; goto setup_exit; } nId = reinterpret_cast<jint *>(env->GetPrimitiveArrayCritical(jId, NULL)); if (nId == NULL) { ALOGE("setup: Error retrieving id pointer"); lStatus = BAD_VALUE; goto setup_exit; } audio_unique_id_t id; lStatus =
; if (lStatus != NO_ERROR) { ALOGE("setup: Error adding SourceDefaultEffect"); goto setup_exit; } nId[0] = static_cast<jint>(id); setup_exit: if (nId != NULL) { env->ReleasePrimitiveArrayCritical(jId, nId, 0); nId = NULL; } if (uuidStr != NULL) { env->ReleaseStringUTFChars(uuid, uuidStr); uuidStr = NULL; } if (typeStr != NULL) { env->ReleaseStringUTFChars(type, typeStr); typeStr = NULL; } return AudioEffectJni::translateNativeErrorToJava(lStatus); } static void android_media_SourceDefaultEffect_native_release(JNIEnv *, jobject , jint id) { status_t lStatus = AudioEffect::removeSourceDefaultEffect(id); if (lStatus != NO_ERROR) { ALOGW("Error releasing SourceDefaultEffect: %d", lStatus); } } static const JNINativeMethod gMethods[] = { {"native_setup", "(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;[I)I", (void *)android_media_SourceDefaultEffect_native_setup}, {"native_release", "(I)V", (void *)android_media_SourceDefaultEffect_native_release}, }; int register_android_media_SourceDefaultEffect(JNIEnv *env) { return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods)); }
AudioEffect::addSourceDefaultEffect(typeStr, String16(opPackageNameStr.c_str()), uuidStr, priority, static_cast<audio_source_t>(source), &id)
call_expression
[]
C++
zircon/system/uapp/iotime/iotime.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <block-client/client.h> #include <fuchsia/hardware/block/c/fidl.h> #include <lib/fzl/fdio.h> #include <lib/zx/channel.h> #include <lib/zx/fifo.h> #include <lib/zx/vmo.h> #include <ramdevice-client/ramdisk.h> #include <zircon/device/block.h> #include <zircon/syscalls.h> #include <zircon/time.h> #include <zircon/types.h> static uint64_t number(const char* str) { char* end; uint64_t n = strtoull(str, &end, 10); uint64_t m = 1; switch (*end) { case 'G': case 'g': m = 1024 * 1024 * 1024; break; case 'M': case 'm': m = 1024 * 1024; break; case 'K': case 'k': m = 1024; break; } return m * n; } static void bytes_per_second(uint64_t bytes, uint64_t nanos) { double s = ((double)nanos) / ((double)1000000000); double rate = ((double)bytes) / s; const char* unit = "B"; if (rate > 1024 * 1024) { unit = "MB"; rate /= 1024 * 1024; } else if (rate > 1024) { unit = "KB"; rate /= 1024; } fprintf(stderr, "%g %s/s\n", rate, unit); } static zx_duration_t iotime_posix(int is_read, int fd, size_t total, size_t bufsz) { void* buffer = malloc(bufsz); if (buffer == NULL) { fprintf(stderr, "error: out of memory\n"); return ZX_TIME_INFINITE; } zx_time_t t0 = zx_clock_get_monotonic(); size_t n = total; const char* fn_name = is_read ? "read" : "write"; while (n > 0) { size_t xfer = (n > bufsz) ? bufsz : n; ssize_t r = is_read ? read(fd, buffer, xfer) : write(fd, buffer, xfer); if (r < 0) { fprintf(stderr, "error: %s() error %d\n", fn_name, errno); return ZX_TIME_INFINITE; } if ((size_t)r != xfer) { fprintf(stderr, "error: %s() %zu of %zu bytes processed\n", fn_name, r, xfer); return ZX_TIME_INFINITE; } n -= xfer; } zx_time_t t1 = zx_clock_get_monotonic(); return zx_time_sub_time(t1, t0); } static zx_duration_t iotime_block(int is_read, int fd, size_t total, size_t bufsz) { if ((total % 4096) || (bufsz % 4096)) { fprintf(stderr, "error: total and buffer size must be multiples of 4K\n"); return ZX_TIME_INFINITE; } return iotime_posix(is_read, fd, total, bufsz); } static zx_duration_t iotime_fifo(char* dev, int is_read, int fd, size_t total, size_t bufsz) { zx_status_t status; zx::vmo vmo; if ((status = zx::vmo::create(bufsz, 0, &vmo)) != ZX_OK) { fprintf(stderr, "error: out of memory %d\n", status); return ZX_TIME_INFINITE; } fzl::UnownedFdioCaller disk_connection(fd); zx::unowned_channel channel(disk_connection.borrow_channel()); fuchsia_hardware_block_BlockInfo info; zx_status_t io_status = fuchsia_hardware_block_BlockGetInfo(channel->get(), &status, &info); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot get info for '%s'\n", dev); return ZX_TIME_INFINITE; } zx::fifo fifo; io_status = fuchsia_hardware_block_BlockGetFifo(channel->get(), &status, fifo.reset_and_get_address()); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot get fifo for '%s'\n", dev); return ZX_TIME_INFINITE; } groupid_t group = 0; zx::vmo dup; if ((status = vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &dup)) != ZX_OK) { fprintf(stderr, "error: cannot duplicate handle %d\n", status); return ZX_TIME_INFINITE; } fuchsia_hardware_block_VmoID vmoid; io_status = fuchsia_hardware_block_BlockAttachVmo(channel->get(), dup.release(), &status, &vmoid); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot attach vmo for '%s'\n", dev); return ZX_TIME_INFINITE; } fifo_client_t* client; if ((status = block_fifo_create_client(fifo.release(), &client)) != ZX_OK) { fprintf(stderr, "error: cannot create block client for '%s' %d\n", dev, status); return ZX_TIME_INFINITE; } zx_time_t t0 = zx_clock_get_monotonic(); size_t n = total; while (n > 0) { size_t xfer = (n > bufsz) ? bufsz : n; block_fifo_request_t request = { .opcode = static_cast<uint32_t>(is_read ? BLOCKIO_READ : BLOCKIO_WRITE), .reqid = 0, .group = group, .vmoid = vmoid.id, .length = static_cast<uint32_t>(xfer / info.block_size), .vmo_offset = 0, .dev_offset = (total - n) / info.block_size, }; if ((status = block_fifo_txn(client, &request, 1)) != ZX_OK) { fprintf(stderr, "error: block_fifo_txn error %d\n", status); return ZX_TIME_INFINITE; } n -= xfer; } zx_time_t t1 = zx_clock_get_monotonic(); return zx_time_sub_time(t1, t0); } static int usage(void) { fprintf(stderr, "usage: iotime <read|write> <posix|block|fifo> <device|--ramdisk> <bytes> <bufsize>\n\n" " <bytes> and <bufsize> must be a multiple of 4k for block mode\n" " --ramdisk only supported for block mode\n"); return -1; } int main(int argc, char** argv) { if (argc != 6) { return usage(); } int is_read = !strcmp(argv[1], "read"); size_t total = number(argv[4]); size_t bufsz = number(argv[5]); int r = -1; ramdisk_client_t* ramdisk = NULL; int fd; if (!strcmp(argv[3], "--ramdisk")) { if (strcmp(argv[2], "block")) { fprintf(stderr, "ramdisk only supported for block\n"); goto done; } zx_status_t status = ramdisk_create(512, total / 512, &ramdisk); if (status != ZX_OK) { fprintf(stderr, "error: cannot create %zu-byte ramdisk\n", total); goto done; } fd = ramdisk_get_block_fd(ramdisk); } else { if ((fd = open(argv[3], is_read ? O_RDONLY : O_WRONLY)) < 0) { fprintf(stderr, "error: cannot open '%s'\n", argv[3]); goto done; } } zx_duration_t res; if (!strcmp(argv[2], "posix")) { res = iotime_posix(is_read, fd, total, bufsz); } else if (!strcmp(argv[2], "block")) { res = iotime_block(is_read, fd, total, bufsz); } else if (!strcmp(argv[2], "fifo")) { res = iotime_fifo(argv[3], is_read, fd, total, bufsz); } else { fprintf(stderr, "error: unknown mode '%s'\n", argv[2]); goto done; } if (res != ZX_TIME_INFINITE) { fprintf(stderr, "%s %zu bytes in %zu ns: ", is_read ? "read" : "write", total, res); bytes_per_second(total, res); r = 0; goto done; } else { goto done; } done: if (ramdisk != NULL) { ramdisk_destroy(ramdisk); } return r; }
#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <block-client/client.h> #include <fuchsia/hardware/block/c/fidl.h> #include <lib/fzl/fdio.h> #include <lib/zx/channel.h> #include <lib/zx/fifo.h> #include <lib/zx/vmo.h> #include <ramdevice-client/ramdisk.h> #include <zircon/device/block.h> #include <zircon/syscalls.h> #include <zircon/time.h> #include <zircon/types.h> static uint64_t number(const char* str) { char* end; uint64_t n = strtoull(str, &end, 10); uint64_t m = 1; switch (*end) { case 'G': case 'g': m = 1024 * 1024 * 1024; break; case 'M': case 'm': m = 1024 * 1024; break; case 'K': case 'k': m = 1024; break; } return m * n; } static void bytes_per_second(uint64_t bytes, uint64_t nanos) { double s = ((double)nanos) / ((double)1000000000); double rate = ((double)bytes) / s; const char* unit = "B"; if (rate > 1024 * 1024) { unit = "MB"; rate /= 1024 * 1024; } else if (rate > 1024) { unit = "KB"; rate /= 1024; } fprintf(std
r, "error: out of memory\n"); return ZX_TIME_INFINITE; } zx_time_t t0 = zx_clock_get_monotonic(); size_t n = total; const char* fn_name = is_read ? "read" : "write"; while (n > 0) { size_t xfer = (n > bufsz) ? bufsz : n; ssize_t r = is_read ? read(fd, buffer, xfer) : write(fd, buffer, xfer); if (r < 0) { fprintf(stderr, "error: %s() error %d\n", fn_name, errno); return ZX_TIME_INFINITE; } if ((size_t)r != xfer) { fprintf(stderr, "error: %s() %zu of %zu bytes processed\n", fn_name, r, xfer); return ZX_TIME_INFINITE; } n -= xfer; } zx_time_t t1 = zx_clock_get_monotonic(); return zx_time_sub_time(t1, t0); } static zx_duration_t iotime_block(int is_read, int fd, size_t total, size_t bufsz) { if ((total % 4096) || (bufsz % 4096)) { fprintf(stderr, "error: total and buffer size must be multiples of 4K\n"); return ZX_TIME_INFINITE; } return iotime_posix(is_read, fd, total, bufsz); } static zx_duration_t iotime_fifo(char* dev, int is_read, int fd, size_t total, size_t bufsz) { zx_status_t status; zx::vmo vmo; if ((status = zx::vmo::create(bufsz, 0, &vmo)) != ZX_OK) { fprintf(stderr, "error: out of memory %d\n", status); return ZX_TIME_INFINITE; } fzl::UnownedFdioCaller disk_connection(fd); zx::unowned_channel channel(disk_connection.borrow_channel()); fuchsia_hardware_block_BlockInfo info; zx_status_t io_status = fuchsia_hardware_block_BlockGetInfo(channel->get(), &status, &info); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot get info for '%s'\n", dev); return ZX_TIME_INFINITE; } zx::fifo fifo; io_status = fuchsia_hardware_block_BlockGetFifo(channel->get(), &status, fifo.reset_and_get_address()); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot get fifo for '%s'\n", dev); return ZX_TIME_INFINITE; } groupid_t group = 0; zx::vmo dup; if ((status = vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &dup)) != ZX_OK) { fprintf(stderr, "error: cannot duplicate handle %d\n", status); return ZX_TIME_INFINITE; } fuchsia_hardware_block_VmoID vmoid; io_status = fuchsia_hardware_block_BlockAttachVmo(channel->get(), dup.release(), &status, &vmoid); if (io_status != ZX_OK || status != ZX_OK) { fprintf(stderr, "error: cannot attach vmo for '%s'\n", dev); return ZX_TIME_INFINITE; } fifo_client_t* client; if ((status = block_fifo_create_client(fifo.release(), &client)) != ZX_OK) { fprintf(stderr, "error: cannot create block client for '%s' %d\n", dev, status); return ZX_TIME_INFINITE; } zx_time_t t0 = zx_clock_get_monotonic(); size_t n = total; while (n > 0) { size_t xfer = (n > bufsz) ? bufsz : n; block_fifo_request_t request = { .opcode = static_cast<uint32_t>(is_read ? BLOCKIO_READ : BLOCKIO_WRITE), .reqid = 0, .group = group, .vmoid = vmoid.id, .length = static_cast<uint32_t>(xfer / info.block_size), .vmo_offset = 0, .dev_offset = (total - n) / info.block_size, }; if ((status = block_fifo_txn(client, &request, 1)) != ZX_OK) { fprintf(stderr, "error: block_fifo_txn error %d\n", status); return ZX_TIME_INFINITE; } n -= xfer; } zx_time_t t1 = zx_clock_get_monotonic(); return zx_time_sub_time(t1, t0); } static int usage(void) { fprintf(stderr, "usage: iotime <read|write> <posix|block|fifo> <device|--ramdisk> <bytes> <bufsize>\n\n" " <bytes> and <bufsize> must be a multiple of 4k for block mode\n" " --ramdisk only supported for block mode\n"); return -1; } int main(int argc, char** argv) { if (argc != 6) { return usage(); } int is_read = !strcmp(argv[1], "read"); size_t total = number(argv[4]); size_t bufsz = number(argv[5]); int r = -1; ramdisk_client_t* ramdisk = NULL; int fd; if (!strcmp(argv[3], "--ramdisk")) { if (strcmp(argv[2], "block")) { fprintf(stderr, "ramdisk only supported for block\n"); goto done; } zx_status_t status = ramdisk_create(512, total / 512, &ramdisk); if (status != ZX_OK) { fprintf(stderr, "error: cannot create %zu-byte ramdisk\n", total); goto done; } fd = ramdisk_get_block_fd(ramdisk); } else { if ((fd = open(argv[3], is_read ? O_RDONLY : O_WRONLY)) < 0) { fprintf(stderr, "error: cannot open '%s'\n", argv[3]); goto done; } } zx_duration_t res; if (!strcmp(argv[2], "posix")) { res = iotime_posix(is_read, fd, total, bufsz); } else if (!strcmp(argv[2], "block")) { res = iotime_block(is_read, fd, total, bufsz); } else if (!strcmp(argv[2], "fifo")) { res = iotime_fifo(argv[3], is_read, fd, total, bufsz); } else { fprintf(stderr, "error: unknown mode '%s'\n", argv[2]); goto done; } if (res != ZX_TIME_INFINITE) { fprintf(stderr, "%s %zu bytes in %zu ns: ", is_read ? "read" : "write", total, res); bytes_per_second(total, res); r = 0; goto done; } else { goto done; } done: if (ramdisk != NULL) { ramdisk_destroy(ramdisk); } return r; }
err, "%g %s/s\n", rate, unit); } static zx_duration_t iotime_posix(int is_read, int fd, size_t total, size_t bufsz) { void* buffer = malloc(bufsz); if (buffer == NULL) { fprintf(stder
random
[]
C++
old/v2/src/sim/Maze.cpp
qiuwenhui/micromouse_-simulator
6625b2814b8281a0db5d4e9d57ae8881ff31fed0
#include "Maze.h" #include <queue> #include <set> #include <vector> #include "../maze/IMazeAlgorithm.h" #include "../maze/MazeAlgorithms.h" #include "Assert.h" #include "Directory.h" #include "Logging.h" #include "MazeChecker.h" #include "MazeFileType.h" #include "MazeFileUtilities.h" #include "MazeInterface.h" #include "Param.h" #include "SimUtilities.h" #include "Tile.h" namespace sim { Maze::Maze() { std::vector<std::vector<BasicTile>> basicMaze; if (P()->useMazeFile()) { std::string mazeFilePath = Directory::getResMazeDirectory() + P()->mazeFile(); try { basicMaze = MazeFileUtilities::loadMaze(mazeFilePath); } catch (...) { std::string reason = ( SimUtilities::isFile(mazeFilePath) ? "invalid format" : "file doesn't exist"); L()->error( "Unable to initialize maze from file \"%v\": %v.", mazeFilePath, reason); SimUtilities::quit(); } } else { if (!MazeAlgorithms::isMazeAlgorithm(P()->mazeAlgorithm())) { L()->error("\"%v\" is not a valid maze algorithm.", P()->mazeAlgorithm()); SimUtilities::quit(); } basicMaze = getBlankBasicMaze(P()->generatedMazeWidth(), P()->generatedMazeHeight()); MazeInterface mazeInterface(&basicMaze); MazeAlgorithms::getMazeAlgorithm(P()->mazeAlgorithm())->generate( P()->generatedMazeWidth(), P()->generatedMazeHeight(), &mazeInterface); } m_isValidMaze = MazeChecker::isValidMaze(basicMaze); if (!m_isValidMaze) { L()->warn("The maze failed validation. The mouse algorithm will not execute."); } if (!P()->useMazeFile() && P()->saveGeneratedMaze()) { MazeFileType type = STRING_TO_MAZE_FILE_TYPE.at(P()->generatedMazeType()); std::string mazeFilePath = Directory::getResMazeDirectory() + P()->generatedMazeFile() + MAZE_FILE_TYPE_TO_SUFFIX.at(type); bool success = MazeFileUtilities::saveMaze(basicMaze, mazeFilePath, type); if (success) { L()->info("Maze saved to \"%v\".", mazeFilePath); } else { L()->warn("Unable to save maze to \"%v\".", mazeFilePath); } } if (P()->mazeMirrored()) { basicMaze = mirrorAcrossVertical(basicMaze); L()->info("Mirroring the maze across the vertical."); } for (int i = 0; i < P()->mazeRotations(); i += 1) { basicMaze = rotateCounterClockwise(basicMaze); L()->info("Rotating the maze counter-clockwise (%vx).", i + 1); } m_isOfficialMaze = m_isValidMaze && MazeChecker::isOfficialMaze(basicMaze); if (m_isValidMaze && !m_isOfficialMaze) { L()->warn("The maze did not pass the \"is official maze\" tests."); } m_maze = initializeFromBasicMaze(basicMaze); } int Maze::getWidth() const { return m_maze.size(); } int Maze::getHeight() const { return (m_maze.size() > 0 ? m_maze.at(0).size() : 0); } bool Maze::withinMaze(int x, int y) const { return 0 <= x && x < getWidth() && 0 <= y && y < getHeight(); } Tile* Maze::getTile(int x, int y) { SIM_ASSERT_TR(withinMaze(x, y)); return &m_maze.at(x).at(y); } const Tile* Maze::getTile(int x, int y) const { SIM_ASSERT_TR(withinMaze(x, y)); return &m_maze.at(x).at(y); } bool Maze::isValidMaze() const { return m_isOfficialMaze; } bool Maze::isOfficialMaze() const { return m_isOfficialMaze; } bool Maze::isCenterTile(int x, int y) const { return ContainerUtilities::vectorContains( MazeChecker::getCenterTiles(getWidth(), getHeight()), std::make_pair(x, y) ); } std::vector<std::vector<Tile>> Maze::initializeFromBasicMaze(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<Tile>> maze; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<Tile> column; for (int y = 0; y < basicMaze.at(x).size(); y += 1) { Tile tile; tile.setPos(x, y); for (Direction direction : DIRECTIONS) { tile.setWall(direction, basicMaze.at(x).at(y).walls.at(direction)); } tile.initPolygons(basicMaze.size(), basicMaze.at(x).size()); column.push_back(tile); } maze.push_back(column); } maze = setTileDistances(maze); return maze; } std::vector<std::vector<BasicTile>> Maze::getBlankBasicMaze(int mazeWidth, int mazeHeight) { std::vector<std::vector<BasicTile>> blankMaze; for (int x = 0; x < mazeWidth; x += 1) { std::vector<BasicTile> column; for (int y = 0; y < mazeHeight; y += 1) { BasicTile tile; for (Direction direction : DIRECTIONS) { tile.walls.insert(std::make_pair(direction, false)); } column.push_back(tile); } blankMaze.push_back(column); } return blankMaze; } std::vector<std::vector<BasicTile>> Maze::mirrorAcrossVertical(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<BasicTile>> mirrored; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<BasicTile> column; for (int y = 0; y < basicMaze.at(x).size(); y += 1) { BasicTile tile; tile.walls.insert(std::make_pair(Direction::NORTH, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::NORTH))); tile.walls.insert(std::make_pair(Direction::EAST, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::WEST))); tile.walls.insert(std::make_pair(Direction::SOUTH, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::SOUTH))); tile.walls.insert(std::make_pair(Direction::WEST, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::EAST))); column.push_back(tile); } mirrored.push_back(column); } return mirrored; } std::vector<std::vector<BasicTile>> Maze::rotateCounterClockwise(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<BasicTile>> rotated; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<BasicTile> row; for (int y = basicMaze.at(x).size() - 1; y >= 0; y -= 1) { BasicTile tile; int rotatedTileX = basicMaze.at(x).size() - 1 - y; tile.walls.insert(std::make_pair(Direction::NORTH, basicMaze.at(x).at(y).walls.at(Direction::EAST))); tile.walls.insert(std::make_pair(Direction::EAST, basicMaze.at(x).at(y).walls.at(Direction::SOUTH))); tile.walls.insert(std::make_pair(Direction::SOUTH, basicMaze.at(x).at(y).walls.at(Direction::WEST))); tile.walls.insert(std::make_pair(Direction::WEST, basicMaze.at(x).at(y).walls.at(Direction::NORTH))); if (rotated.size() <= rotatedTileX) { rotated.push_back({tile}); } else { rotated.at(rotatedTileX).push_back(tile); } } } return rotated; } std::vector<std::vector<Tile>> Maze::setTileDistances(std::vector<std::vector<Tile>> maze) { int width = maze.size(); int height = maze.at(0).size(); auto getNeighbor = [&maze, &width, &height](int x, int y, Direction direction) { switch (direction) { case Direction::NORTH: return (y < height - 1 ? &maze.at(x).at(y + 1) : nullptr); case Direction::EAST: return (x < width - 1 ? &maze.at(x + 1).at(y) : nullptr); case Direction::SOUTH: return (0 < y ? &maze.at(x).at(y - 1) : nullptr); case Direction::WEST: return (0 < x ? &maze.at(x - 1).at(y) : nullptr); } }; std::vector<Tile*> centerTiles; centerTiles.push_back(&maze.at((width - 1) / 2).at((height - 1) / 2)); if (width % 2 == 0) { centerTiles.push_back(&maze.at( width / 2).at((height - 1) / 2)); if (height % 2 == 0) { centerTiles.push_back(&maze.at((width - 1) / 2).at( height / 2)); centerTiles.push_back(&maze.at( width / 2).at( height / 2)); } } else if (height % 2 == 0) { centerTiles.push_back(&maze.at((width - 1) / 2).at( height / 2)); } std::queue<Tile*> discovered; for (Tile* tile : centerTiles) { tile->setDistance(0); discovered.push(tile); } while (!discovered.empty()){ Tile* tile = discovered.front(); discovered.pop(); for (Direction direction : DIRECTIONS) { if (!tile->isWall(direction)) { Tile* neighbor = getNeighbor(tile->getX(), tile->getY(), direction); if (neighbor != nullptr && neighbor->getDistance() == -1) { neighbor->setDistance(tile->getDistance() + 1); discovered.push(neighbor); } } } } return maze; } }
#include "Maze.h" #include <queue> #include <set> #include <vector> #include "../maze/IMazeAlgorithm.h" #include "../maze/MazeAlgorithms.h" #include "Assert.h" #include "Directory.h" #include "Logging.h" #include "MazeChecker.h" #include "MazeFileType.h" #include "MazeFileUtilities.h" #include "MazeInterface.h" #include "Param.h" #include "SimUtilities.h" #include "Tile.h" namespace sim { Maze::Maze() { std::vector<std::vector<BasicTile>> basicMaze; if (P()->useMazeFile()) { std::string mazeFilePath = Directory::getResMazeDirectory() + P()->mazeFile(); try { basicMaze = MazeFileUtilities::loadMaze(mazeFilePath); } catch (...) { std::string reason = ( SimUtilities::isFile(mazeFilePath) ? "invalid format" : "file doesn't exist"); L()->error( "Unable to initialize maze from file \"%v\": %v.", mazeFilePath, reason); SimUtilities::quit(); } } else { if (!MazeAlgorithms::isMazeAlgorithm(P()->mazeAlgorithm())) { L()->error("\"%v\" is not a valid maze algorithm.", P()->mazeAlgorithm()); SimUtilities::quit(); } basicMaze = getBlankBasicMaze(P()->generatedMazeWidth(), P()->generatedMazeHeight()); MazeInterface mazeInterface(&basicMaze); MazeAlgorithms::getMazeAlgorithm(P()->mazeAlgorithm())->generate( P()->generatedMazeWidth(), P()->generatedMazeHeight(), &mazeInterface); } m_isValidMaze = MazeChecker::isValidMaze(basicMaze); if (!m_isValidMaze) { L()->warn("The maze failed validation. The mouse algorithm will not execute."); } if (!P()->useMazeFile() && P()->saveGeneratedMaze()) { MazeFileType type = STRING_TO_MAZE_FILE_TYPE.at(P()->generatedMazeType()); std::string mazeFilePath = Directory::getResMazeDirectory() + P()->generatedMazeFile() + MAZE_FILE_TYPE_TO_SUFFIX.at(type); bool success = MazeFileUtilities::saveMaze(basicMaze, mazeFilePath, type); if (success) { L()->info("Maze saved to \"%v\".", mazeFilePath); } else { L()->warn("Unable to save maze to \"%v\".", mazeFilePath); } } if (P()->mazeMirrored()) { basicMaze = mirrorAcrossVertical(basicMaze); L()->info("Mirroring the maze across the vertical."); } for (int i = 0; i < P()->mazeRotations(); i += 1) { basicMaze = rotateCounterClockwise(basicMaze); L()->info("Rotating the maze counter-clockwise (%vx).", i + 1); } m_isOfficialMaze = m_isValidMaze && MazeChecker::isOfficialMaze(basicMaze); if (m_isValidMaze && !m_isOfficialMaze) { L()->warn("The maze did not pass the \"is official maze\" tests."); } m_maze = initializeFromBasicMaze(basicMaze); } int Maze::getWidth() const { return m_maze.size(); } int Maze::getHeight() const { return (m_maze.size() > 0 ? m_maze.at(0).size() : 0); } bool Maze::withinMaze(int x, int y) const { return 0 <= x && x < getWidth() && 0 <= y && y < getHeight(); } Tile* Maze::getTile(int x, int y) { SIM_ASSERT_TR(withinMaze(x, y)); return &m_maze.at(x).at(y); } const Tile* Maze::getTile(int x, int y) const { SIM_ASSERT_TR(withinMaze(x, y)); return &m_maze.at(x).at(y); } bool Maze::isValidMaze() const { return m_isOfficialMaze; } bool Maze::isOfficialMaze() const { return m_isOfficialMaze; } bool Maze::isCenterTile(int x, int y) const { return ContainerUtilities::vectorContains( MazeChecker::getCenterTiles(getWidth(), getHeight()), std::make_pair(x, y) ); } std::vector<std::vector<Tile>> Maze::initializeFromBasicMaze(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<Tile>> maze; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<Tile> column; for (int y = 0; y < basicMaze.at(x).size(); y += 1) { Tile tile; tile.setPos(x, y); for (Direction direction : DIRECTIONS) { tile.setWall(direction, basicMaze.at(x).at(y).walls.at(direction)); } tile.initPolygons(basicMaze.size(), basicMaze.at(x).size()); column.push_back(tile); } maze.push_back(column); } maze = setTileDistances(maze); return maze; } std::vector<std::vector<BasicTile>> Maze::getBlankBasicMaze(int
} } return rotated; } std::vector<std::vector<Tile>> Maze::setTileDistances(std::vector<std::vector<Tile>> maze) { int width = maze.size(); int height = maze.at(0).size(); auto getNeighbor = [&maze, &width, &height](int x, int y, Direction direction) { switch (direction) { case Direction::NORTH: return (y < height - 1 ? &maze.at(x).at(y + 1) : nullptr); case Direction::EAST: return (x < width - 1 ? &maze.at(x + 1).at(y) : nullptr); case Direction::SOUTH: return (0 < y ? &maze.at(x).at(y - 1) : nullptr); case Direction::WEST: return (0 < x ? &maze.at(x - 1).at(y) : nullptr); } }; std::vector<Tile*> centerTiles; centerTiles.push_back(&maze.at((width - 1) / 2).at((height - 1) / 2)); if (width % 2 == 0) { centerTiles.push_back(&maze.at( width / 2).at((height - 1) / 2)); if (height % 2 == 0) { centerTiles.push_back(&maze.at((width - 1) / 2).at( height / 2)); centerTiles.push_back(&maze.at( width / 2).at( height / 2)); } } else if (height % 2 == 0) { centerTiles.push_back(&maze.at((width - 1) / 2).at( height / 2)); } std::queue<Tile*> discovered; for (Tile* tile : centerTiles) { tile->setDistance(0); discovered.push(tile); } while (!discovered.empty()){ Tile* tile = discovered.front(); discovered.pop(); for (Direction direction : DIRECTIONS) { if (!tile->isWall(direction)) { Tile* neighbor = getNeighbor(tile->getX(), tile->getY(), direction); if (neighbor != nullptr && neighbor->getDistance() == -1) { neighbor->setDistance(tile->getDistance() + 1); discovered.push(neighbor); } } } } return maze; } }
mazeWidth, int mazeHeight) { std::vector<std::vector<BasicTile>> blankMaze; for (int x = 0; x < mazeWidth; x += 1) { std::vector<BasicTile> column; for (int y = 0; y < mazeHeight; y += 1) { BasicTile tile; for (Direction direction : DIRECTIONS) { tile.walls.insert(std::make_pair(direction, false)); } column.push_back(tile); } blankMaze.push_back(column); } return blankMaze; } std::vector<std::vector<BasicTile>> Maze::mirrorAcrossVertical(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<BasicTile>> mirrored; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<BasicTile> column; for (int y = 0; y < basicMaze.at(x).size(); y += 1) { BasicTile tile; tile.walls.insert(std::make_pair(Direction::NORTH, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::NORTH))); tile.walls.insert(std::make_pair(Direction::EAST, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::WEST))); tile.walls.insert(std::make_pair(Direction::SOUTH, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::SOUTH))); tile.walls.insert(std::make_pair(Direction::WEST, basicMaze.at(basicMaze.size() - 1 - x).at(y).walls.at(Direction::EAST))); column.push_back(tile); } mirrored.push_back(column); } return mirrored; } std::vector<std::vector<BasicTile>> Maze::rotateCounterClockwise(const std::vector<std::vector<BasicTile>>& basicMaze) { std::vector<std::vector<BasicTile>> rotated; for (int x = 0; x < basicMaze.size(); x += 1) { std::vector<BasicTile> row; for (int y = basicMaze.at(x).size() - 1; y >= 0; y -= 1) { BasicTile tile; int rotatedTileX = basicMaze.at(x).size() - 1 - y; tile.walls.insert(std::make_pair(Direction::NORTH, basicMaze.at(x).at(y).walls.at(Direction::EAST))); tile.walls.insert(std::make_pair(Direction::EAST, basicMaze.at(x).at(y).walls.at(Direction::SOUTH))); tile.walls.insert(std::make_pair(Direction::SOUTH, basicMaze.at(x).at(y).walls.at(Direction::WEST))); tile.walls.insert(std::make_pair(Direction::WEST, basicMaze.at(x).at(y).walls.at(Direction::NORTH))); if (rotated.size() <= rotatedTileX) { rotated.push_back({tile}); } else { rotated.at(rotatedTileX).push_back(tile); }
random
[ { "content": "class Test : public IMouseAlgorithm {\n\n\n\npublic:\n\n std::string mouseFile() const;\n\n std::string interfaceType() const;\n\n void solve(\n\n int mazeWidth, int mazeHeight, bool isOfficialMaze,\n\n char initialDirection, sim::MouseInterface* mouse);\n\n\n\n};\n\n\n\n} /...
C++
libc/winsup/cygwin/fhandler_procsys.cc
The0x539/wasp
5f83aab7bf0c0915b1d3491034d35b091c7aebdf
#include "winsup.h" #include <stdlib.h> #include "cygerrno.h" #include "security.h" #include "path.h" #include "fhandler.h" #include "dtable.h" #include "cygheap.h" #include <winioctl.h> #include "ntdll.h" #include "tls_pbuf.h" #include <dirent.h> const char procsys[] = "/proc/sys"; const size_t procsys_len = sizeof (procsys) - 1; #define mk_unicode_path(p) \ WCHAR namebuf[strlen (get_name ()) + 1]; \ { \ const char *from; \ PWCHAR to; \ for (to = namebuf, from = get_name () + procsys_len; *from; \ to++, from++) \ \ *to = (*from == '/') ? L'\\' : (WCHAR) *from; \ if (to == namebuf) \ *to++ = L'\\'; \ *to = L'\0'; \ RtlInitUnicodeString ((p), namebuf); \ } virtual_ftype_t fhandler_procsys::exists (struct stat *buf) { UNICODE_STRING path; UNICODE_STRING dir; OBJECT_ATTRIBUTES attr; IO_STATUS_BLOCK io; NTSTATUS status; HANDLE h; FILE_BASIC_INFORMATION fbi; bool internal = false; bool desperate_parent_check = false; virtual_ftype_t file_type = virt_chr; if (strlen (get_name ()) == procsys_len) return virt_rootdir; mk_unicode_path (&path); RtlSplitUnicodePath (&path, &dir, NULL); if (dir.Length > sizeof (WCHAR)) dir.Length -= sizeof (WCHAR); InitializeObjectAttributes (&attr, &dir, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject (&h, DIRECTORY_QUERY, &attr); debug_printf ("NtOpenDirectoryObject: %y", status); if (NT_SUCCESS (status)) { internal = true; NtClose (h); } InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenSymbolicLinkObject (&h, READ_CONTROL | SYMBOLIC_LINK_QUERY, &attr); debug_printf ("NtOpenSymbolicLinkObject: %y", status); if (NT_SUCCESS (status)) { if (buf) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); NtClose (h); return virt_symlink; } else if (status == STATUS_ACCESS_DENIED) return virt_symlink; status = NtOpenDirectoryObject (&h, READ_CONTROL | DIRECTORY_QUERY, &attr); debug_printf ("NtOpenDirectoryObject: %y", status); if (NT_SUCCESS (status)) { if (buf) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); NtClose (h); return virt_directory; } else if (status == STATUS_ACCESS_DENIED) return virt_directory; status = NtOpenFile (&h, READ_CONTROL | FILE_READ_ATTRIBUTES, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_OPEN_FOR_BACKUP_INTENT); debug_printf ("NtOpenFile: %y", status); if (status == STATUS_OBJECT_NAME_INVALID) return virt_none; if (status == STATUS_NO_MEDIA_IN_DEVICE || status == STATUS_SHARING_VIOLATION) return virt_fsfile; if (status == STATUS_OBJECT_PATH_NOT_FOUND || status == STATUS_OBJECT_NAME_NOT_FOUND) return virt_fsfile; if (status >= STATUS_PIPE_NOT_AVAILABLE && status <= STATUS_PIPE_BUSY) return virt_pipe; if (status == STATUS_ACCESS_DENIED && !internal) { status = NtQueryAttributesFile (&attr, &fbi); debug_printf ("NtQueryAttributesFile: %y", status); if (NT_SUCCESS (status)) return (fbi.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? virt_fsdir : virt_fsfile; dir = path; InitializeObjectAttributes (&attr, &dir, OBJ_CASE_INSENSITIVE, NULL, NULL); do { RtlSplitUnicodePath (&dir, &dir, NULL); status = NtOpenFile (&h, READ_CONTROL | FILE_READ_ATTRIBUTES, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_OPEN_FOR_BACKUP_INTENT); debug_printf ("NtOpenDirectoryObject: %y", status); if (dir.Length > sizeof (WCHAR)) dir.Length -= sizeof (WCHAR); } while (dir.Length > sizeof (WCHAR) && !NT_SUCCESS (status)); desperate_parent_check = true; } if (NT_SUCCESS (status)) { FILE_FS_DEVICE_INFORMATION ffdi; if (buf && !desperate_parent_check) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); status = NtQueryVolumeInformationFile (h, &io, &ffdi, sizeof ffdi, FileFsDeviceInformation); debug_printf ("NtQueryVolumeInformationFile: %y", status); if (NT_SUCCESS (status)) { if (ffdi.DeviceType == FILE_DEVICE_NETWORK_FILE_SYSTEM) file_type = virt_blk; else if (ffdi.DeviceType == FILE_DEVICE_NAMED_PIPE) file_type = internal ? virt_blk : virt_pipe; else if (ffdi.DeviceType == FILE_DEVICE_DISK || ffdi.DeviceType == FILE_DEVICE_CD_ROM || ffdi.DeviceType == FILE_DEVICE_DFS || ffdi.DeviceType == FILE_DEVICE_VIRTUAL_DISK) { status = NtQueryInformationFile (h, &io, &fbi, sizeof fbi, FileBasicInformation); debug_printf ("NtQueryInformationFile: %y", status); if (!NT_SUCCESS (status)) file_type = virt_blk; else file_type = (fbi.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? virt_fsdir : virt_fsfile; } } NtClose (h); } return file_type; } virtual_ftype_t fhandler_procsys::exists () { return exists (NULL); } fhandler_procsys::fhandler_procsys (): fhandler_virtual () { } #define UNREADABLE_SYMLINK_CONTENT "<access denied>" bool fhandler_procsys::fill_filebuf () { char *fnamep; UNICODE_STRING path, target; OBJECT_ATTRIBUTES attr; NTSTATUS status; HANDLE h; tmp_pathbuf tp; size_t len; mk_unicode_path (&path); if (path.Buffer[path.Length / sizeof (WCHAR) - 1] == L'\\') path.Length -= sizeof (WCHAR); InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenSymbolicLinkObject (&h, SYMBOLIC_LINK_QUERY, &attr); if (!NT_SUCCESS (status)) goto unreadable; RtlInitEmptyUnicodeString (&target, tp.w_get (), (NT_MAX_PATH - 1) * sizeof (WCHAR)); status = NtQuerySymbolicLinkObject (h, &target, NULL); NtClose (h); if (!NT_SUCCESS (status)) goto unreadable; len = sys_wcstombs (NULL, 0, target.Buffer, target.Length / sizeof (WCHAR)); filebuf = (char *) crealloc_abort (filebuf, procsys_len + len + 1); sys_wcstombs (fnamep = stpcpy (filebuf, procsys), len + 1, target.Buffer, target.Length / sizeof (WCHAR)); while ((fnamep = strchr (fnamep, '\\'))) *fnamep = '/'; return true; unreadable: filebuf = (char *) crealloc_abort (filebuf, sizeof (UNREADABLE_SYMLINK_CONTENT)); strcpy (filebuf, UNREADABLE_SYMLINK_CONTENT); return false; } int __reg2 fhandler_procsys::fstat (struct stat *buf) { const char *path = get_name (); debug_printf ("fstat (%s)", path); fhandler_base::fstat (buf); buf->st_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; buf->st_uid = 544; buf->st_gid = 18; buf->st_dev = buf->st_rdev = dev (); buf->st_ino = get_ino (); switch (exists (buf)) { case virt_directory: case virt_rootdir: case virt_fsdir: buf->st_mode |= S_IFDIR; if (buf->st_mode & S_IRUSR) buf->st_mode |= S_IXUSR; if (buf->st_mode & S_IRGRP) buf->st_mode |= S_IXGRP; if (buf->st_mode & S_IROTH) buf->st_mode |= S_IXOTH; break; case virt_file: case virt_fsfile: buf->st_mode |= S_IFREG; break; case virt_symlink: buf->st_mode |= S_IFLNK; break; case virt_pipe: buf->st_mode |= S_IFIFO; break; case virt_socket: buf->st_mode |= S_IFSOCK; break; case virt_chr: buf->st_mode |= S_IFCHR; break; case virt_blk: buf->st_mode |= S_IFBLK; break; default: set_errno (ENOENT); return -1; } return 0; } DIR * fhandler_procsys::opendir (int fd) { UNICODE_STRING path; OBJECT_ATTRIBUTES attr; NTSTATUS status; HANDLE h; DIR *dir; mk_unicode_path (&path); InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject (&h, DIRECTORY_QUERY, &attr); if (!NT_SUCCESS (status)) { __seterrno_from_nt_status (status); return NULL; } if (!(dir = fhandler_virtual::opendir (fd))) NtClose (h); else dir->__handle = h; return dir; } int fhandler_procsys::readdir (DIR *dir, dirent *de) { NTSTATUS status; struct fdbi { DIRECTORY_BASIC_INFORMATION dbi; WCHAR buf[2][NAME_MAX + 1]; } f; int res = EBADF; if (dir->__handle != INVALID_HANDLE_VALUE) { BOOLEAN restart = dir->__d_position ? FALSE : TRUE; status = NtQueryDirectoryObject (dir->__handle, &f, sizeof f, TRUE, restart, (PULONG) &dir->__d_position, NULL); if (!NT_SUCCESS (status)) res = ENMFILE; else { sys_wcstombs (de->d_name, NAME_MAX + 1, f.dbi.ObjectName.Buffer, f.dbi.ObjectName.Length / sizeof (WCHAR)); de->d_ino = hash_path_name (get_ino (), de->d_name); if (RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natdir, FALSE)) de->d_type = DT_DIR; else if (RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natsyml, FALSE)) de->d_type = DT_LNK; else if (!RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natdev, FALSE)) de->d_type = DT_CHR; else de->d_type = DT_UNKNOWN; res = 0; } } syscall_printf ("%d = readdir(%p, %p)", res, dir, de); return res; } long fhandler_procsys::telldir (DIR *dir) { return dir->__d_position; } void fhandler_procsys::seekdir (DIR *dir, long pos) { dir->__d_position = pos; } int fhandler_procsys::closedir (DIR *dir) { if (dir->__handle != INVALID_HANDLE_VALUE) { NtClose (dir->__handle); dir->__handle = INVALID_HANDLE_VALUE; } return fhandler_virtual::closedir (dir); } void __reg3 fhandler_procsys::read (void *ptr, size_t& len) { fhandler_base::raw_read (ptr, len); } ssize_t __stdcall fhandler_procsys::write (const void *ptr, size_t len) { return fhandler_base::raw_write (ptr, len); } int fhandler_procsys::open (int flags, mode_t mode) { int res = 0; if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) set_errno (EINVAL); else { switch (exists (NULL)) { case virt_directory: case virt_rootdir: if ((flags & O_ACCMODE) != O_RDONLY) set_errno (EISDIR); else { nohandle (true); res = 1; } break; case virt_none: set_errno (ENOENT); break; default: res = fhandler_base::open (flags, mode); break; } } syscall_printf ("%d = fhandler_procsys::open(%p, 0%o)", res, flags, mode); return res; } int fhandler_procsys::close () { if (!nohandle ()) NtClose (get_handle ()); return fhandler_virtual::close (); } #if 0 int fhandler_procsys::ioctl (unsigned int cmd, void *) { } #endif
#include "winsup.h" #include <stdlib.h> #include "cygerrno.h" #include "security.h" #include "path.h" #include "fhandler.h" #include "dtable.h" #include "cygheap.h" #include <winioctl.h> #include "ntdll.h" #include "tls_pbuf.h" #include <dirent.h> const char procsys[] = "/proc/sys"; const size_t procsys_len = sizeof (procsys) - 1; #define mk_unicode_path(p) \ WCHAR namebuf[strlen (get_name ()) + 1]; \ { \ const char *from; \ PWCHAR to; \ for (to = namebuf, from = get_name () + procsys_len; *from; \ to++, from++) \ \ *to = (*from == '/') ? L'\\' : (WCHAR) *from; \ if (to == namebuf) \ *to++ = L'\\'; \ *to = L'\0'; \ RtlInitUnicodeString ((p), namebuf); \ } virtual_ftype_t fhandler_procsys::exists (struct stat *buf) { UNICODE_STRING path; UNICODE_STRING dir; OBJECT_ATTRIBUTES attr; IO_STATUS_BLOCK io; NTSTATUS status; HANDLE h; FILE_BASIC_INFORMATION fbi; bool internal = false; bool desperate_parent_check = false; virtual_ftype_t file_type = virt_chr; if (strlen (get_name ()) == procsys_len) return virt_rootdir; mk_unicode_path (&path); RtlSplitUnicodePath (&path, &dir, NULL); if (dir.Length > sizeof (WCHAR)) dir.Length -= sizeof (WCHAR); InitializeObjectAttributes (&attr, &dir, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject (&h, DIRECTORY_QUERY, &attr); debug_printf ("NtOpenDirectoryObject: %y", status); if (NT_SUCCESS (status)) { internal = true; NtClose (h); } InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenSymbolicLinkObject (&h, READ_CONTROL | SYMBOLIC_LINK_QUERY, &attr); debug_printf ("NtOpenSymbolicLinkObject: %y", status); if (NT_SUCCESS (status)) { if (buf) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); NtClose (h); return virt_symlink; } else if (status == STATUS_ACCESS_DENIED) return virt_symlink; status = NtOpenDirectoryObject (&h, READ_CONTROL | DIRECTORY_QUERY, &attr); debug_printf ("NtOpenDirectoryObject: %y", status); if (NT_SUCCESS (status)) { if (buf) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); NtClose (h); return virt_directory; } else if (status == STATUS_ACCESS_DENIED) return virt_directory; status = NtOpenFile (&h, READ_CONTROL | FILE_READ_ATTRIBUTES, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_OPEN_FOR_BACKUP_INTENT); debug_printf ("NtOpenFile: %y", status); if (status == STATUS_OBJECT_NAME_INVALID) return virt_none; if (status == STATUS_NO_MEDIA_IN_DEVICE || status == STAT
; if (!NT_SUCCESS (status)) goto unreadable; RtlInitEmptyUnicodeString (&target, tp.w_get (), (NT_MAX_PATH - 1) * sizeof (WCHAR)); status = NtQuerySymbolicLinkObject (h, &target, NULL); NtClose (h); if (!NT_SUCCESS (status)) goto unreadable; len = sys_wcstombs (NULL, 0, target.Buffer, target.Length / sizeof (WCHAR)); filebuf = (char *) crealloc_abort (filebuf, procsys_len + len + 1); sys_wcstombs (fnamep = stpcpy (filebuf, procsys), len + 1, target.Buffer, target.Length / sizeof (WCHAR)); while ((fnamep = strchr (fnamep, '\\'))) *fnamep = '/'; return true; unreadable: filebuf = (char *) crealloc_abort (filebuf, sizeof (UNREADABLE_SYMLINK_CONTENT)); strcpy (filebuf, UNREADABLE_SYMLINK_CONTENT); return false; } int __reg2 fhandler_procsys::fstat (struct stat *buf) { const char *path = get_name (); debug_printf ("fstat (%s)", path); fhandler_base::fstat (buf); buf->st_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; buf->st_uid = 544; buf->st_gid = 18; buf->st_dev = buf->st_rdev = dev (); buf->st_ino = get_ino (); switch (exists (buf)) { case virt_directory: case virt_rootdir: case virt_fsdir: buf->st_mode |= S_IFDIR; if (buf->st_mode & S_IRUSR) buf->st_mode |= S_IXUSR; if (buf->st_mode & S_IRGRP) buf->st_mode |= S_IXGRP; if (buf->st_mode & S_IROTH) buf->st_mode |= S_IXOTH; break; case virt_file: case virt_fsfile: buf->st_mode |= S_IFREG; break; case virt_symlink: buf->st_mode |= S_IFLNK; break; case virt_pipe: buf->st_mode |= S_IFIFO; break; case virt_socket: buf->st_mode |= S_IFSOCK; break; case virt_chr: buf->st_mode |= S_IFCHR; break; case virt_blk: buf->st_mode |= S_IFBLK; break; default: set_errno (ENOENT); return -1; } return 0; } DIR * fhandler_procsys::opendir (int fd) { UNICODE_STRING path; OBJECT_ATTRIBUTES attr; NTSTATUS status; HANDLE h; DIR *dir; mk_unicode_path (&path); InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenDirectoryObject (&h, DIRECTORY_QUERY, &attr); if (!NT_SUCCESS (status)) { __seterrno_from_nt_status (status); return NULL; } if (!(dir = fhandler_virtual::opendir (fd))) NtClose (h); else dir->__handle = h; return dir; } int fhandler_procsys::readdir (DIR *dir, dirent *de) { NTSTATUS status; struct fdbi { DIRECTORY_BASIC_INFORMATION dbi; WCHAR buf[2][NAME_MAX + 1]; } f; int res = EBADF; if (dir->__handle != INVALID_HANDLE_VALUE) { BOOLEAN restart = dir->__d_position ? FALSE : TRUE; status = NtQueryDirectoryObject (dir->__handle, &f, sizeof f, TRUE, restart, (PULONG) &dir->__d_position, NULL); if (!NT_SUCCESS (status)) res = ENMFILE; else { sys_wcstombs (de->d_name, NAME_MAX + 1, f.dbi.ObjectName.Buffer, f.dbi.ObjectName.Length / sizeof (WCHAR)); de->d_ino = hash_path_name (get_ino (), de->d_name); if (RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natdir, FALSE)) de->d_type = DT_DIR; else if (RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natsyml, FALSE)) de->d_type = DT_LNK; else if (!RtlEqualUnicodeString (&f.dbi.ObjectTypeName, &ro_u_natdev, FALSE)) de->d_type = DT_CHR; else de->d_type = DT_UNKNOWN; res = 0; } } syscall_printf ("%d = readdir(%p, %p)", res, dir, de); return res; } long fhandler_procsys::telldir (DIR *dir) { return dir->__d_position; } void fhandler_procsys::seekdir (DIR *dir, long pos) { dir->__d_position = pos; } int fhandler_procsys::closedir (DIR *dir) { if (dir->__handle != INVALID_HANDLE_VALUE) { NtClose (dir->__handle); dir->__handle = INVALID_HANDLE_VALUE; } return fhandler_virtual::closedir (dir); } void __reg3 fhandler_procsys::read (void *ptr, size_t& len) { fhandler_base::raw_read (ptr, len); } ssize_t __stdcall fhandler_procsys::write (const void *ptr, size_t len) { return fhandler_base::raw_write (ptr, len); } int fhandler_procsys::open (int flags, mode_t mode) { int res = 0; if ((flags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL)) set_errno (EINVAL); else { switch (exists (NULL)) { case virt_directory: case virt_rootdir: if ((flags & O_ACCMODE) != O_RDONLY) set_errno (EISDIR); else { nohandle (true); res = 1; } break; case virt_none: set_errno (ENOENT); break; default: res = fhandler_base::open (flags, mode); break; } } syscall_printf ("%d = fhandler_procsys::open(%p, 0%o)", res, flags, mode); return res; } int fhandler_procsys::close () { if (!nohandle ()) NtClose (get_handle ()); return fhandler_virtual::close (); } #if 0 int fhandler_procsys::ioctl (unsigned int cmd, void *) { } #endif
US_SHARING_VIOLATION) return virt_fsfile; if (status == STATUS_OBJECT_PATH_NOT_FOUND || status == STATUS_OBJECT_NAME_NOT_FOUND) return virt_fsfile; if (status >= STATUS_PIPE_NOT_AVAILABLE && status <= STATUS_PIPE_BUSY) return virt_pipe; if (status == STATUS_ACCESS_DENIED && !internal) { status = NtQueryAttributesFile (&attr, &fbi); debug_printf ("NtQueryAttributesFile: %y", status); if (NT_SUCCESS (status)) return (fbi.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? virt_fsdir : virt_fsfile; dir = path; InitializeObjectAttributes (&attr, &dir, OBJ_CASE_INSENSITIVE, NULL, NULL); do { RtlSplitUnicodePath (&dir, &dir, NULL); status = NtOpenFile (&h, READ_CONTROL | FILE_READ_ATTRIBUTES, &attr, &io, FILE_SHARE_VALID_FLAGS, FILE_OPEN_FOR_BACKUP_INTENT); debug_printf ("NtOpenDirectoryObject: %y", status); if (dir.Length > sizeof (WCHAR)) dir.Length -= sizeof (WCHAR); } while (dir.Length > sizeof (WCHAR) && !NT_SUCCESS (status)); desperate_parent_check = true; } if (NT_SUCCESS (status)) { FILE_FS_DEVICE_INFORMATION ffdi; if (buf && !desperate_parent_check) get_object_attribute (h, &buf->st_uid, &buf->st_gid, &buf->st_mode); status = NtQueryVolumeInformationFile (h, &io, &ffdi, sizeof ffdi, FileFsDeviceInformation); debug_printf ("NtQueryVolumeInformationFile: %y", status); if (NT_SUCCESS (status)) { if (ffdi.DeviceType == FILE_DEVICE_NETWORK_FILE_SYSTEM) file_type = virt_blk; else if (ffdi.DeviceType == FILE_DEVICE_NAMED_PIPE) file_type = internal ? virt_blk : virt_pipe; else if (ffdi.DeviceType == FILE_DEVICE_DISK || ffdi.DeviceType == FILE_DEVICE_CD_ROM || ffdi.DeviceType == FILE_DEVICE_DFS || ffdi.DeviceType == FILE_DEVICE_VIRTUAL_DISK) { status = NtQueryInformationFile (h, &io, &fbi, sizeof fbi, FileBasicInformation); debug_printf ("NtQueryInformationFile: %y", status); if (!NT_SUCCESS (status)) file_type = virt_blk; else file_type = (fbi.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? virt_fsdir : virt_fsfile; } } NtClose (h); } return file_type; } virtual_ftype_t fhandler_procsys::exists () { return exists (NULL); } fhandler_procsys::fhandler_procsys (): fhandler_virtual () { } #define UNREADABLE_SYMLINK_CONTENT "<access denied>" bool fhandler_procsys::fill_filebuf () { char *fnamep; UNICODE_STRING path, target; OBJECT_ATTRIBUTES attr; NTSTATUS status; HANDLE h; tmp_pathbuf tp; size_t len; mk_unicode_path (&path); if (path.Buffer[path.Length / sizeof (WCHAR) - 1] == L'\\') path.Length -= sizeof (WCHAR); InitializeObjectAttributes (&attr, &path, OBJ_CASE_INSENSITIVE, NULL, NULL); status = NtOpenSymbolicLinkObject (&h, SYMBOLIC_LINK_QUERY, &attr)
random
[ { "content": "struct __sFILE64 *fopen64 (const char *, const char *);\n", "file_path": "libc/winsup/cygwin/winsup.h", "rank": 0, "score": 303894.749413499 }, { "content": "struct passwd *getpwnam (const char *);\n", "file_path": "libc/winsup/cygwin/winsup.h", "rank": 1, "score": ...
C++
iverilog-parser/IRStmtVisitor.cc
gokhankici/xenon
d749abd865f2017cda323cf63cf38b585de9e7af
#include <sstream> #include "IRExporter.h" #include "IRStmtVisitor.h" #include "IRExprVisitor.h" using namespace std; void IRStmtVisitor::visit(PGAssign *ga) { if (ga->delay_count() != 0) { cerr << "continuous assignment has a delay:" << endl; ga->dump(cerr,0); cerr << endl; } if (ga->pin_count() != 2 || ga->pin(0) == NULL || ga->pin(1) == NULL) { cerr << "NOT SUPPORTED: PrologExporter@PGAssign: sth wrong with pins" << endl; exit(1); } irStmt = doAssignment(IRStmt_AssignmentType::CONTINUOUS, ga->pin(0), ga->pin(1)); } void IRStmtVisitor::visit(PGBuiltin *gb) { unsigned inputCnt = 0; IRUFOp fun; switch (gb->type()) { case PGBuiltin::AND: fun = IRBinaryOp::AND; inputCnt = 2; break; case PGBuiltin::NAND: fun = IRBinaryOp::NAND; inputCnt = 2; break; case PGBuiltin::OR: fun = IRBinaryOp::OR; inputCnt = 2; break; case PGBuiltin::NOR: fun = IRBinaryOp::NOR; inputCnt = 2; break; case PGBuiltin::XOR: fun = IRBinaryOp::XOR; inputCnt = 2; break; case PGBuiltin::XNOR: fun = IRBinaryOp::XNOR; inputCnt = 2; break; case PGBuiltin::NOT: fun = IRUnaryOp::NOT; inputCnt = 1; break; default: cerr << "NOT SUPPORTED: builtin gate type: " << gb->type() << endl; exit(1); } if (inputCnt + 1 != gb->pin_count()) { cerr << "builtin gate "; gb->dump(cerr, 0); cerr << " has wrong number of inputs" << endl; exit(1); } PExpr* lhs = gb->pin(0); IRExpr_UF* uf = new IRExpr_UF(fun); for (unsigned i = 1; i < inputCnt + 1; i++) { uf->addOperand(toIRExpr(gb->pin(i))); } irStmt = doAssignment(IRStmt_AssignmentType::CONTINUOUS, lhs, uf); } extern std::map<perm_string,Module*> pform_modules; void IRStmtVisitor::visit(PGModule *gm) { Module* mod; auto mod_itr = pform_modules.find(gm->get_type()); if (mod_itr != pform_modules.end()) { mod = (*mod_itr).second; } else { cerr << "module " << gm->get_type() << " not found !"; exit(1); } const string module_name(gm->get_type().str()); const string instance_name(gm->get_name().str()); IRStmt_ModuleInstance* mi = new IRStmt_ModuleInstance(module_name, instance_name); if (gm->pins_) { for (unsigned i=0; i < gm->npins_; i++) { const string name(gm->pins_[i].name.str()); PExpr* expr = gm->pins_[i].parm; if(expr == NULL) { cerr << "module instance " << instance_name << " of type " << module_name << " has a null pin for " << name << endl; gm->dump(cerr, 0); exit(1); } mi->setPort(IRExpr_Variable(name, mod), toIRExpr(expr)); } } else { PGate *g = (PGate *)gm; for (unsigned i = 0; i < g->pin_count(); i += 1) { const string name(mod->ports[i]->name.str()); PExpr* expr = g->pin(i); if(expr == NULL) { cerr << "module instance " << module_name << " of type " << module_name << " has a null pin for " << name << endl; gm->dump(cerr, 0); exit(1); } mi->setPort(IRExpr_Variable(name, mod), toIRExpr(expr)); } } if (!IRExporter::moduleExists(module_name)) { IRExporter submoduleExporter(this->irExporter, mod, gm); submoduleExporter.extractModule(); } irStmt = mi; } void IRStmtVisitor::visit(PCondit *c) { const IRStmt *thenStmt = (c->if_) ? toIRStmt(c->if_) : new IRStmt_Skip(); const IRStmt *elseStmt = (c->else_) ? toIRStmt(c->else_) : new IRStmt_Skip(); irStmt = new IRStmt_If(toIRExpr(c->expr_), thenStmt, elseStmt); } void IRStmtVisitor::visit(PAssign *ba) { if (ba->delay_ || ba->count_ || ba->event_) { cerr << "Blocking assignment has a delay, repeat or event:" << endl; ba->dump(cerr, 0); exit(1); } irStmt = doAssignment(IRStmt_AssignmentType::BLOCKING, ba->lval_, ba->rval_); } void IRStmtVisitor::visit(PAssignNB *nba) { if (nba->count_ || nba->event_) { cerr << "Non-blocking assignment has a delay, repeat or event:" << endl; nba->dump(cerr, 0); exit(1); } if (nba->delay_) { cerr << endl; nba->dump(cerr, 0); cerr << endl; } irStmt = doAssignment(IRStmt_AssignmentType::NON_BLOCKING, nba->lval_, nba->rval_); } void IRStmtVisitor::visit(PBlock *b) { if (b->pscope_name() != 0) { cerr << "NOT SUPPORTED: PBLock w/ pscope_name non-NULL" << endl; exit(1); } if (b->list_.size() == 0) { irStmt = new IRStmt_Skip(); } IRStmt_Sequence *irSeq = new IRStmt_Sequence(); for (unsigned idx = 0; idx < b->list_.size(); idx += 1) { Statement *s = b->list_[idx]; if (s) { irSeq->addStmt(toIRStmt(s)); } else { irSeq->addStmt(new IRStmt_Skip()); } } irStmt = irSeq; } void IRStmtVisitor::visit(PCase *c) { struct CaseStruct { const IRExpr *const caseExpr; const IRStmt *const caseStmt; }; vector<CaseStruct> items; bool hasDefault = false; Statement *defaultStmt = NULL; auto switchExpr = toIRExpr(c->expr_); for (unsigned idx = 0; idx < c->items_->count(); idx += 1) { PCase::Item *cur = (*c->items_)[idx]; if (cur == NULL || cur->stat == NULL) { continue; } if (cur->expr.size() == 0 && cur->stat) { hasDefault = true; defaultStmt = cur->stat; } else { if (cur->expr.size() == 1) { IRExpr_UF *uf = new IRExpr_UF(IRBinaryOp::LOGIC_EQ, switchExpr, toIRExpr(cur->expr.front())); CaseStruct cs = {uf, toIRStmt(cur->stat)}; items.push_back(cs); } else { IRExpr_UF *bigUf = new IRExpr_UF(IRBinaryOp::OR); for (auto idx_expr : cur->expr) { IRExpr_UF *uf = new IRExpr_UF(IRBinaryOp::LOGIC_EQ, switchExpr, toIRExpr(idx_expr)); bigUf->addOperand(uf); } CaseStruct cs = {bigUf, toIRStmt(cur->stat)}; items.push_back(cs); } } } irStmt = (hasDefault) ? toIRStmt(defaultStmt) : new IRStmt_Skip(); for (int i = items.size() - 1; i >= 0; i--) { CaseStruct cs = items.at(i); irStmt = new IRStmt_If(cs.caseExpr, cs.caseStmt, irStmt); } } void IRStmtVisitor::visit(PCallTask *ct) { ostringstream os; os << ct->path(); string taskname = os.str(); if (taskname == "$readmemh" || taskname == "$display" || taskname == "$finish") { irStmt = new IRStmt_Skip(); } else { cerr << endl << "unknown task name " << taskname << endl; exit(1); } } const IRStmt *IRStmtVisitor::doAssignment(IRStmt_AssignmentType assignmentType, const IRExpr *lhs, const IRExpr *rhs) const { if (auto lhsVar = dynamic_cast<const IRExpr_Variable *>(lhs)) { return new IRStmt_Assignment(assignmentType, lhsVar, rhs); } else if (auto lhsSelect = dynamic_cast<const IRExpr_Select *>(lhs)) { IRExpr_UF *newRhs = new IRExpr_UF(IROtherOp::WRITE_TO_INDEX); newRhs->addOperand(lhsSelect->getVariable()); for (auto i : lhsSelect->getIndices()) { newRhs->addOperand(i); } newRhs->addOperand(rhs); return new IRStmt_Assignment(assignmentType, lhsSelect->getVariable(), newRhs); } else { cerr << "Lhs is not a variable or a select expression" << endl; cerr << lhs->toIRString() << " = " << rhs->toIRString() << endl; exit(1); } }
#include <sstream> #include "IRExporter.h" #include "IRStmtVisitor.h" #include "IRExprVisitor.h" using namespace std; void IRStmtVisitor::visit(PGAssign *ga) {
if (ga->pin_count() != 2 || ga->pin(0) == NULL || ga->pin(1) == NULL) { cerr << "NOT SUPPORTED: PrologExporter@PGAssign: sth wrong with pins" << endl; exit(1); } irStmt = doAssignment(IRStmt_AssignmentType::CONTINUOUS, ga->pin(0), ga->pin(1)); } void IRStmtVisitor::visit(PGBuiltin *gb) { unsigned inputCnt = 0; IRUFOp fun; switch (gb->type()) { case PGBuiltin::AND: fun = IRBinaryOp::AND; inputCnt = 2; break; case PGBuiltin::NAND: fun = IRBinaryOp::NAND; inputCnt = 2; break; case PGBuiltin::OR: fun = IRBinaryOp::OR; inputCnt = 2; break; case PGBuiltin::NOR: fun = IRBinaryOp::NOR; inputCnt = 2; break; case PGBuiltin::XOR: fun = IRBinaryOp::XOR; inputCnt = 2; break; case PGBuiltin::XNOR: fun = IRBinaryOp::XNOR; inputCnt = 2; break; case PGBuiltin::NOT: fun = IRUnaryOp::NOT; inputCnt = 1; break; default: cerr << "NOT SUPPORTED: builtin gate type: " << gb->type() << endl; exit(1); } if (inputCnt + 1 != gb->pin_count()) { cerr << "builtin gate "; gb->dump(cerr, 0); cerr << " has wrong number of inputs" << endl; exit(1); } PExpr* lhs = gb->pin(0); IRExpr_UF* uf = new IRExpr_UF(fun); for (unsigned i = 1; i < inputCnt + 1; i++) { uf->addOperand(toIRExpr(gb->pin(i))); } irStmt = doAssignment(IRStmt_AssignmentType::CONTINUOUS, lhs, uf); } extern std::map<perm_string,Module*> pform_modules; void IRStmtVisitor::visit(PGModule *gm) { Module* mod; auto mod_itr = pform_modules.find(gm->get_type()); if (mod_itr != pform_modules.end()) { mod = (*mod_itr).second; } else { cerr << "module " << gm->get_type() << " not found !"; exit(1); } const string module_name(gm->get_type().str()); const string instance_name(gm->get_name().str()); IRStmt_ModuleInstance* mi = new IRStmt_ModuleInstance(module_name, instance_name); if (gm->pins_) { for (unsigned i=0; i < gm->npins_; i++) { const string name(gm->pins_[i].name.str()); PExpr* expr = gm->pins_[i].parm; if(expr == NULL) { cerr << "module instance " << instance_name << " of type " << module_name << " has a null pin for " << name << endl; gm->dump(cerr, 0); exit(1); } mi->setPort(IRExpr_Variable(name, mod), toIRExpr(expr)); } } else { PGate *g = (PGate *)gm; for (unsigned i = 0; i < g->pin_count(); i += 1) { const string name(mod->ports[i]->name.str()); PExpr* expr = g->pin(i); if(expr == NULL) { cerr << "module instance " << module_name << " of type " << module_name << " has a null pin for " << name << endl; gm->dump(cerr, 0); exit(1); } mi->setPort(IRExpr_Variable(name, mod), toIRExpr(expr)); } } if (!IRExporter::moduleExists(module_name)) { IRExporter submoduleExporter(this->irExporter, mod, gm); submoduleExporter.extractModule(); } irStmt = mi; } void IRStmtVisitor::visit(PCondit *c) { const IRStmt *thenStmt = (c->if_) ? toIRStmt(c->if_) : new IRStmt_Skip(); const IRStmt *elseStmt = (c->else_) ? toIRStmt(c->else_) : new IRStmt_Skip(); irStmt = new IRStmt_If(toIRExpr(c->expr_), thenStmt, elseStmt); } void IRStmtVisitor::visit(PAssign *ba) { if (ba->delay_ || ba->count_ || ba->event_) { cerr << "Blocking assignment has a delay, repeat or event:" << endl; ba->dump(cerr, 0); exit(1); } irStmt = doAssignment(IRStmt_AssignmentType::BLOCKING, ba->lval_, ba->rval_); } void IRStmtVisitor::visit(PAssignNB *nba) { if (nba->count_ || nba->event_) { cerr << "Non-blocking assignment has a delay, repeat or event:" << endl; nba->dump(cerr, 0); exit(1); } if (nba->delay_) { cerr << endl; nba->dump(cerr, 0); cerr << endl; } irStmt = doAssignment(IRStmt_AssignmentType::NON_BLOCKING, nba->lval_, nba->rval_); } void IRStmtVisitor::visit(PBlock *b) { if (b->pscope_name() != 0) { cerr << "NOT SUPPORTED: PBLock w/ pscope_name non-NULL" << endl; exit(1); } if (b->list_.size() == 0) { irStmt = new IRStmt_Skip(); } IRStmt_Sequence *irSeq = new IRStmt_Sequence(); for (unsigned idx = 0; idx < b->list_.size(); idx += 1) { Statement *s = b->list_[idx]; if (s) { irSeq->addStmt(toIRStmt(s)); } else { irSeq->addStmt(new IRStmt_Skip()); } } irStmt = irSeq; } void IRStmtVisitor::visit(PCase *c) { struct CaseStruct { const IRExpr *const caseExpr; const IRStmt *const caseStmt; }; vector<CaseStruct> items; bool hasDefault = false; Statement *defaultStmt = NULL; auto switchExpr = toIRExpr(c->expr_); for (unsigned idx = 0; idx < c->items_->count(); idx += 1) { PCase::Item *cur = (*c->items_)[idx]; if (cur == NULL || cur->stat == NULL) { continue; } if (cur->expr.size() == 0 && cur->stat) { hasDefault = true; defaultStmt = cur->stat; } else { if (cur->expr.size() == 1) { IRExpr_UF *uf = new IRExpr_UF(IRBinaryOp::LOGIC_EQ, switchExpr, toIRExpr(cur->expr.front())); CaseStruct cs = {uf, toIRStmt(cur->stat)}; items.push_back(cs); } else { IRExpr_UF *bigUf = new IRExpr_UF(IRBinaryOp::OR); for (auto idx_expr : cur->expr) { IRExpr_UF *uf = new IRExpr_UF(IRBinaryOp::LOGIC_EQ, switchExpr, toIRExpr(idx_expr)); bigUf->addOperand(uf); } CaseStruct cs = {bigUf, toIRStmt(cur->stat)}; items.push_back(cs); } } } irStmt = (hasDefault) ? toIRStmt(defaultStmt) : new IRStmt_Skip(); for (int i = items.size() - 1; i >= 0; i--) { CaseStruct cs = items.at(i); irStmt = new IRStmt_If(cs.caseExpr, cs.caseStmt, irStmt); } } void IRStmtVisitor::visit(PCallTask *ct) { ostringstream os; os << ct->path(); string taskname = os.str(); if (taskname == "$readmemh" || taskname == "$display" || taskname == "$finish") { irStmt = new IRStmt_Skip(); } else { cerr << endl << "unknown task name " << taskname << endl; exit(1); } } const IRStmt *IRStmtVisitor::doAssignment(IRStmt_AssignmentType assignmentType, const IRExpr *lhs, const IRExpr *rhs) const { if (auto lhsVar = dynamic_cast<const IRExpr_Variable *>(lhs)) { return new IRStmt_Assignment(assignmentType, lhsVar, rhs); } else if (auto lhsSelect = dynamic_cast<const IRExpr_Select *>(lhs)) { IRExpr_UF *newRhs = new IRExpr_UF(IROtherOp::WRITE_TO_INDEX); newRhs->addOperand(lhsSelect->getVariable()); for (auto i : lhsSelect->getIndices()) { newRhs->addOperand(i); } newRhs->addOperand(rhs); return new IRStmt_Assignment(assignmentType, lhsSelect->getVariable(), newRhs); } else { cerr << "Lhs is not a variable or a select expression" << endl; cerr << lhs->toIRString() << " = " << rhs->toIRString() << endl; exit(1); } }
if (ga->delay_count() != 0) { cerr << "continuous assignment has a delay:" << endl; ga->dump(cerr,0); cerr << endl; }
if_condition
[ { "content": "extern DLLEXPORT void (*vlog_startup_routines[])(void);\n", "file_path": "iverilog-parser/vpi_user.h", "rank": 0, "score": 98623.54510942122 }, { "content": "static void do_include();\n", "file_path": "iverilog-parser/ivlpp/lexor.c", "rank": 1, "score": 54072.917652...
C++
examples/12-fonts/src/Main.cpp
szszszsz/blue
a6a93d9a6c7bda6b4ed4fa3b9b4b01094c4915b8
#include <blue/Context.hpp> #include <blue/Timestep.hpp> #include <blue/ShaderUtils.h> #include <blue/TextureUtils.hpp> #include <blue/camera/OrthographicCamera.hpp> #include <blue/FontUtils.hpp> #include <atomic> #include <string> #include <cstdint> #include <cstdlib> namespace Sample { const std::uint16_t window_width = 400; const std::uint16_t window_height = 400; } int main(int argc, char* argv[]) { blue::Context::init(); blue::Context::window().create(Sample::window_width, Sample::window_height); blue::Context::gpu_thread().run(); std::atomic_bool running{ true }; blue::Context::input().registerKeyCallback({ [&running]() { running = false; }, SDLK_ESCAPE, SDL_KEYDOWN } ); auto compile_shader_entity = ShaderUtils::make_entity ( "resources/SimpleTextureShader.vertex.glsl", "resources/SimpleTextureShader.fragment.glsl" ); auto shader = blue::Context::gpu_system().submit(compile_shader_entity).get(); Vertices vertices = { -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 1.0f, 0.0f, }; Indices indices = { 0, 1, 2, 2, 3, 0 }; Attributes attributes = { {ShaderAttribute::Type::VEC2, ShaderAttribute::Purpose::VERTEX_POSITION, ShaderAttribute::Buffer::VERTEX}, {ShaderAttribute::Type::VEC2, ShaderAttribute::Purpose::TEXTURE_COORDINATE, ShaderAttribute::Buffer::VERTEX} }; auto vertex_array = blue::Context::gpu_system().submit(CreateMeshEntity{ vertices, indices, attributes, static_cast<std::uint32_t>(indices.size()) }).get(); auto environment = blue::Context::gpu_system().submit(CreateEnvironmentEntity{}).get(); OrthographicCamera camera(OrthographicCamera::Mode::SCREEN_SPACE, blue::Context::window().get_width(), blue::Context::window().get_height()); blue::Context::gpu_system().submit(UpdateEnvironmentEntity_Projection{ environment, camera.get_projection() }); blue::Context::gpu_system().submit(UpdateEnvironmentEntity_View{ environment, camera.get_view() }); auto font = FontUtils::read_ttf_relative("resources/Lato-Black.ttf"); auto create_texture_entity = FontUtils::create_text(font, "The quick brown fox jumps over the lazy dog.", Sample::window_width, Sample::window_height, 22); auto texture = blue::Context::gpu_system().submit(create_texture_entity).get(); UpdateUniformVariableEntity update_uniform_entity{}; update_uniform_entity.type = ShaderAttribute::Type::INT; update_uniform_entity.value = &create_texture_entity.slot; update_uniform_entity.program = shader; update_uniform_entity.location = 9; blue::Context::gpu_system().submit(update_uniform_entity); RenderEntity entity; entity.position = { blue::Context::window().get_width() / 2, blue::Context::window().get_height() / 2, 0.0f }; entity.shader = shader; entity.vertex_array = vertex_array; entity.scale = { Sample::window_width, Sample::window_height, 1.0f }; entity.rotation = glm::identity<glm::quat>(); entity.environment = environment; entity.textures[0] = texture; RenderEntityId id = blue::Context::renderer().add(entity); Timestep timestep(30); while (running) { timestep.mark_start(); blue::Context::input().poll(); timestep.mark_end(); timestep.delay(); } blue::Context::gpu_thread().stop(); blue::Context::dispose(); return EXIT_SUCCESS; }
#include <blue/Context.hpp> #include <blue/Timestep.hpp> #include <blue/ShaderUtils.h> #include <blue/TextureUtils.hpp> #include <blue/camera/OrthographicCamera.hpp> #include <blue/FontUtils.hpp> #include <atomic> #include <string> #include <cstdint> #include <cstdlib> namespace Sample { const std::uint16_t window_width = 400; const std::uint16_t window_height = 400; } int main(int argc, char* argv[]) { blue::Context::init(); blue::Context::window().create(Sample::window_width, Sample::window_height); blue::Context::gpu_thread().run(); std::atomic_bool running{ true }; blue::Context::input().registerKeyCallback({ [&running]() { running = false; }, SDLK_ESCAPE, SDL_KEYDOWN } ); auto compile_shader_entity = ShaderUtils::make_entity ( "resources/SimpleTextureShader.vertex.glsl", "resources/SimpleTextureShader.fragment.glsl" ); auto shader = blue::Context::gpu_system().submit(compile_shader_entity).get(); Vertices vertices = { -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 1.0f, 0.0f, }; Indices indices = { 0, 1, 2, 2, 3, 0 }; Attributes attributes = { {ShaderAttribute::Type::VEC2, ShaderAttribute::Purpose::VERTEX_POSITION, ShaderAttribute::Buffer::VERTEX}, {ShaderAttribute::Type::VEC2, ShaderAttribute::Purpose::TEXTURE_COORDINATE, ShaderAttribute::Buffer::VERTEX} }; auto vertex_
view() }); auto font = FontUtils::read_ttf_relative("resources/Lato-Black.ttf"); auto create_texture_entity = FontUtils::create_text(font, "The quick brown fox jumps over the lazy dog.", Sample::window_width, Sample::window_height, 22); auto texture = blue::Context::gpu_system().submit(create_texture_entity).get(); UpdateUniformVariableEntity update_uniform_entity{}; update_uniform_entity.type = ShaderAttribute::Type::INT; update_uniform_entity.value = &create_texture_entity.slot; update_uniform_entity.program = shader; update_uniform_entity.location = 9; blue::Context::gpu_system().submit(update_uniform_entity); RenderEntity entity; entity.position = { blue::Context::window().get_width() / 2, blue::Context::window().get_height() / 2, 0.0f }; entity.shader = shader; entity.vertex_array = vertex_array; entity.scale = { Sample::window_width, Sample::window_height, 1.0f }; entity.rotation = glm::identity<glm::quat>(); entity.environment = environment; entity.textures[0] = texture; RenderEntityId id = blue::Context::renderer().add(entity); Timestep timestep(30); while (running) { timestep.mark_start(); blue::Context::input().poll(); timestep.mark_end(); timestep.delay(); } blue::Context::gpu_thread().stop(); blue::Context::dispose(); return EXIT_SUCCESS; }
array = blue::Context::gpu_system().submit(CreateMeshEntity{ vertices, indices, attributes, static_cast<std::uint32_t>(indices.size()) }).get(); auto environment = blue::Context::gpu_system().submit(CreateEnvironmentEntity{}).get(); OrthographicCamera camera(OrthographicCamera::Mode::SCREEN_SPACE, blue::Context::window().get_width(), blue::Context::window().get_height()); blue::Context::gpu_system().submit(UpdateEnvironmentEntity_Projection{ environment, camera.get_projection() }); blue::Context::gpu_system().submit(UpdateEnvironmentEntity_View{ environment, camera.get_
random
[ { "content": "struct ShaderAttribute\n\n{\n", "file_path": "include/blue/gpu/GpuEntities.hpp", "rank": 0, "score": 105984.379388146 }, { "content": "\tenum class Model : int\n\n\t{\n\n\t\tPINE_TREE = 0,\n\n\t\tHURDLE = 1,\n\n\t\tWHEAT = 2,\n\n\t\tBOULDER = 3,\n\n\t\tSMALL_BOULDER = 4,\n\n\t\...
C++
Code/Engine/Animation/Graph/Nodes/Animation_RuntimeGraphNode_Parameters.cpp
JuanluMorales/KRG
f3a11de469586a4ef0db835af4bc4589e6b70779
#include "Animation_RuntimeGraphNode_Parameters.h" namespace KRG::Animation::GraphNodes { void ControlParameterBoolNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterBoolNode>( nodePtrs, options ); } void ControlParameterBoolNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (bool*) pOutValue ) = m_value; } void ControlParameterBoolNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(bool*) pInValue; } void ControlParameterIDNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterIDNode>( nodePtrs, options ); } void ControlParameterIDNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (StringID*) pOutValue ) = m_value; } void ControlParameterIDNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(StringID*) pInValue; } void ControlParameterIntNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterIntNode>( nodePtrs, options ); } void ControlParameterIntNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (int32*) pOutValue ) = m_value; } void ControlParameterIntNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(int32*) pInValue; } void ControlParameterFloatNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterFloatNode>( nodePtrs, options ); } void ControlParameterFloatNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (float*) pOutValue ) = m_value; } void ControlParameterFloatNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(float*) pInValue; } void ControlParameterVectorNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterVectorNode>( nodePtrs, options ); } void ControlParameterVectorNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (Vector*) pOutValue ) = m_value; } void ControlParameterVectorNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(Vector*) pInValue; } void ControlParameterTargetNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterTargetNode>( nodePtrs, options ); } void ControlParameterTargetNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (Target*) pOutValue ) = m_value; } void ControlParameterTargetNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(Target*) pInValue; } void ControlParameterBoneMaskNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterBoneMaskNode>( nodePtrs, options ); } void ControlParameterBoneMaskNode::InitializeInternal( GraphContext& context ) { BoneMaskValueNode::InitializeInternal( context ); m_value = eastl::move( BoneMask( context.m_pSkeleton, 1.0f ) ); } void ControlParameterBoneMaskNode::ShutdownInternal( GraphContext& context ) { m_value = eastl::move( BoneMask() ); BoneMaskValueNode::ShutdownInternal( context ); } void ControlParameterBoneMaskNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *reinterpret_cast<BoneMask const**>( pOutValue ) = &m_value; } void ControlParameterBoneMaskNode::SetValueInternal( GraphContext& context, void const* pInValue ) { auto pBoneMaskPtr = *reinterpret_cast<BoneMask const* const*>( pInValue ); m_value = *pBoneMaskPtr; } void VirtualParameterBoolNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterBoolNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterBoolNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); BoolValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterBoolNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); BoolValueNode::ShutdownInternal( context ); } void VirtualParameterBoolNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<bool*>( pOutValue ) = m_pChildNode->GetValue<bool>( context ); } void VirtualParameterIDNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterIDNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterIDNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); IDValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterIDNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); IDValueNode::ShutdownInternal( context ); } void VirtualParameterIDNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<StringID*>( pOutValue ) = m_pChildNode->GetValue<StringID>( context ); } void VirtualParameterIntNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterIntNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterIntNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); IntValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterIntNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); IntValueNode::ShutdownInternal( context ); } void VirtualParameterIntNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<int32*>( pOutValue ) = m_pChildNode->GetValue<int32>( context ); } void VirtualParameterFloatNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterFloatNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterFloatNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); FloatValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterFloatNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); FloatValueNode::ShutdownInternal( context ); } void VirtualParameterFloatNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<float*>( pOutValue ) = m_pChildNode->GetValue<float>( context ); } void VirtualParameterVectorNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterVectorNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterVectorNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); VectorValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterVectorNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); VectorValueNode::ShutdownInternal( context ); } void VirtualParameterVectorNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<Vector*>( pOutValue ) = m_pChildNode->GetValue<Vector>( context ); } void VirtualParameterTargetNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterTargetNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterTargetNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); TargetValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterTargetNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); TargetValueNode::ShutdownInternal( context ); } void VirtualParameterTargetNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<Target*>( pOutValue ) = m_pChildNode->GetValue<Target>( context ); } void VirtualParameterBoneMaskNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterBoneMaskNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterBoneMaskNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); BoneMaskValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterBoneMaskNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); BoneMaskValueNode::ShutdownInternal( context ); } void VirtualParameterBoneMaskNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<BoneMask const**>( pOutValue ) = m_pChildNode->GetValue<BoneMask const*>( context ); } }
#include "Animation_RuntimeGraphNode_Parameters.h" namespace KRG::Animation::GraphNodes { void ControlParameterBoolNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterBoolNode>( nodePtrs, options ); } void ControlParameterBoolNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (bool*) pOutValue ) = m_value; } void ControlParameterBoolNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(bool*) pInValue; } void ControlParameterIDNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterIDNode>( nodePtrs, options ); } void ControlParameterIDNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (StringID*) pOutValue ) = m_value; } void ControlParameterIDNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(StringID*) pInValue; } void ControlParameterIntNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterIntNode>( nodePtrs, options ); } void ControlParameterIntNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (int32*) pOutValue ) = m_value; } void ControlParameterIntNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(int32*) pInValue; } void ControlParameterFloatNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterFloatNode>( nodePtrs, options ); } void ControlParameterFloatNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (float*) pOutValue ) = m_value; } void ControlParameterFloatNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(float*) pInValue; } void ControlParameterVectorNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterVectorNode>( nodePtrs, options ); } void ControlParameterVectorNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (Vector*) pOutValue ) = m_value; } void ControlParameterVectorNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(Vector*) pInValue; } void ControlParameterTargetNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterTargetNode>( nodePtrs, options ); } void ControlParameterTargetNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *( (Target*) pOutValue ) = m_value; } void ControlParameterTargetNode::SetValueInternal( GraphContext& context, void const* pInValue ) { m_value = *(Target*) pInValue; } void ControlParameterBoneMaskNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<ControlParameterBoneMaskNode>( nodePtrs, options ); } void ControlParameterBoneMaskNode::InitializeInternal( GraphContext& context ) { BoneMaskValueNode::InitializeInternal( context ); m_value = eastl::move( BoneMask( context.m_pSkeleton, 1.0f ) ); } void ControlParameterBoneMaskNode::ShutdownInternal( GraphContext& context ) { m_value = eastl::move( BoneMask() ); BoneMaskValueNode::ShutdownInternal( context ); } void ControlParameterBoneMaskNode::GetValueInternal( GraphContext& context, void* pOutValue ) { *reinterpret_cast<BoneMask const**>( pOutValue ) = &m_value; } void ControlParameterBoneMaskNode::SetValueInternal( GraphContext& context, void const* pInValue ) { auto pBoneMaskPtr = *reinterpret_cast<BoneMask const* const*>( pInValue ); m_value = *pBoneMaskPtr; } void VirtualParameterBoolNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterBoolNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterBoolNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); BoolValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterBoolNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); BoolValueNode::ShutdownInternal( context ); } void VirtualParameterBoolNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<bool*>( pOutValue ) = m_pChildNode->GetValue<bool>( context ); } void VirtualParameterIDNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterIDNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterIDNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); IDValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterIDNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); IDValueNode::ShutdownInternal( context ); } void VirtualParameterIDNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<StringID*>( pOutValue ) = m_pChildNode->GetValue<StringID>( context ); } void VirtualParameterIntNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterIntNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterIntNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); IntValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterIntNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); IntValueNode::ShutdownInternal( context ); } void VirtualParameterIntNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<int32*>( pOutValue ) = m_pChildNode->GetValue<int32>( context ); } void VirtualParameterFloatNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterFloatNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterFloatNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); FloatValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterFloatNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); FloatValueNode::ShutdownInternal( context ); } void VirtualParameterFloatNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<float*>( pOutValue ) = m_pChildNode->GetValue<float>( context ); } void VirtualParameterVectorNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterVectorNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterVectorNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); VectorValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterVectorNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); VectorValueNode::ShutdownInternal( context ); } void VirtualParameterVectorNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<Vector*>( pOutValue ) = m_pChildNode->GetValue<Vector>( context ); } void VirtualParameterTargetNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterTargetNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); }
void VirtualParameterTargetNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); TargetValueNode::ShutdownInternal( context ); } void VirtualParameterTargetNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<Target*>( pOutValue ) = m_pChildNode->GetValue<Target>( context ); } void VirtualParameterBoneMaskNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<VirtualParameterBoneMaskNode>( nodePtrs, options ); SetNodePtrFromIndex( nodePtrs, m_childNodeIdx, pNode->m_pChildNode ); } void VirtualParameterBoneMaskNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); BoneMaskValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); } void VirtualParameterBoneMaskNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); m_pChildNode->Shutdown( context ); BoneMaskValueNode::ShutdownInternal( context ); } void VirtualParameterBoneMaskNode::GetValueInternal( GraphContext& context, void* pOutValue ) { KRG_ASSERT( m_pChildNode != nullptr ); *reinterpret_cast<BoneMask const**>( pOutValue ) = m_pChildNode->GetValue<BoneMask const*>( context ); } }
void VirtualParameterTargetNode::InitializeInternal( GraphContext& context ) { KRG_ASSERT( m_pChildNode != nullptr ); TargetValueNode::InitializeInternal( context ); m_pChildNode->Initialize( context ); }
function_block-full_function
[]
C++
chrome/browser/renderer_host/render_process_host_chrome_browsertest.cc
hujiajie/pa-chromium
1816ff80336a6efd1616f9e936880af460b1e105
#include "base/command_line.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" using content::RenderViewHost; using content::RenderWidgetHost; using content::WebContents; namespace { int RenderProcessHostCount() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); int count = 0; while (!hosts.IsAtEnd()) { if (hosts.GetCurrentValue()->HasConnection()) count++; hosts.Advance(); } return count; } RenderViewHost* FindFirstDevToolsHost() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); for (; !hosts.IsAtEnd(); hosts.Advance()) { content::RenderProcessHost* render_process_host = hosts.GetCurrentValue(); DCHECK(render_process_host); if (!render_process_host->HasConnection()) continue; content::RenderProcessHost::RenderWidgetHostsIterator iter( render_process_host->GetRenderWidgetHostsIterator()); for (; !iter.IsAtEnd(); iter.Advance()) { const RenderWidgetHost* widget = iter.GetCurrentValue(); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; RenderViewHost* host = RenderViewHost::From(const_cast<RenderWidgetHost*>(widget)); WebContents* contents = WebContents::FromRenderViewHost(host); GURL url = contents->GetURL(); if (url.SchemeIs(chrome::kChromeDevToolsScheme)) return host; } } return NULL; } } class ChromeRenderProcessHostTest : public InProcessBrowserTest { public: ChromeRenderProcessHostTest() {} base::ProcessHandle ShowSingletonTab(const GURL& page) { chrome::ShowSingletonTab(browser(), page); WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents(); CHECK(wc->GetURL() == page); content::BrowserThread::PostTaskAndReply( content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE, base::Bind(&base::DoNothing), base::MessageLoop::QuitClosure()); base::MessageLoop::current()->Run(); return wc->GetRenderProcessHost()->GetHandle(); } void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), newtab); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph1); GURL bookmarks(chrome::kChromeUIBookmarksURL); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), bookmarks); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), bookmarks); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } }; class ChromeRenderProcessHostTestWithCommandLine : public ChromeRenderProcessHostTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { command_line->AppendSwitchASCII(switches::kRendererProcessLimit, "1"); } }; IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessPerTab) { content::RenderProcessHost::SetMaxRendererProcessCount(1); CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer4.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } #if defined(OS_WIN) || defined(OS_LINUX) IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, Backgrounding) { if (!base::Process::CanBackgroundProcesses()) { LOG(ERROR) << "Can't background processes"; return; } CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); GURL page1("data:text/html,hello world1"); base::ProcessHandle pid1 = ShowSingletonTab(page1); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); GURL page2("data:text/html,hello world2"); base::ProcessHandle pid2 = ShowSingletonTab(page2); EXPECT_NE(pid1, pid2); EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded()); EXPECT_EQ(pid1, ShowSingletonTab(page1)); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded()); } #endif #if defined(OS_WIN) #define MAYBE_ProcessOverflow DISABLED_ProcessOverflow #else #define MAYBE_ProcessOverflow ProcessOverflow #endif IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, MAYBE_ProcessOverflow) { content::RenderProcessHost::SetMaxRendererProcessCount(1); TestProcessOverflow(); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTestWithCommandLine, ProcessOverflow) { TestProcessOverflow(); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcessPPT) { CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcess) { int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); }
#include "base/command_line.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" using content::RenderViewHost; using content::RenderWidgetHost; using content::WebContents; namespace {
RenderViewHost* FindFirstDevToolsHost() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); for (; !hosts.IsAtEnd(); hosts.Advance()) { content::RenderProcessHost* render_process_host = hosts.GetCurrentValue(); DCHECK(render_process_host); if (!render_process_host->HasConnection()) continue; content::RenderProcessHost::RenderWidgetHostsIterator iter( render_process_host->GetRenderWidgetHostsIterator()); for (; !iter.IsAtEnd(); iter.Advance()) { const RenderWidgetHost* widget = iter.GetCurrentValue(); DCHECK(widget); if (!widget || !widget->IsRenderView()) continue; RenderViewHost* host = RenderViewHost::From(const_cast<RenderWidgetHost*>(widget)); WebContents* contents = WebContents::FromRenderViewHost(host); GURL url = contents->GetURL(); if (url.SchemeIs(chrome::kChromeDevToolsScheme)) return host; } } return NULL; } } class ChromeRenderProcessHostTest : public InProcessBrowserTest { public: ChromeRenderProcessHostTest() {} base::ProcessHandle ShowSingletonTab(const GURL& page) { chrome::ShowSingletonTab(browser(), page); WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents(); CHECK(wc->GetURL() == page); content::BrowserThread::PostTaskAndReply( content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE, base::Bind(&base::DoNothing), base::MessageLoop::QuitClosure()); base::MessageLoop::current()->Run(); return wc->GetRenderProcessHost()->GetHandle(); } void TestProcessOverflow() { int tab_count = 1; int host_count = 1; WebContents* tab1 = NULL; WebContents* tab2 = NULL; content::RenderProcessHost* rph1 = NULL; content::RenderProcessHost* rph2 = NULL; content::RenderProcessHost* rph3 = NULL; GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph1 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), newtab); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph2 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), page1); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph2); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), page2); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph2); GURL history(chrome::kChromeUIHistoryURL); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), history); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); EXPECT_EQ(tab2->GetURL(), GURL(history)); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_EQ(tab2->GetRenderProcessHost(), rph1); GURL bookmarks(chrome::kChromeUIBookmarksURL); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), bookmarks); observer4.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1); rph3 = tab1->GetRenderProcessHost(); EXPECT_EQ(tab1->GetURL(), bookmarks); EXPECT_EQ(host_count, RenderProcessHostCount()); EXPECT_NE(rph1, rph3); EXPECT_NE(rph2, rph3); } }; class ChromeRenderProcessHostTestWithCommandLine : public ChromeRenderProcessHostTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { command_line->AppendSwitchASCII(switches::kRendererProcessLimit, "1"); } }; IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessPerTab) { content::RenderProcessHost::SetMaxRendererProcessCount(1); CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); GURL page2("data:text/html,hello world2"); ui_test_utils::WindowedTabAddedNotificationObserver observer2( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page2); observer2.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); ui_test_utils::WindowedTabAddedNotificationObserver observer3( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer3.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); ui_test_utils::WindowedTabAddedNotificationObserver observer4( content::NotificationService::AllSources()); chrome::NewTab(browser()); observer4.Wait(); tab_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } #if defined(OS_WIN) || defined(OS_LINUX) IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, Backgrounding) { if (!base::Process::CanBackgroundProcesses()) { LOG(ERROR) << "Can't background processes"; return; } CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); GURL newtab(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), newtab); GURL page1("data:text/html,hello world1"); base::ProcessHandle pid1 = ShowSingletonTab(page1); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); GURL page2("data:text/html,hello world2"); base::ProcessHandle pid2 = ShowSingletonTab(page2); EXPECT_NE(pid1, pid2); EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded()); EXPECT_EQ(pid1, ShowSingletonTab(page1)); EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded()); EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded()); } #endif #if defined(OS_WIN) #define MAYBE_ProcessOverflow DISABLED_ProcessOverflow #else #define MAYBE_ProcessOverflow ProcessOverflow #endif IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, MAYBE_ProcessOverflow) { content::RenderProcessHost::SetMaxRendererProcessCount(1); TestProcessOverflow(); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTestWithCommandLine, ProcessOverflow) { TestProcessOverflow(); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcessPPT) { CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); parsed_command_line.AppendSwitch(switches::kProcessPerTab); int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); } IN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, DevToolsOnSelfInOwnProcess) { int tab_count = 1; int host_count = 1; GURL page1("data:text/html,hello world1"); ui_test_utils::WindowedTabAddedNotificationObserver observer1( content::NotificationService::AllSources()); chrome::ShowSingletonTab(browser(), page1); observer1.Wait(); tab_count++; host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); RenderViewHost* devtools = FindFirstDevToolsHost(); DCHECK(devtools); DevToolsWindow::ToggleDevToolsWindow( devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT); host_count++; EXPECT_EQ(tab_count, browser()->tab_strip_model()->count()); EXPECT_EQ(host_count, RenderProcessHostCount()); }
int RenderProcessHostCount() { content::RenderProcessHost::iterator hosts = content::RenderProcessHost::AllHostsIterator(); int count = 0; while (!hosts.IsAtEnd()) { if (hosts.GetCurrentValue()->HasConnection()) count++; hosts.Advance(); } return count; }
function_block-full_function
[]
C++
src/material/material_mixture.cpp
Luvideria/lightmetrica-v3
3e83db59998e79648047bac29c37d8eb18d7600d
#include <pch.h> #include <lm/core.h> #include <lm/material.h> #include <lm/surface.h> LM_NAMESPACE_BEGIN(LM_NAMESPACE) class Material_ConstantWeightMixture_RR final : public Material { private: struct Entry { Material* material; Float weight; template <typename Archive> void serialize(Archive& ar) { ar(material, weight); } }; std::vector<Entry> materials_; Dist dist_; public: LM_SERIALIZE_IMPL(ar) { ar(materials_, dist_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { for (auto& e : materials_) { comp::visit(visit, e.material); } } public: virtual void construct(const Json& prop) override { for (auto& entry : prop) { auto* mat = json::comp_ref<Material>(entry, "material"); const auto weight = json::value<Float>(entry, "weight"); materials_.push_back({ mat, weight }); dist_.add(weight); } dist_.norm(); } virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry&, Vec3) const override { const int comp = dist_.sample(u.uc[0]); const auto p = dist_.pmf(comp); return { comp, 1_f / p }; } virtual Float pdf_component(int comp, const PointGeometry&, Vec3) const override { return dist_.pmf(comp); } virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override { const auto& e = materials_[comp]; const auto s = e.material->sample_direction(us, geom, wi, {}, trans_dir); if (!s) { return {}; } return DirectionSample{ s->wo, e.weight * s->weight }; } virtual Vec3 reflectance(const PointGeometry& geom) const override { Vec3 sum(0_f); for (const auto& e : materials_) { sum += e.weight * e.material->reflectance(geom); } return sum; } virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override { return materials_[comp].material->pdf_direction(geom, wi, wo, {}, eval_delta); } virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override { const auto& e = materials_[comp]; return e.weight * e.material->eval(geom, wi, wo, {}, trans_dir, eval_delta); } virtual bool is_specular_component(int comp) const override { return materials_[comp].material->is_specular_component({}); } }; LM_COMP_REG_IMPL(Material_ConstantWeightMixture_RR, "material::constant_weight_mixture_rr"); class Material_ConstantWeightMixture_Marginalized final : public Material { private: struct MaterialGroup { struct Entry { Material* material; Float weight; template <typename Archive> void serialize(Archive& ar) { ar(material, weight); } }; std::vector<Entry> entries; Dist dist; template <typename Archive> void serialize(Archive& ar) { ar(entries, dist); } }; std::vector<MaterialGroup> material_groups_; Dist dist_; public: LM_SERIALIZE_IMPL(ar) { ar(material_groups_, dist_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { for (auto& material_group : material_groups_) { for (auto& e : material_group.entries) { comp::visit(visit, e.material); } } } public: virtual void construct(const Json& prop) override { material_groups_.emplace_back(); for (auto& entry : prop) { auto* mat = json::comp_ref<Material>(entry, "material"); const auto weight = json::value<Float>(entry, "weight"); if (mat->is_specular_component({})) { material_groups_.emplace_back(); material_groups_.back().entries.push_back({ mat, weight }); } else { material_groups_[0].entries.push_back({ mat, weight }); } } for (auto& group : material_groups_) { Float weight_sum = 0_f; for (const auto& entry : group.entries) { weight_sum += entry.weight; group.dist.add(entry.weight); } group.dist.norm(); dist_.add(weight_sum); } dist_.norm(); } virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry&, Vec3) const override { const int comp = dist_.sample(u.uc[0]); const auto p = dist_.pmf(comp); return { comp, 1_f / p }; } virtual Float pdf_component(int comp, const PointGeometry&, Vec3) const override { return dist_.pmf(comp); } virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override { const auto& group = material_groups_[comp]; const int comp_in_group = group.dist.sample(us.udc[0]); const auto& e = group.entries[comp_in_group]; const auto s = e.material->sample_direction(us, geom, wi, {}, trans_dir); if (!s) { return {}; } const auto f = eval(geom, wi, s->wo, comp, trans_dir, false); const auto p = pdf_direction(geom, wi, s->wo, comp, false); const auto C = f / p; return DirectionSample{ s->wo, C }; } virtual Vec3 reflectance(const PointGeometry& geom) const override { Vec3 sum(0_f); for (auto& group : material_groups_) { for (const auto& entry : group.entries) { sum += entry.weight * entry.material->reflectance(geom); } } return sum; } virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override { const auto& group = material_groups_[comp]; Float p_marginal = 0_f; for (int i = 0; i < (int)(group.entries.size()); i++) { const auto p_sel = group.dist.pmf(i); const auto p = group.entries[i].material->pdf_direction(geom, wi, wo, {}, eval_delta); p_marginal += p_sel * p; } return p_marginal; } virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override { const auto& group = material_groups_[comp]; Vec3 result(0_f); for (const auto& entry : group.entries) { const auto f = entry.material->eval(geom, wi, wo, {}, trans_dir, eval_delta); result += entry.weight * f; } return result; } virtual bool is_specular_component(int comp) const override { return comp != 0; } }; LM_COMP_REG_IMPL(Material_ConstantWeightMixture_Marginalized, "material::constant_weight_mixture_marginalized"); LM_NAMESPACE_END(LM_NAMESPACE)
#include <pch.h> #include <lm/core.h> #include <lm/material.h> #include <lm/surface.h> LM_NAMESPACE_BEGIN(LM_NAMESPACE) class Material_ConstantWeightMixture_RR final : public Material { private: struct Entry { Material* material; Float weight; template <typename Archive> void serialize(Archive& ar) { ar(material, weight); } }; std::vector<Entry> materials_; Dist dist_; public: LM_SERIALIZE_IMPL(ar) { ar(materials_, dist_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { for (auto& e : materials_) { comp::visit(visit, e.material); } } public: virtual void construct(const Json& prop) override { for (auto& entry : prop) { auto* mat = json::comp_ref<Material>(entry, "material"); const auto weight = json::value<Float>(entry, "weight"); materials_.push_back({ mat, weight }); dist_.add(weight); } dist_.norm(); } virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry&, Vec3) const override { const int comp = dist_.sample(u.uc[0]); const auto p = dist_.pmf(comp); return { comp, 1_f / p }; } virtual Float pdf_component(int comp, const PointGeometry&, Vec3) const override { return dist_.pmf(comp); } virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override { const auto& e = materials_[comp]; const auto s = e.material->sample_direction(us, geom, wi, {}, trans_dir); if (!s) { return {}; } return DirectionSample{ s->wo, e.weight * s->weight }; } virtual Vec3 reflectance(const PointGeometry& geom) const override { Vec3 sum(0_f); for (const auto& e : materials_) { sum += e.weight * e.material->reflectance(geom); } return sum; } virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override { return materials_[comp].material->pdf_direction(geom, wi, wo, {}, eval_delta); } virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override { const auto& e = materials_[comp]; return e.weight * e.material->eval(geom, wi, wo, {}, trans_dir, eval_delta); } virtual bool is_specular_component(int comp) const override { return materials_[comp].material->is_specular_component({}); } }; LM_COMP_REG_IMPL(Material_ConstantWeightMixture_RR, "material::constant_weight_mixture_rr"); class Material_ConstantWeightMixture_Marginalized final : public Material { private: struct MaterialGroup { struct Entry { Material* material; Float weight; template <typename Archive> void serialize(Archive& ar) { ar(material, weight); } }; std::vector<Entry> entries; Dist dist; template <typename Archive> void serialize(Archive& ar) { ar(entries, dist); } }; std::vector<MaterialGroup> material_groups_; Dist dist_; public: LM_SERIALIZE_IMPL(ar) { ar(material_groups_, dist_); } virtual void foreach_underlying(const ComponentVisitor& visit) override { for (auto& material_group : material_groups_) { for (auto& e : material_group.entries) { comp::visit(visit, e.material); } } } public: virtual void construct(const Json& prop) override { material_groups_.emplace_back();
group.dist.add(entry.weight); } group.dist.norm(); dist_.add(weight_sum); } dist_.norm(); } virtual ComponentSample sample_component(const ComponentSampleU& u, const PointGeometry&, Vec3) const override { const int comp = dist_.sample(u.uc[0]); const auto p = dist_.pmf(comp); return { comp, 1_f / p }; } virtual Float pdf_component(int comp, const PointGeometry&, Vec3) const override { return dist_.pmf(comp); } virtual std::optional<DirectionSample> sample_direction(const DirectionSampleU& us, const PointGeometry& geom, Vec3 wi, int comp, TransDir trans_dir) const override { const auto& group = material_groups_[comp]; const int comp_in_group = group.dist.sample(us.udc[0]); const auto& e = group.entries[comp_in_group]; const auto s = e.material->sample_direction(us, geom, wi, {}, trans_dir); if (!s) { return {}; } const auto f = eval(geom, wi, s->wo, comp, trans_dir, false); const auto p = pdf_direction(geom, wi, s->wo, comp, false); const auto C = f / p; return DirectionSample{ s->wo, C }; } virtual Vec3 reflectance(const PointGeometry& geom) const override { Vec3 sum(0_f); for (auto& group : material_groups_) { for (const auto& entry : group.entries) { sum += entry.weight * entry.material->reflectance(geom); } } return sum; } virtual Float pdf_direction(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, bool eval_delta) const override { const auto& group = material_groups_[comp]; Float p_marginal = 0_f; for (int i = 0; i < (int)(group.entries.size()); i++) { const auto p_sel = group.dist.pmf(i); const auto p = group.entries[i].material->pdf_direction(geom, wi, wo, {}, eval_delta); p_marginal += p_sel * p; } return p_marginal; } virtual Vec3 eval(const PointGeometry& geom, Vec3 wi, Vec3 wo, int comp, TransDir trans_dir, bool eval_delta) const override { const auto& group = material_groups_[comp]; Vec3 result(0_f); for (const auto& entry : group.entries) { const auto f = entry.material->eval(geom, wi, wo, {}, trans_dir, eval_delta); result += entry.weight * f; } return result; } virtual bool is_specular_component(int comp) const override { return comp != 0; } }; LM_COMP_REG_IMPL(Material_ConstantWeightMixture_Marginalized, "material::constant_weight_mixture_marginalized"); LM_NAMESPACE_END(LM_NAMESPACE)
for (auto& entry : prop) { auto* mat = json::comp_ref<Material>(entry, "material"); const auto weight = json::value<Float>(entry, "weight"); if (mat->is_specular_component({})) { material_groups_.emplace_back(); material_groups_.back().entries.push_back({ mat, weight }); } else { material_groups_[0].entries.push_back({ mat, weight }); } } for (auto& group : material_groups_) { Float weight_sum = 0_f; for (const auto& entry : group.entries) { weight_sum += entry.weight;
random
[ { "content": "class Material_Glossy final : public Material {\n\nprivate:\n\n Vec3 Ks_; // Specular reflectance\n\n Float ax_, ay_; // Roughness (anisotropic)\n\n\n\npublic:\n\n LM_SERIALIZE_IMPL(ar) {\n\n ar(Ks_, ax_, ay_);\n\n }\n\n\n\npublic:\n\n virtual void construct(const Jso...
C++
example/add2/addserver.cc
walterzhaoJR/braft_walter
bba0afae3b28e9446e4ecc44e0b2b8baac1c4780
#include <map> #include <string> #include <fstream> #include <gflags/gflags.h> #include <brpc/controller.h> #include <brpc/server.h> #include <braft/raft.h> #include <braft/util.h> #include <braft/storage.h> #include <butil/sys_byteorder.h> #include "add.pb.h" DEFINE_int32(port, 8100, "Listen port of this peer"); DEFINE_bool(h, false, "print help information"); DEFINE_string(group, "add", "Id of the replication group"); DEFINE_string(conf, "", "Initial configuration of the replication group"); DEFINE_string(data_path, "./data", "Path of data stored on"); DEFINE_int32(election_timeout_ms, 5000, "Start election in such milliseconds if disconnect with the leader"); DEFINE_int32(snapshot_interval, 60, "Interval between each snapshot"); using namespace std; namespace example { class AddStateMachine ; class AddClosure : public braft::Closure { public: AddClosure(AddStateMachine* statemachine,const AddRequest* request,AddResponse* response ,google::protobuf::Closure* done) :statemachine_(statemachine),request_(request),response_(response),done_(done){ }; void Run(); const AddRequest* Request(){ return request_; } AddResponse* Response(){ return response_; } private: AddStateMachine* statemachine_; const AddRequest* request_; AddResponse* response_; google::protobuf::Closure* done_; }; class AddStateMachine : public braft::StateMachine { public: AddStateMachine():_node(NULL),leader_term_(-1),id_(-1){}; ~AddStateMachine(){} int start(int id); virtual void on_apply(::braft::Iterator& iter) ; virtual void on_snapshot_save(::braft::SnapshotWriter* writer, ::braft::Closure* done); virtual int on_snapshot_load(::braft::SnapshotReader* reader); void on_shutdown() { LOG(INFO) << "This node is down"; } void on_error(const ::braft::Error& e) { LOG(ERROR) << "Met raft error " << e; } void on_configuration_committed(const ::braft::Configuration& conf) { LOG(INFO) << "Configuration of this group is " << conf; } void on_stop_following(const ::braft::LeaderChangeContext& ctx) { LOG(INFO) << "Node stops following " << ctx; } void on_start_following(const ::braft::LeaderChangeContext& ctx) { LOG(INFO) << "Node start following " << ctx; } void on_leader_start(int64_t term) { leader_term_.store(term, butil::memory_order_release); LOG(INFO) << "Node becomes leader"; } void on_leader_stop(const butil::Status& status) { leader_term_.store(-1, butil::memory_order_release); LOG(INFO) << "Node stepped down : " << status; } bool is_leader() const { return leader_term_.load(butil::memory_order_acquire) > 0; } void redirect(AddResponse* response) { response->set_success(false); response->set_result(-1); if (_node) { braft::PeerId leader = _node->leader_id(); if (!leader.is_empty()) { LOG(DEBUG) << "id:"<<id_<<"," <<"redirect : " << leader; response->set_redirect(leader.to_string()); } else{ LOG(ERROR) << "id:"<<id_<<"," <<"NO LEADER "; } } } void write(const ::example::AddRequest* request,::example::AddResponse* response ,::google::protobuf::Closure* done); void reallyWrite(const string& key ,long long number,AddResponse* response); void shutdown() { if (_node) { _node->shutdown(NULL); } } void join() { if (_node) { _node->join(); } } private: map<string,long long> number_map_; braft::Node* volatile _node; butil::atomic<int64_t> leader_term_; int id_; }; void AddStateMachine::on_snapshot_save(::braft::SnapshotWriter* writer, ::braft::Closure* done){ brpc::ClosureGuard done_guard(done); std::string snapshot_path = writer->get_path(); snapshot_path.append("/data"); std::ofstream os(snapshot_path.c_str()); for (auto it = number_map_.begin(); it != number_map_.end() ; it++) { os << it->first << ' ' << it->second << '\n'; } CHECK_EQ(0, writer->add_file("data")); return; } int AddStateMachine::on_snapshot_load(::braft::SnapshotReader* reader){ CHECK_EQ(-1, leader_term_) << "Leader is not supposed to load snapshot"; number_map_.clear(); std::string snapshot_path = reader->get_path(); snapshot_path.append("/data"); std::ifstream is(snapshot_path.c_str()); string key ; int64_t value = 0; while (is >> key >> value) { LOG(DEBUG) << "key:" << key << ",value:" << value; number_map_[key] = value; } return 0; } int AddStateMachine::start(int id){ id_ = id; butil::EndPoint addr(butil::my_ip(), FLAGS_port); braft::Node* node = new braft::Node(FLAGS_group, braft::PeerId(addr,id)); braft::NodeOptions node_options; stringstream data_path_stream; data_path_stream << FLAGS_data_path << id; string data_path = data_path_stream.str(); if (!butil::CreateDirectory(butil::FilePath(data_path))) { LOG(ERROR) << "Fail to create directory " << data_path; return -1; } LOG(INFO) << "data_path:"<<data_path; node_options.election_timeout_ms = FLAGS_election_timeout_ms; node_options.fsm = this; node_options.snapshot_interval_s = FLAGS_snapshot_interval; std::string prefix = "local://" + data_path; node_options.log_uri = prefix + "/log"; node_options.raft_meta_uri = prefix + "/raft_meta"; node_options.snapshot_uri = prefix + "/snapshot"; stringstream ss(FLAGS_conf); string t; stringstream conf; while (getline(ss, t, ',')) { conf << t <<":"<<id<<","; } LOG(INFO) << "CONF:"<<conf.str(); if (node_options.initial_conf.parse_from(conf.str()) != 0) { LOG(ERROR) << "Fail to parse configuration `" << conf.str() << '\''; return -1; } if (node->init(node_options) != 0) { LOG(ERROR) << "Fail to init raft node"; delete node; return -1; } _node = node; return 0; } void AddStateMachine::on_apply(braft::Iterator& iter) { for (; iter.valid(); iter.next()) { braft::AsyncClosureGuard closure_guard(iter.done()); butil::IOBuf data; string key; long long number; AddResponse* response = NULL; if (iter.done()) { LOG(DEBUG) << "id:"<<id_<<"," <<"iter.done"; AddClosure* c = dynamic_cast<AddClosure*>(iter.done()); LOG(INFO) << "id:"<<id_<<"," <<"request ptr:" <<c->Request(); key = c->Request()->key(); number = c->Request()->number(); response = c->Response(); } else { LOG(DEBUG) << "id:"<<id_<<"," << "parse from iter.data"; uint32_t meta_size = 0; butil::IOBuf saved_log = iter.data(); saved_log.cutn(&meta_size, sizeof(uint32_t)); meta_size = butil::NetToHost32(meta_size); butil::IOBuf meta; saved_log.cutn(&meta, meta_size); butil::IOBufAsZeroCopyInputStream wrapper(meta); AddRequest request; CHECK(request.ParseFromZeroCopyStream(&wrapper)); key = request.key(); number = request.number(); } reallyWrite(key,number,response); } } void AddStateMachine::write(const ::example::AddRequest* request,::example::AddResponse* response ,::google::protobuf::Closure* done){ brpc::ClosureGuard done_guard(done); const int64_t term = leader_term_.load(butil::memory_order_relaxed); LOG(DEBUG) <<"term:" <<term; if (term < 0) { LOG(DEBUG) <<"redirect"; return redirect(response); } LOG(INFO) << "id:"<<id_<<","<<"request ptr:" <<request; LOG(INFO) << "id:"<<id_<<","<<"done ptr:" <<done; LOG(INFO) << "id:"<<id_<<"," << "request message ,key:" << request->key() << ",number:" << request->number(); butil::IOBuf log; const uint32_t meta_size_raw = butil::HostToNet32(request->ByteSize()); log.append(&meta_size_raw, sizeof(uint32_t)); butil::IOBufAsZeroCopyOutputStream wrapper(&log); if (!request->SerializeToZeroCopyStream(&wrapper)) { LOG(ERROR) << "Fail to serialize request"; response->set_success(false); return; } braft::Task task; task.data = &log; task.done = new AddClosure( this,request,response,done_guard.release()); _node->apply(task); LOG(INFO) << "id:"<<id_<<"," <<"apply done"; return; } void AddStateMachine::reallyWrite(const string& key ,long long number,AddResponse* response){ LOG(INFO) << "request message ,key:" << key << ",number:" << number; long long result = number; if (number_map_.find(key) == number_map_.end()) { number_map_.insert(make_pair(key,result)); } else { result += number_map_[key]; number_map_[key] = result; } LOG(INFO) << "reslut:" << result; if (response) { LOG(DEBUG) << "response isn't NULL,set response"; response->set_success(true); response->set_result(result); } } class AddServiceImpl :public AddService{ public: AddServiceImpl(AddStateMachine* sm,AddStateMachine* sm2):statemachine_(sm),statemachine2_(sm2) ,statemachine3_(NULL){ } void shutdown(){ if (statemachine3_ != NULL) { statemachine3_->shutdown(); } } void write(::google::protobuf::RpcController* controller, const ::example::AddRequest* request, ::example::AddResponse* response, ::google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); if (request->key() == "key2") { statemachine2_->write(request,response, done_guard.release()); return; } if (request->key() == "key3") { if (statemachine3_ == NULL) { response->set_success(false); response->set_result(-1); response->set_redirect("statemachine3 can't start."); return; } statemachine3_->write(request,response, done_guard.release()); return; } statemachine_->write(request,response, done_guard.release()); return; } void start_new_statemachine(::google::protobuf::RpcController* controller, const ::example::NewStateMachineRequest* request, ::example::NewStateMachineResponse* response, ::google::protobuf::Closure* done){ brpc::ClosureGuard done_guard(done); statemachine3_ = new AddStateMachine(); if (statemachine3_->start(2) != 0) { LOG(ERROR) << "Fail to start state machine1"; response->set_success(false); return ; } response->set_success(true); } private: AddStateMachine* statemachine_; AddStateMachine* statemachine2_; AddStateMachine* statemachine3_; }; void AddClosure::Run(){ std::unique_ptr<AddClosure> self_guard(this); LOG(INFO) <<"done ptr:" <<done_; brpc::ClosureGuard done_guard(done_); if (status().ok()) { return; } statemachine_->redirect(response_); } } int main(int argc, char* argv[]){ gflags::SetVersionString("0.1"); gflags::SetUsageMessage("Usage: xxxx"); gflags::ParseCommandLineFlags(&argc, &argv, true); brpc::Server server; example::AddStateMachine statemachine; example::AddStateMachine statemachine2; example::AddServiceImpl service(&statemachine,&statemachine2); if (server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE) != 0) { LOG(ERROR) << "Fail to add service"; return -1; } if (braft::add_service(&server, FLAGS_port) != 0) { LOG(ERROR) << "Fail to add raft service"; return -1; } if (server.Start(FLAGS_port, NULL) != 0) { LOG(ERROR) << "Fail to start Server"; return -1; } if (statemachine.start(0) != 0) { LOG(ERROR) << "Fail to start state machine0"; return -1; } if (statemachine2.start(1) != 0) { LOG(ERROR) << "Fail to start state machine1"; return -1; } LOG(INFO) << "add service is running on " << server.listen_address(); while (!brpc::IsAskedToQuit()) { sleep(1); } LOG(INFO) << "add service is going to quit"; statemachine.shutdown(); statemachine2.shutdown(); service.shutdown(); server.Stop(0); statemachine.join(); statemachine2.join(); server.Join(); return 0; }
#include <map> #include <string> #include <fstream> #include <gflags/gflags.h> #include <brpc/controller.h> #include <brpc/server.h> #include <braft/raft.h> #include <braft/util.h> #include <braft/storage.h> #include <butil/sys_byteorder.h> #include "add.pb.h" DEFINE_int32(port, 8100, "Listen port of this peer"); DEFINE_bool(h, false, "print help information"); DEFINE_string(group, "add", "Id of the replication group"); DEFINE_string(conf, "", "Initial configuration of the replication group"); DEFINE_string(data_path, "./data", "Path of data stored on"); DEFINE_int32(election_timeout_ms, 5000, "Start election in such milliseconds if disconnect with the leader"); DEFINE_int32(snapshot_interval, 60, "Interval between each snapshot"); using namespace std; namespace example { class AddStateMachine ; class AddClosure : public braft::Closure { public: AddClosure(AddStateMachine* statemachine,const AddRequest* request,AddResponse* response ,google::protobuf::Closure* done) :statemachine_(statemachine),request_(request),response_(response),done_(done){ }; void Run(); const AddRequest* Request(){ return request_; } AddResponse* Response(){ return response_; } private: AddStateMachine* statemachine_; const AddRequest* request_; AddResponse* response_; google::protobuf::Closure* done_; }; class AddStateMachine : public braft::StateMachine { public: AddStateMachine():_node(NULL),leader_term_(-1),id_(-1){}; ~AddStateMachine(){} int start(int id); virtual void on_apply(::braft::Iterator& iter) ; virtual void on_snapshot_save(::braft::SnapshotWriter* writer, ::braft::Closure* done); virtual int on_snapshot_load(::braft::SnapshotReader* reader); void on_shutdown() { LOG(INFO) << "This node is down"; } void on_error(const ::braft::Error& e) { LOG(ERROR) << "Met raft error " << e; } void on_configuration_committed(const ::braft::Configuration& conf) { LOG(INFO) << "Configuration of this group is " << conf; } void on_stop_following(const ::braft::LeaderChangeContext& ctx) { LOG(INFO) << "Node stops following " << ctx; } void on_start_following(const ::braft::LeaderChangeContext& ctx) { LOG(INFO) << "Node start following " << ctx; } void on_leader_start(int64_t term) { leader_term_.store(term, butil::memory_order_release); LOG(INFO) << "Node becomes leader"; } void on_leader_stop(const butil::Status& status) { leader_term_.store(-1, butil::memory_order_release); LOG(INFO) << "Node stepped down : " << status; } bool is_leader() const { return leader_term_.load(butil::memory_order_acquire) > 0; } void redirect(AddResponse* response) { response->set_success(false); response->set_result(-1); if (_node) { braft::PeerId leader = _node->leader_id(); if (!leader.is_empty()) { LOG(DEBUG) << "id:"<<id_<<"," <<"redirect : " << leader; response->set_redirect(leader.to_string()); } else{ LOG(ERROR) << "id:"<<id_<<"," <<"NO LEADER "; } } } void write(const ::example::AddRequest* request,::example::AddResponse* response ,::google::protobuf::Closure* done); void reallyWrite(const string& key ,long long number,AddResponse* response); void shutdown() { if (_node) { _node->shutdown(NULL); } } void join() { if (_node) { _node->join(); } } private: map<string,long long> number_map_; braft::Node* volatile _node; butil::atomic<int64_t> leader_term_; int id_; }; void AddStateMachine::on_snapshot_save(::braft::SnapshotWriter* writer, ::braft::Closure* done){ brpc::ClosureGuard done_guard(done); std::string snapshot_path = writer->get_path(); snapshot_path.append("/data"); std::ofstream os(snapshot_path.c_str()); for (auto it = number_map_.begin(); it != number_map_.end() ; it++) { os << it->first << ' ' << it->second << '\n'; } CHECK_EQ(0, writer->add_file("data")); return; } int AddStateMachine::on_snapshot_load(::braft::SnapshotReader* reader){ CHECK_EQ(-1, leader_term_) << "Leader is not supposed to load snapshot"; number_map_.clear(); std::string snapshot_path = reader->get_pat
int AddStateMachine::start(int id){ id_ = id; butil::EndPoint addr(butil::my_ip(), FLAGS_port); braft::Node* node = new braft::Node(FLAGS_group, braft::PeerId(addr,id)); braft::NodeOptions node_options; stringstream data_path_stream; data_path_stream << FLAGS_data_path << id; string data_path = data_path_stream.str(); if (!butil::CreateDirectory(butil::FilePath(data_path))) { LOG(ERROR) << "Fail to create directory " << data_path; return -1; } LOG(INFO) << "data_path:"<<data_path; node_options.election_timeout_ms = FLAGS_election_timeout_ms; node_options.fsm = this; node_options.snapshot_interval_s = FLAGS_snapshot_interval; std::string prefix = "local://" + data_path; node_options.log_uri = prefix + "/log"; node_options.raft_meta_uri = prefix + "/raft_meta"; node_options.snapshot_uri = prefix + "/snapshot"; stringstream ss(FLAGS_conf); string t; stringstream conf; while (getline(ss, t, ',')) { conf << t <<":"<<id<<","; } LOG(INFO) << "CONF:"<<conf.str(); if (node_options.initial_conf.parse_from(conf.str()) != 0) { LOG(ERROR) << "Fail to parse configuration `" << conf.str() << '\''; return -1; } if (node->init(node_options) != 0) { LOG(ERROR) << "Fail to init raft node"; delete node; return -1; } _node = node; return 0; } void AddStateMachine::on_apply(braft::Iterator& iter) { for (; iter.valid(); iter.next()) { braft::AsyncClosureGuard closure_guard(iter.done()); butil::IOBuf data; string key; long long number; AddResponse* response = NULL; if (iter.done()) { LOG(DEBUG) << "id:"<<id_<<"," <<"iter.done"; AddClosure* c = dynamic_cast<AddClosure*>(iter.done()); LOG(INFO) << "id:"<<id_<<"," <<"request ptr:" <<c->Request(); key = c->Request()->key(); number = c->Request()->number(); response = c->Response(); } else { LOG(DEBUG) << "id:"<<id_<<"," << "parse from iter.data"; uint32_t meta_size = 0; butil::IOBuf saved_log = iter.data(); saved_log.cutn(&meta_size, sizeof(uint32_t)); meta_size = butil::NetToHost32(meta_size); butil::IOBuf meta; saved_log.cutn(&meta, meta_size); butil::IOBufAsZeroCopyInputStream wrapper(meta); AddRequest request; CHECK(request.ParseFromZeroCopyStream(&wrapper)); key = request.key(); number = request.number(); } reallyWrite(key,number,response); } } void AddStateMachine::write(const ::example::AddRequest* request,::example::AddResponse* response ,::google::protobuf::Closure* done){ brpc::ClosureGuard done_guard(done); const int64_t term = leader_term_.load(butil::memory_order_relaxed); LOG(DEBUG) <<"term:" <<term; if (term < 0) { LOG(DEBUG) <<"redirect"; return redirect(response); } LOG(INFO) << "id:"<<id_<<","<<"request ptr:" <<request; LOG(INFO) << "id:"<<id_<<","<<"done ptr:" <<done; LOG(INFO) << "id:"<<id_<<"," << "request message ,key:" << request->key() << ",number:" << request->number(); butil::IOBuf log; const uint32_t meta_size_raw = butil::HostToNet32(request->ByteSize()); log.append(&meta_size_raw, sizeof(uint32_t)); butil::IOBufAsZeroCopyOutputStream wrapper(&log); if (!request->SerializeToZeroCopyStream(&wrapper)) { LOG(ERROR) << "Fail to serialize request"; response->set_success(false); return; } braft::Task task; task.data = &log; task.done = new AddClosure( this,request,response,done_guard.release()); _node->apply(task); LOG(INFO) << "id:"<<id_<<"," <<"apply done"; return; } void AddStateMachine::reallyWrite(const string& key ,long long number,AddResponse* response){ LOG(INFO) << "request message ,key:" << key << ",number:" << number; long long result = number; if (number_map_.find(key) == number_map_.end()) { number_map_.insert(make_pair(key,result)); } else { result += number_map_[key]; number_map_[key] = result; } LOG(INFO) << "reslut:" << result; if (response) { LOG(DEBUG) << "response isn't NULL,set response"; response->set_success(true); response->set_result(result); } } class AddServiceImpl :public AddService{ public: AddServiceImpl(AddStateMachine* sm,AddStateMachine* sm2):statemachine_(sm),statemachine2_(sm2) ,statemachine3_(NULL){ } void shutdown(){ if (statemachine3_ != NULL) { statemachine3_->shutdown(); } } void write(::google::protobuf::RpcController* controller, const ::example::AddRequest* request, ::example::AddResponse* response, ::google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); if (request->key() == "key2") { statemachine2_->write(request,response, done_guard.release()); return; } if (request->key() == "key3") { if (statemachine3_ == NULL) { response->set_success(false); response->set_result(-1); response->set_redirect("statemachine3 can't start."); return; } statemachine3_->write(request,response, done_guard.release()); return; } statemachine_->write(request,response, done_guard.release()); return; } void start_new_statemachine(::google::protobuf::RpcController* controller, const ::example::NewStateMachineRequest* request, ::example::NewStateMachineResponse* response, ::google::protobuf::Closure* done){ brpc::ClosureGuard done_guard(done); statemachine3_ = new AddStateMachine(); if (statemachine3_->start(2) != 0) { LOG(ERROR) << "Fail to start state machine1"; response->set_success(false); return ; } response->set_success(true); } private: AddStateMachine* statemachine_; AddStateMachine* statemachine2_; AddStateMachine* statemachine3_; }; void AddClosure::Run(){ std::unique_ptr<AddClosure> self_guard(this); LOG(INFO) <<"done ptr:" <<done_; brpc::ClosureGuard done_guard(done_); if (status().ok()) { return; } statemachine_->redirect(response_); } } int main(int argc, char* argv[]){ gflags::SetVersionString("0.1"); gflags::SetUsageMessage("Usage: xxxx"); gflags::ParseCommandLineFlags(&argc, &argv, true); brpc::Server server; example::AddStateMachine statemachine; example::AddStateMachine statemachine2; example::AddServiceImpl service(&statemachine,&statemachine2); if (server.AddService(&service, brpc::SERVER_DOESNT_OWN_SERVICE) != 0) { LOG(ERROR) << "Fail to add service"; return -1; } if (braft::add_service(&server, FLAGS_port) != 0) { LOG(ERROR) << "Fail to add raft service"; return -1; } if (server.Start(FLAGS_port, NULL) != 0) { LOG(ERROR) << "Fail to start Server"; return -1; } if (statemachine.start(0) != 0) { LOG(ERROR) << "Fail to start state machine0"; return -1; } if (statemachine2.start(1) != 0) { LOG(ERROR) << "Fail to start state machine1"; return -1; } LOG(INFO) << "add service is running on " << server.listen_address(); while (!brpc::IsAskedToQuit()) { sleep(1); } LOG(INFO) << "add service is going to quit"; statemachine.shutdown(); statemachine2.shutdown(); service.shutdown(); server.Stop(0); statemachine.join(); statemachine2.join(); server.Join(); return 0; }
h(); snapshot_path.append("/data"); std::ifstream is(snapshot_path.c_str()); string key ; int64_t value = 0; while (is >> key >> value) { LOG(DEBUG) << "key:" << key << ",value:" << value; number_map_[key] = value; } return 0; }
function_block-function_prefixed
[]
C++
Wargame/Auth/Session.hpp
N00byEdge/best-wargame
35af9e00bad31c31eed4b902266e24dbf33a42ef
#pragma once #include <array> #include <random> #include <queue> #include "Wargame/Web/Network.hpp" #include "Wargame/Util.hpp" namespace Wargame { struct User; } namespace Auth { auto sessionTimeoutDuration = std::chrono::hours{24*7}; using SessionKey = std::array<char, 40>; constexpr char sessionChars[] { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" }; SessionKey makeSessionKey() { SessionKey key; for(std::size_t i = 0; i < key.size(); ++ i) std::sample(std::begin(sessionChars), std::end(sessionChars) - 1, key.begin()+ i, 1, Util::rand); return key; } struct UserPtr: std::weak_ptr<Wargame::User> { bool operator<(UserPtr const &other) const { return owner_before(other); } }; struct ActiveSession { static constexpr std::size_t SessionIndex = 0; static constexpr std::size_t UserIndex = 1; SessionKey sessionKey; UserPtr user; mutable std::chrono::time_point<std::chrono::system_clock> lastActiveAt; mutable std::queue<SessionKey> csrfTokens; }; struct CSRFToken { static constexpr std::size_t SessionIndex = 0; static constexpr std::size_t TokenIndex = 1; SessionKey session; SessionKey token; std::string uri; }; } namespace std { template<size_t Ind> constexpr auto &get(Auth::ActiveSession &session) noexcept { if constexpr(Ind == Auth::ActiveSession::SessionIndex) return session.sessionKey; else if constexpr(Ind == Auth::ActiveSession::UserIndex) return session.user; } template<size_t Ind> constexpr auto &get(Auth::ActiveSession const &session) noexcept { if constexpr(Ind == Auth::ActiveSession::SessionIndex) return session.sessionKey; else if constexpr(Ind == Auth::ActiveSession::UserIndex) return session.user; } template<size_t Ind> constexpr auto &get(Auth::CSRFToken &session) noexcept { if constexpr(Ind == Auth::CSRFToken::SessionIndex) return session.session; else if constexpr(Ind == Auth::CSRFToken::TokenIndex) return session.token; } template<size_t Ind> constexpr auto &get(Auth::CSRFToken const &session) noexcept { if constexpr(Ind == Auth::CSRFToken::SessionIndex) return session.session; else if constexpr(Ind == Auth::CSRFToken::TokenIndex) return session.token; } } template<> struct std::tuple_size<Auth::ActiveSession>: std::integral_constant<std::size_t, 2> { }; template<> struct std::tuple_size<Auth::CSRFToken>: std::integral_constant<std::size_t, 2> { }; #include "CQL/Custom.hpp" namespace CQL::Custom { template<> struct Unique<Auth::ActiveSession, Auth::ActiveSession::SessionIndex> { constexpr Uniqueness operator()() const { return Uniqueness::EnforceUnique; } }; template<> struct Unique<Auth::ActiveSession, Auth::ActiveSession::UserIndex> { constexpr Uniqueness operator()() const { return Uniqueness::NotUnique; } }; template<> struct Unique<Auth::CSRFToken, Auth::CSRFToken::SessionIndex> { constexpr Uniqueness operator()() const { return Uniqueness::NotUnique; } }; template<> struct Unique<Auth::CSRFToken, Auth::CSRFToken::TokenIndex> { constexpr Uniqueness operator()() const { return Uniqueness::AssumeUnique; } }; } #include "CQL.hpp" namespace Auth { CQL::Table<ActiveSession> activeSessions; CQL::Table<CSRFToken> csrfTokens; ActiveSession const *getSession(SessionKey const &sKey) { auto session = activeSessions.lookup<ActiveSession::SessionIndex>(sKey); if(session) { auto timeSinceOnline = std::chrono::system_clock::now() - session->lastActiveAt; if(timeSinceOnline > sessionTimeoutDuration) activeSessions.erase(std::exchange(session, nullptr)); } return session; } void updateSession(ActiveSession const *ptr, UserPtr user) { activeSessions.update<ActiveSession::UserIndex>(ptr, user); ptr->lastActiveAt = std::chrono::system_clock::now(); } void updateSession(ActiveSession const *ptr) { updateSession(ptr, ptr->user); } ActiveSession const *updateSession(SessionKey const &sKey, UserPtr user = {}) { auto ptr = getSession(sKey); if(!ptr) { ptr = activeSessions.emplace(ActiveSession{sKey}); } updateSession(ptr, user); return ptr; } void invalidateCSRFToken(SessionKey const &csrf) { auto tok = csrfTokens.lookup<CSRFToken::TokenIndex>(csrf); if(tok) csrfTokens.erase(tok); } bool consumeCSRFToken(ActiveSession const &session, SessionKey const &csrf, std::string_view uri) { auto tok = csrfTokens.lookup<CSRFToken::TokenIndex>(csrf); bool valid = tok && tok->session == session.sessionKey && tok->uri == uri; if(valid) csrfTokens.erase(tok); return valid; } SessionKey makeCSRFForSession(ActiveSession const &session, std::string_view uri) { auto csrf = Auth::makeSessionKey(); auto token = csrfTokens.emplace(CSRFToken{session.sessionKey, csrf, std::string{uri}}); session.csrfTokens.emplace(csrf); if(session.csrfTokens.size() > 10) invalidateCSRFToken(session.csrfTokens.front()), session.csrfTokens.pop(); return csrf; } }
#pragma once #include <array> #include <random> #include <queue> #include "Wargame/Web/Network.hpp" #include "Wargame/Util.hpp" namespace Wargame { struct User; } namespace Auth { auto sessionTimeoutDuration = std::chrono::hours{24*7}; using SessionKey = std::array<char, 40>; constexpr char sessionChars[] { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" }; SessionKey makeSessionKey() { SessionKey key; for(std::size_t i = 0; i < key.size(); ++ i) std::sample(std::begin(sessionChars), std::end(sessionChars) - 1, key.begin()+ i, 1, Util::rand); return key; } struct UserPtr: std::weak_ptr<Wargame::User> { bool operator<(UserPtr const &other) const { return owner_before(other); } }; struct ActiveSession { static constexpr std::size_t SessionIndex = 0; static constexpr std::size_t UserIndex = 1; SessionKey sessionKey; UserPtr user; mutable std::chrono::time_point<std::chrono::system_clock> lastActiveAt; mutable std::queue<SessionKey> csrfTokens; }; struct CSRFToken { static constexpr std::size_t SessionIndex = 0; static constexpr std::size_t TokenIndex = 1; SessionKey session; SessionKey token; std::string uri; }; } namespace std { template<size_t Ind> constexpr auto &get(Auth::ActiveSession &session) noexcept { if constexpr(Ind == Auth::ActiveSession::SessionIndex) return session.sessionKey; else if constexpr(Ind == Auth::ActiveSession::UserIndex) return session.user; } template<size_t Ind> constexpr auto &get(Auth::ActiveSession const &session) noexcept { if constexpr(Ind == Auth::ActiveSession::SessionIndex) return session.sessionKey; else if constexpr(Ind == Auth::ActiveSession::UserIndex) return session.user; } template<size_t Ind> constexpr auto &get(Auth::CSRFToken &session) noexcept { if constexpr(Ind == Auth::CSRFToken::SessionIndex) return session.session; else if constexpr(Ind == Auth::CSRFToken::TokenIndex) return session.token; } template<size_t Ind> constexpr auto &get(Auth::CSRFToken const &session) noexcept { if constexpr(Ind == Auth::CSRFToken::SessionIndex) return session.session; else if constexpr(Ind == Auth::CSRFToken::TokenIndex) return session.token; } } template<> struct std::tuple_size<Auth::ActiveSession>: std::integral_constant<std::size_t, 2> { }; template<> struct std::tuple_size<Auth::CSRFToken>: std::integral_constant<std::size_t, 2> { }; #include "CQL/Custom.hpp" namespace CQL::Custom { template<> struct Unique<Auth::ActiveSession, Auth::ActiveSession::SessionIndex> { constexpr Uniqueness operator()() const { return Uniqueness::EnforceUnique; } }; template<> struct Unique<Auth::ActiveSession, Auth::ActiveSession::UserIndex> { constexpr Uniqueness operator()() const { return Uniqueness::NotUnique; } }; template<> struct Unique<Auth::CSRFToken, Auth::CSRFToken::SessionIndex> { constexpr Uniqueness operator()() const { return Uniqueness::NotUnique; } }; template<> struct Unique<Auth::CSRFToken, Auth::CSRFToken::TokenIndex> { constexpr Uniqueness operator()() const { return Uniqueness::AssumeUnique; } }; } #include "CQL.hpp" namespace Auth { CQL::Table<ActiveSession> activeSessions; CQL::Table<CSRFToken> csrfTokens; ActiveSession const *getSession(SessionKey const &sKey) { auto session = activeSessions.lookup<ActiveSession::SessionIndex>(sKey);
return session; } void updateSession(ActiveSession const *ptr, UserPtr user) { activeSessions.update<ActiveSession::UserIndex>(ptr, user); ptr->lastActiveAt = std::chrono::system_clock::now(); } void updateSession(ActiveSession const *ptr) { updateSession(ptr, ptr->user); } ActiveSession const *updateSession(SessionKey const &sKey, UserPtr user = {}) { auto ptr = getSession(sKey); if(!ptr) { ptr = activeSessions.emplace(ActiveSession{sKey}); } updateSession(ptr, user); return ptr; } void invalidateCSRFToken(SessionKey const &csrf) { auto tok = csrfTokens.lookup<CSRFToken::TokenIndex>(csrf); if(tok) csrfTokens.erase(tok); } bool consumeCSRFToken(ActiveSession const &session, SessionKey const &csrf, std::string_view uri) { auto tok = csrfTokens.lookup<CSRFToken::TokenIndex>(csrf); bool valid = tok && tok->session == session.sessionKey && tok->uri == uri; if(valid) csrfTokens.erase(tok); return valid; } SessionKey makeCSRFForSession(ActiveSession const &session, std::string_view uri) { auto csrf = Auth::makeSessionKey(); auto token = csrfTokens.emplace(CSRFToken{session.sessionKey, csrf, std::string{uri}}); session.csrfTokens.emplace(csrf); if(session.csrfTokens.size() > 10) invalidateCSRFToken(session.csrfTokens.front()), session.csrfTokens.pop(); return csrf; } }
if(session) { auto timeSinceOnline = std::chrono::system_clock::now() - session->lastActiveAt; if(timeSinceOnline > sessionTimeoutDuration) activeSessions.erase(std::exchange(session, nullptr)); }
if_condition
[ { "content": "#pragma once\n\n\n\n#include \"Wargame/Auth/Passwords.hpp\"\n\n\n\nnamespace Auth {\n\n struct UserAuth {\n\n bool authenticate(std::string password) {\n\n auto attemptedHash = Auth::hashPassword(password, salt, hashIterations);\n\n return attemptedHash == passwordHash;\n\n }\n\n\...
C++
requests/requestexecutor.cpp
aghoward/dbpp
b55f1f3d70ea3f0a8d6058ab0ba3b4d5a568b802
#include "requests/requestexecutor.h" #include <algorithm> #include <cstdio> #include <memory> #include <optional> #include <string> #include <vector> #include <cpr/cpr.h> #include "parameters/arguments.h" #include "multi-threading/threadpool.h" #include "multi-threading/workqueue.h" #include "requests/executioncontext.h" #include "requests/requestfactory.h" #include "support/fileio.h" #include "support/template_formatting.h" bool RequestExecutor::status_code_indicates_existance(const int status_code) const { return std::find( _args.ignore_codes.begin(), _args.ignore_codes.end(), static_cast<uint16_t>(status_code)) == _args.ignore_codes.end(); } bool RequestExecutor::passes_content_length_check(const uint32_t content_length) const { return std::find( _args.ignore_content_lengths.begin(), _args.ignore_content_lengths.end(), static_cast<uint32_t>(content_length)) == _args.ignore_content_lengths.end(); } uint32_t get_content_length(cpr::Response& response) { return std::atoi(response.header["Content-Length"].c_str()); } bool RequestExecutor::response_passes_checks(cpr::Response& response) const { return status_code_indicates_existance(response.status_code) && passes_content_length_check(get_content_length(response)); } cpr::Response RequestExecutor::get_response( const std::string& url, const std::string& data, const std::map<std::string, std::string>& templates) { using namespace std::string_literals; if (data == ""s) _context->logger.log("Trying: \""s + url + "\"\r"s); else _context->logger.log("Trying: \""s + url + "\" - \"" + data + "\"\r"s); return _context->request_factory.make_request(url, data, templates); } std::optional<std::string> RequestExecutor::execute(const std::string& item, const std::string& request_template) { using namespace std::string_literals; auto templates = std::map<std::string, std::string>{{"{WORD}"s, item}, {"{BASE_URL}"s, _context->base_url}}; auto url = format_template(request_template, templates); auto data = format_template(_context->request_data, templates); auto response = get_response(url, data, templates); if (response_passes_checks(response)) { auto message_addendum = (data != ""s) ? "\" - \""s + data : ""s; _context->logger.log_line( "\""s + url + message_addendum + "\" - "s + std::to_string(get_content_length(response)) + " (CL) - "s + std::to_string(response.status_code) + " (S)"s); return url; } return {}; } std::vector<std::string> RequestExecutor::execute(const std::string& item) { auto results = std::vector<std::string>(); for (const auto& request_template : _context->request_templates) { auto result = execute(item, request_template); if (result) results.push_back(result.value()); } return results; } std::shared_ptr<WorkQueue<std::string>> RequestExecutor::create_work_queue(std::size_t queue_size) const { auto word_list = get_word_list(_args.wordlist_file); auto work_pool = std::make_shared<WorkQueue<std::string>>(queue_size); work_pool->add_items(word_list.begin(), word_list.end()); return work_pool; } std::vector<std::string> RequestExecutor::search(const std::vector<std::string>& request_templates) { using namespace std::string_literals; _context = std::make_shared<ExecutionContext>(_args.base_url, request_templates, _request_factory, _args.ignore_codes, _args.request_body); auto work_pool = create_work_queue(_args.thread_count); std::function work_func = [&](const std::string& item) { return execute(item); }; auto thread_pool = ThreadPool(work_func, work_pool); auto pool_results = thread_pool.execute(); auto found_items = std::vector<std::string>{}; for (const auto& pool_result : pool_results) found_items.insert(found_items.end(), pool_result.begin(), pool_result.end()); _context->logger.log_line(); return found_items; } void RequestExecutor::search() { search(_args.request_templates); } void RequestExecutor::recursive_search() { using namespace std::string_literals; auto urls = search(_args.request_templates); while (!urls.empty()) { auto url = urls.back(); urls.pop_back(); auto new_template = url + "/{WORD}"s; auto results = search({new_template}); urls.insert(urls.end(), results.begin(), results.end()); } }
#include "requests/requestexecutor.h" #include <algorithm> #include <cstdio> #include <memory> #include <optional> #include <string> #include <vector> #include <cpr/cpr.h> #include "parameters/arguments.h" #include "multi-threading/threadpool.h" #include "multi-threading/workqueue.h" #include "requests/executioncontext.h" #include "requests/requestfactory.h" #include "support/fileio.h" #include "support/template_formatting.h" bool RequestExecutor::status_code_indicates_existance(const int status_code) const { return std::find( _args.ignore_codes.begin(), _args.ignore_codes.end(), static_cast<uint16_t>(status_code)) == _args.ignore_codes.end(); } bool RequestExecutor::passes_content_length_check(const uint32_t content_length) const { return std::find( _args.ignore_content_lengths.begin(), _args.ignore_content_lengths.end(), static_cast<uint32_t>(content_length)) == _args.ignore_content_lengths.end(); } uint32_t get_content_length(cpr::Response& response) { return std::atoi(response.header["Content-Length"].c_str()); } bool RequestExecutor::response_passes_checks(cpr::Response& response) const { return status_code_indicates_existance(response.status_code) && passes_content_length_check(get_content_length(response)); } cpr::Response RequestExecutor::get_response( const std::string& url, const std::string& data, const std::map<std::string, std::string>& templates) { using namespace std::string_literals; if (data == ""s) _context->logger.log("Trying: \""s + url + "\"\r"s); else _context->logger.log("Trying: \""s + url + "\" - \"" + data + "\"\r"s); return _context->request_factory.make_request(url, data, templates); } std::optional<std::string> RequestExecutor::execute(const std::string& item, const std::string& request_template) { using namespace std::string_literals; auto templates = std::map<std::string, std::string>{{"{WORD}"s, item}, {"{BASE_URL}"s, _context->base_url}}; auto url = format_template(request_template, templates); auto data = format_template(_context->request_data, templates); auto response = get_response(url, data, templates); if (response_passes_checks(response)) { auto message_addendum = (data != ""s) ? "\" - \""s + data : ""s; _context->logger.log_line( "\""s + url + message_addendum + "\" - "s + std::to_string(get_content_length(response)) + " (CL) - "s + std::to_string(response.status_code) + " (S)"s); return url; } return {}; }
std::shared_ptr<WorkQueue<std::string>> RequestExecutor::create_work_queue(std::size_t queue_size) const { auto word_list = get_word_list(_args.wordlist_file); auto work_pool = std::make_shared<WorkQueue<std::string>>(queue_size); work_pool->add_items(word_list.begin(), word_list.end()); return work_pool; } std::vector<std::string> RequestExecutor::search(const std::vector<std::string>& request_templates) { using namespace std::string_literals; _context = std::make_shared<ExecutionContext>(_args.base_url, request_templates, _request_factory, _args.ignore_codes, _args.request_body); auto work_pool = create_work_queue(_args.thread_count); std::function work_func = [&](const std::string& item) { return execute(item); }; auto thread_pool = ThreadPool(work_func, work_pool); auto pool_results = thread_pool.execute(); auto found_items = std::vector<std::string>{}; for (const auto& pool_result : pool_results) found_items.insert(found_items.end(), pool_result.begin(), pool_result.end()); _context->logger.log_line(); return found_items; } void RequestExecutor::search() { search(_args.request_templates); } void RequestExecutor::recursive_search() { using namespace std::string_literals; auto urls = search(_args.request_templates); while (!urls.empty()) { auto url = urls.back(); urls.pop_back(); auto new_template = url + "/{WORD}"s; auto results = search({new_template}); urls.insert(urls.end(), results.begin(), results.end()); } }
std::vector<std::string> RequestExecutor::execute(const std::string& item) { auto results = std::vector<std::string>(); for (const auto& request_template : _context->request_templates) { auto result = execute(item, request_template); if (result) results.push_back(result.value()); } return results; }
function_block-full_function
[ { "content": "#include \"support/template_formatting.h\"\n\n\n\n#include <string>\n\n#include <map>\n\n#include <utility>\n\n\n\nnamespace impl\n\n{\n\n std::string format_single(const std::string& _template, const std::pair<std::string, std::string>& replacement)\n\n {\n\n auto result = _template;...
C++
SurgSim/Graphics/RenderTests/OsgPointCloudRepresentationRenderTests.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
#include <gtest/gtest.h> #include <memory> #include <vector> #include "SurgSim/DataStructures/Vertices.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Graphics/OsgBoxRepresentation.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgMaterial.h" #include "SurgSim/Graphics/OsgPointCloudRepresentation.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/PointCloudRepresentation.h" #include "SurgSim/Graphics/RenderTests/RenderTest.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" #include "SurgSim/Testing/MathUtilities.h" using SurgSim::Math::Vector3d; using SurgSim::Math::Vector4d; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::makeRigidTransform; using SurgSim::Math::makeRotationQuaternion; using SurgSim::Testing::interpolate; using SurgSim::Testing::interpolatePose; namespace SurgSim { namespace Graphics { using SurgSim::Graphics::PointCloud; struct OsgPointCloudRepresentationRenderTests : public RenderTest { protected: std::vector<Vector3d> makeCube() { std::vector<Vector3d> result; result.push_back(Vector3d(0.01, -0.01, 0.01)); result.push_back(Vector3d(0.01, -0.01, 0.01)); result.push_back(Vector3d(-0.01, -0.01, 0.01)); result.push_back(Vector3d(-0.01, -0.01, -0.01)); result.push_back(Vector3d(0.01, -0.01, -0.01)); result.push_back(Vector3d(0.01, 0.01, 0.01)); result.push_back(Vector3d(-0.01, 0.01, 0.01)); result.push_back(Vector3d(-0.01, 0.01, -0.01)); result.push_back(Vector3d(0.01, 0.01, -0.01)); return result; } std::shared_ptr<PointCloudRepresentation> makeCloud(std::vector<Vector3d> vertices) { std::shared_ptr<PointCloudRepresentation> representation = std::make_shared<OsgPointCloudRepresentation>("cloud representation"); representation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); for (auto it = std::begin(vertices); it != std::end(vertices); ++it) { representation->getVertices()->addVertex(SurgSim::Graphics::PointCloud::VertexType(*it)); } viewElement->addComponent(representation); return representation; } }; TEST_F(OsgPointCloudRepresentationRenderTests, PointAdd) { std::vector<Vector3d> vertices = makeCube(); auto representation = std::make_shared<OsgPointCloudRepresentation>("pointcloud representation"); auto pointCloud = representation->getVertices(); representation->setPointSize(2.0); RigidTransform3d pose = makeRigidTransform(makeRotationQuaternion(0.2, Vector3d(1.0, 1.0, 1.0)), Vector3d(0.0, 0.0, -0.2)); representation->setLocalPose(pose); viewElement->addComponent(representation); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); for (size_t i = 0; i < vertices.size(); ++i) { pointCloud->addVertex(PointCloud::VertexType(vertices[i])); boost::this_thread::sleep(boost::posix_time::milliseconds(250)); } } TEST_F(OsgPointCloudRepresentationRenderTests, StaticRotate) { std::shared_ptr<PointCloudRepresentation> representation = makeCloud(makeCube()); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; Vector3d startAngles(0.0, 0.0, 0.0); Vector3d endAngles(M_PI_4, M_PI_2, M_PI_2); Vector3d startPosition(-0.1, 0.0, -0.0); Vector3d endPosition(0.1, 0.0, -0.4); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; representation->setLocalPose(interpolatePose(startAngles, endAngles, startPosition, endPosition, t)); boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, DynamicRotate) { std::vector<Vector3d> startVertices = makeCube(); std::shared_ptr<PointCloudRepresentation> representation = makeCloud(startVertices); std::shared_ptr<PointCloud> pointCloud = representation->getVertices(); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; RigidTransform3d start = makeRigidTransform(makeRotationQuaternion(-M_PI_2, Vector3d(1.0, 1.0, 1.0)), Vector3d(-0.1, 0.0, 0.2)); RigidTransform3d end = makeRigidTransform(makeRotationQuaternion(M_PI_2, Vector3d(1.0, 1.0, 1.0)), Vector3d(0.1, 0.0, -0.2)); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; RigidTransform3d currentPose = interpolate(start, end, t); int id = 0; for (auto it = std::begin(startVertices); it != std::end(startVertices); ++it, ++id) { pointCloud->setVertexPosition(id, currentPose * (*it)); } boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, PointSizeAndColor) { std::shared_ptr<PointCloudRepresentation> representation = makeCloud(makeCube()); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; std::pair<double, double> size = std::make_pair(0.0, 20.0); std::pair<Vector4d, Vector4d> color = std::make_pair(Vector4d(0.0, 1.0, 0.0, 1.0), Vector4d(1.0, 0.0, 1.0, 1.0)); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; representation->setPointSize(interpolate(size, t)); representation->setColor(interpolate(color, t)); boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, PointSprite) { std::vector<Vector3d> vertices = makeCube(); auto graphics = std::make_shared<SurgSim::Graphics::OsgPointCloudRepresentation>("Cloud"); graphics->setPointSize(10.0f); graphics->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); for (auto vertex : vertices) { graphics->getVertices()->addVertex(SurgSim::Graphics::PointCloud::VertexType(vertex)); } auto material = std::make_shared<SurgSim::Graphics::OsgMaterial>("material"); auto texture = std::make_shared<SurgSim::Graphics::OsgTexture2d>(); texture->setIsPointSprite(true); std::string textureFilename; ASSERT_TRUE(runtime->getApplicationData()->tryFindFile("Textures/checkered.png", &textureFilename)); texture->loadImage(textureFilename); auto diffuseMapUniform = std::make_shared<SurgSim::Graphics::OsgTextureUniform<SurgSim::Graphics::OsgTexture2d>>("diffuseMap"); diffuseMapUniform->set(texture); material->addUniform(diffuseMapUniform); graphics->setMaterial(material); auto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>("Blood"); sceneElement->addComponent(graphics); sceneElement->addComponent(material); scene->addSceneElement(sceneElement); runtime->start(); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); runtime->stop(); } }; };
#include <gtest/gtest.h> #include <memory> #include <vector> #include "SurgSim/DataStructures/Vertices.h" #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Graphics/OsgBoxRepresentation.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgMaterial.h" #include "SurgSim/Graphics/OsgPointCloudRepresentation.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/PointCloudRepresentation.h" #include "SurgSim/Graphics/RenderTests/RenderTest.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Vector.h" #include "SurgSim/Testing/MathUtilities.h" using SurgSim::Math::Vector3d; using SurgSim::Math::Vector4d; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::makeRigidTransform; using SurgSim::Math::makeRotationQuaternion; using SurgSim::Testing::interpolate; using SurgSim::Testing::interpolatePose; namespace SurgSim { namespace Graphics { using SurgSim::Graphics::PointCloud; struct OsgPointCloudRepresentationRenderTests : public RenderTest { protected: std::vector<Vector3d> makeCube() { std::vector<Vector3d> result; result.push_back(Vector3d(0.01, -0.01, 0.01)); result.push_back(Vector3d(0.01, -0.01, 0.01)); result.push_back(Vector3d(-0.01, -0.01, 0.01)); result.push_back(Vector3d(-0.01, -0.01, -0.01)); result.push_back(Vector3d(0.01, -0.01, -0.01)); result.push_back(Vector3d(0.01, 0.01, 0.01)); result.push_back(Vector3d(-0.01, 0.01, 0.01)); result.push_back(Vector3d(-0.01, 0.01, -0.01)); result.push_back(Vector3d(0.01, 0.01, -0.01)); return result; } std::shared_ptr<PointCloudRepresentation> makeCloud(std::vector<Vector3d> vertices) { std::shared_ptr<PointCloudRepresentation> representation = std::make_shared<OsgPointCloudRepresentation>("cloud representation"); representation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); for (auto it = std::begin(vertices); it != std::end(vertices); ++it) { representation->getVertices()->addVertex(SurgSim::Graphics::PointCloud::VertexType(*it)); } viewElement->addComponent(representation); return representation; } }; TEST_F(OsgPointCloudRepresentationRenderTests, PointAdd) { std::vector<Vector3d> vertices = makeCube(); auto representation = std::make_shared<OsgPointCloudRepresentation>("pointcloud representation"); auto pointCloud = representation->getVertices(); representation->setPointSize(2.0); RigidTransform3d pose = makeRigidTransform(makeRotationQuaternion(0.2, Vector3d(1.0, 1.0, 1.0)), Vector3d(0.0, 0.0, -0.2)); representation->setLocalPose(pose);
TEST_F(OsgPointCloudRepresentationRenderTests, StaticRotate) { std::shared_ptr<PointCloudRepresentation> representation = makeCloud(makeCube()); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; Vector3d startAngles(0.0, 0.0, 0.0); Vector3d endAngles(M_PI_4, M_PI_2, M_PI_2); Vector3d startPosition(-0.1, 0.0, -0.0); Vector3d endPosition(0.1, 0.0, -0.4); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; representation->setLocalPose(interpolatePose(startAngles, endAngles, startPosition, endPosition, t)); boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, DynamicRotate) { std::vector<Vector3d> startVertices = makeCube(); std::shared_ptr<PointCloudRepresentation> representation = makeCloud(startVertices); std::shared_ptr<PointCloud> pointCloud = representation->getVertices(); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; RigidTransform3d start = makeRigidTransform(makeRotationQuaternion(-M_PI_2, Vector3d(1.0, 1.0, 1.0)), Vector3d(-0.1, 0.0, 0.2)); RigidTransform3d end = makeRigidTransform(makeRotationQuaternion(M_PI_2, Vector3d(1.0, 1.0, 1.0)), Vector3d(0.1, 0.0, -0.2)); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; RigidTransform3d currentPose = interpolate(start, end, t); int id = 0; for (auto it = std::begin(startVertices); it != std::end(startVertices); ++it, ++id) { pointCloud->setVertexPosition(id, currentPose * (*it)); } boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, PointSizeAndColor) { std::shared_ptr<PointCloudRepresentation> representation = makeCloud(makeCube()); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); int numSteps = 100; std::pair<double, double> size = std::make_pair(0.0, 20.0); std::pair<Vector4d, Vector4d> color = std::make_pair(Vector4d(0.0, 1.0, 0.0, 1.0), Vector4d(1.0, 0.0, 1.0, 1.0)); for (int i = 0; i < numSteps; ++i) { double t = static_cast<double>(i) / numSteps; representation->setPointSize(interpolate(size, t)); representation->setColor(interpolate(color, t)); boost::this_thread::sleep(boost::posix_time::milliseconds(1000 / numSteps)); } } TEST_F(OsgPointCloudRepresentationRenderTests, PointSprite) { std::vector<Vector3d> vertices = makeCube(); auto graphics = std::make_shared<SurgSim::Graphics::OsgPointCloudRepresentation>("Cloud"); graphics->setPointSize(10.0f); graphics->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); for (auto vertex : vertices) { graphics->getVertices()->addVertex(SurgSim::Graphics::PointCloud::VertexType(vertex)); } auto material = std::make_shared<SurgSim::Graphics::OsgMaterial>("material"); auto texture = std::make_shared<SurgSim::Graphics::OsgTexture2d>(); texture->setIsPointSprite(true); std::string textureFilename; ASSERT_TRUE(runtime->getApplicationData()->tryFindFile("Textures/checkered.png", &textureFilename)); texture->loadImage(textureFilename); auto diffuseMapUniform = std::make_shared<SurgSim::Graphics::OsgTextureUniform<SurgSim::Graphics::OsgTexture2d>>("diffuseMap"); diffuseMapUniform->set(texture); material->addUniform(diffuseMapUniform); graphics->setMaterial(material); auto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>("Blood"); sceneElement->addComponent(graphics); sceneElement->addComponent(material); scene->addSceneElement(sceneElement); runtime->start(); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); runtime->stop(); } }; };
viewElement->addComponent(representation); runtime->start(); EXPECT_TRUE(graphicsManager->isInitialized()); EXPECT_TRUE(viewElement->isInitialized()); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); for (size_t i = 0; i < vertices.size(); ++i) { pointCloud->addVertex(PointCloud::VertexType(vertices[i])); boost::this_thread::sleep(boost::posix_time::milliseconds(250)); } }
function_block-function_prefix_line
[ { "content": "struct OsgVectorFieldRepresentationRenderTests : public SurgSim::Graphics::RenderTest\n\n{\n\nprotected:\n\n\t// A point is a location (X,Y,Z) in 3D space\n\n\tstd::vector<Vector3d> makeStartingPoints()\n\n\t{\n\n\t\tstd::vector<Vector3d> points(8);\n\n\t\tpoints[0] = Vector3d(1.0, 0.0, 0.0);\n\n\...
C++
Utilities/itkSplitAlternatingTimeSeriesImageFilter.hxx
KevinScholtes/ANTsX
5462269c0c32e5d65560bae4014c5a05cb02588d
#ifndef __itkSplitAlternatingTimeSeriesImageFilter_hxx #define __itkSplitAlternatingTimeSeriesImageFilter_hxx #include "itkSplitAlternatingTimeSeriesImageFilter.h" #include "itkProgressReporter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" namespace itk { template< typename TInputImage, typename TOutputImage > SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::SplitAlternatingTimeSeriesImageFilter() { this->SetNumberOfRequiredOutputs(2); this->SetNthOutput( 0, this->MakeOutput(0) ); this->SetNthOutput( 1, this->MakeOutput(1) ); } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::GenerateOutputInformation() { typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); typename Superclass::OutputImagePointer outputPtr0 = this->GetOutput(0); typename Superclass::OutputImagePointer outputPtr1 = this->GetOutput(1); if ( !outputPtr0 || !outputPtr1 || !inputPtr ) { return; } OutputImageRegionType outputLargestPossibleRegion; this->CallCopyInputRegionToOutputRegion( outputLargestPossibleRegion, inputPtr->GetLargestPossibleRegion() ); unsigned int halfTime = inputPtr->GetLargestPossibleRegion().GetSize()[InputImageDimension-1] / 2; outputLargestPossibleRegion.SetSize( InputImageDimension-1, halfTime ); outputPtr0->SetLargestPossibleRegion(outputLargestPossibleRegion); outputPtr1->SetLargestPossibleRegion(outputLargestPossibleRegion); outputPtr0->SetSpacing( inputPtr->GetSpacing() ); outputPtr1->SetSpacing( inputPtr->GetSpacing() ); outputPtr0->SetDirection( inputPtr->GetDirection() ); outputPtr1->SetDirection( inputPtr->GetDirection() ); typename InputImageType::PointType origin = inputPtr->GetOrigin(); outputPtr0->SetOrigin( origin ); origin[InputImageDimension-1] += inputPtr->GetSpacing()[InputImageDimension-1]; outputPtr1->SetOrigin( origin ); const unsigned int numComponents = inputPtr->GetNumberOfComponentsPerPixel(); if ( numComponents != outputPtr0->GetNumberOfComponentsPerPixel() ) { outputPtr0->SetNumberOfComponentsPerPixel( numComponents ); } if ( numComponents != outputPtr1->GetNumberOfComponentsPerPixel() ) { outputPtr1->SetNumberOfComponentsPerPixel( numComponents ); } } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId) { itkDebugMacro(<< "Actually executing"); ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); OutputImageRegionType outputRegion = outputRegionForThread; ImageRegionIterator< OutputImageType > outIt0( this->GetOutput(0), outputRegion); ImageRegionIterator< OutputImageType > outIt1( this->GetOutput(1), outputRegion); while ( !outIt0.IsAtEnd() ) { typename InputImageType::IndexType idx = outIt0.GetIndex(); idx[InputImageDimension-1] *= 2; outIt0.Set( this->GetInput()->GetPixel( idx ) ); idx[InputImageDimension-1] += 1; outIt1.Set( this->GetInput()->GetPixel( idx ) ); ++outIt0; ++outIt1; } } } #endif
#ifndef __itkSplitAlternatingTimeSeriesImageFilter_hxx #define __itkSplitAlternatingTimeSeriesImageFilter_hxx #include "itkSplitAlternatingTimeSeriesImageFilter.h" #include "itkProgressReporter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" namespace itk { template< typename TInputImage, typename TOutputImage > SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::SplitAlternatingTimeSeriesImageFilter() { this->SetNumberOfRequiredOutputs(2); this->SetNthOutput( 0, this->MakeOutput(0) ); this->SetNthOutput( 1, this->MakeOutput(1) ); } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::GenerateOutputInformation() { typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); typename Superclass::OutputImagePointer outputPtr0 = this->GetOutput(0); typename Superclass::OutputImagePointer outputPtr1 = this->GetOutput(1); if ( !outputPtr0 || !outputPtr1 || !inputPtr ) { return; } OutputImageRegionType outputLargestPossibleRegion; this->CallCopyInputRegionToOutputRegion( outputLargestPossibleRegion, inputPtr->GetLargestPossibleRegion() ); unsigned int halfTime = inputPtr->GetLargestPossibleRegion().GetSize()[InputImageDimension-1] / 2; outputLargestPossibleRegion.SetSize( InputImageDimension-1, halfTime ); outputPtr0->SetLargestPossibleRegion(outputLargestPossibleRegion); outputPtr1->SetLargestPossibleRegion(outputLargestPossibleRegion); outputPtr0->SetSpacing( inputPtr->GetSpacing() ); outputPtr1->SetSpacing( inputPtr->GetSpacing() ); outputPtr0->SetDirection( inputPtr->GetDirection() ); outputPtr1->SetDirection( inputPtr->GetDirection() ); typename InputImageType::PointType origin = inputPtr->GetOrigin(); outputPtr0->SetOrigin( origin ); origin[InputImageDimension-1] += inputPtr->GetSpacing()[InputImageDimension-1]; outputPtr1->SetOrigin( origin ); const unsigned int numComponents = inputPtr->GetNumberOfComponentsPerPixel();
if ( numComponents != outputPtr1->GetNumberOfComponentsPerPixel() ) { outputPtr1->SetNumberOfComponentsPerPixel( numComponents ); } } template< typename TInputImage, typename TOutputImage > void SplitAlternatingTimeSeriesImageFilter< TInputImage, TOutputImage > ::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId) { itkDebugMacro(<< "Actually executing"); ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); OutputImageRegionType outputRegion = outputRegionForThread; ImageRegionIterator< OutputImageType > outIt0( this->GetOutput(0), outputRegion); ImageRegionIterator< OutputImageType > outIt1( this->GetOutput(1), outputRegion); while ( !outIt0.IsAtEnd() ) { typename InputImageType::IndexType idx = outIt0.GetIndex(); idx[InputImageDimension-1] *= 2; outIt0.Set( this->GetInput()->GetPixel( idx ) ); idx[InputImageDimension-1] += 1; outIt1.Set( this->GetInput()->GetPixel( idx ) ); ++outIt0; ++outIt1; } } } #endif
if ( numComponents != outputPtr0->GetNumberOfComponentsPerPixel() ) { outputPtr0->SetNumberOfComponentsPerPixel( numComponents ); }
if_condition
[ { "content": "class ITK_TEMPLATE_EXPORT SimulatedDisplacementFieldSource:\n\n public ImageSource<TOutputImage>\n\n{\n\npublic:\n\n ITK_DISALLOW_COPY_AND_ASSIGN( SimulatedDisplacementFieldSource );\n\n\n\n /** Standard class type aliases. */\n\n using Self = SimulatedDisplacementFieldSource;\n\n using Super...
C++
searchlib/src/tests/features/subqueries/subqueries_test.cpp
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
#include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/features/setup.h> #include <vespa/searchlib/fef/test/indexenvironment.h> #include <vespa/searchlib/fef/test/indexenvironmentbuilder.h> #include <vespa/searchlib/fef/test/queryenvironment.h> #include <vespa/searchlib/features/subqueries_feature.h> #include <vespa/searchlib/fef/fef.h> #include <vespa/searchlib/fef/test/dummy_dependency_handler.h> #include <vespa/vespalib/util/stringfmt.h> using search::feature_t; using namespace search::fef; using namespace search::fef::test; using namespace search::features; using CollectionType = FieldInfo::CollectionType; struct BlueprintFactoryFixture { BlueprintFactory factory; BlueprintFactoryFixture() : factory() { setup_search_features(factory); } }; struct IndexFixture { IndexEnvironment indexEnv; IndexFixture() : indexEnv() { IndexEnvironmentBuilder builder(indexEnv); builder.addField(FieldType::INDEX, CollectionType::SINGLE, "foo"); builder.addField(FieldType::ATTRIBUTE, CollectionType::SINGLE, "bar"); } }; struct FeatureDumpFixture : public IDumpFeatureVisitor { virtual void visitDumpFeature(const vespalib::string &) override { TEST_ERROR("no features should be dumped"); } FeatureDumpFixture() : IDumpFeatureVisitor() {} }; struct RankFixture : BlueprintFactoryFixture, IndexFixture { QueryEnvironment queryEnv; RankSetup rankSetup; MatchDataLayout mdl; MatchData::UP match_data; RankProgram::UP rankProgram; std::vector<TermFieldHandle> fooHandles; std::vector<TermFieldHandle> barHandles; RankFixture(size_t fooCnt, size_t barCnt, std::string featureName = "subqueries(foo)") : queryEnv(&indexEnv), rankSetup(factory, indexEnv), mdl(), match_data(), rankProgram(), fooHandles(), barHandles() { fooHandles = addFields(fooCnt, indexEnv.getFieldByName("foo")->id()); barHandles = addFields(barCnt, indexEnv.getFieldByName("bar")->id()); rankSetup.setFirstPhaseRank(featureName); rankSetup.setIgnoreDefaultRankFeatures(true); ASSERT_TRUE(rankSetup.compile()); match_data = mdl.createMatchData(); rankProgram = rankSetup.create_first_phase_program(); rankProgram->setup(*match_data, queryEnv); } std::vector<TermFieldHandle> addFields(size_t count, uint32_t fieldId) { std::vector<TermFieldHandle> handles; for (size_t i = 0; i < count; ++i) { handles.push_back(mdl.allocTermField(fieldId)); SimpleTermData term; term.addField(fieldId).setHandle(handles.back()); queryEnv.getTerms().push_back(term); } return handles; } feature_t getSubqueries(uint32_t docId) { return Utils::getScoreFeature(*rankProgram, docId); } void setSubqueries(TermFieldHandle handle, uint32_t docId, uint64_t subqueries) { match_data->resolveTermField(handle)->setSubqueries(docId, subqueries); } void setFooSubqueries(uint32_t i, uint32_t docId, uint64_t subqueries) { ASSERT_LESS(i, fooHandles.size()); setSubqueries(fooHandles[i], docId, subqueries); } void setBarSubqueries(uint32_t i, uint32_t docId, uint64_t subqueries) { ASSERT_LESS(i, barHandles.size()); setSubqueries(barHandles[i], docId, subqueries); } }; TEST_F("require that blueprint can be created from factory", BlueprintFactoryFixture) { Blueprint::SP bp = f.factory.createBlueprint("subqueries"); EXPECT_TRUE(bp.get() != 0); EXPECT_TRUE(dynamic_cast<SubqueriesBlueprint*>(bp.get()) != 0); } TEST_FFF("require that no features are dumped", SubqueriesBlueprint, IndexFixture, FeatureDumpFixture) { f1.visitDumpFeatures(f2.indexEnv, f3); } TEST_FF("require that setup can be done on index field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(foo)", f1.getBaseName().c_str())); EXPECT_TRUE(((Blueprint&)f1).setup(f2.indexEnv, {"foo"})); } TEST_FF("require that setup can be done on attribute field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(bar)", f1.getBaseName().c_str())); EXPECT_TRUE(((Blueprint&)f1).setup(f2.indexEnv, {"bar"})); } TEST_FF("require that setup fails for unknown field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(unknown)", f1.getBaseName().c_str())); EXPECT_FALSE(((Blueprint&)f1).setup(f2.indexEnv, {"unknown"})); } TEST_F("require that not searching a field will give it 0 subqueries", RankFixture(0, 3)) { EXPECT_EQUAL(0, f1.getSubqueries(10)); } TEST_F("require that subqueries can be obtained", RankFixture(1, 0)) { f1.setFooSubqueries(0, 10, 0x1234); EXPECT_EQUAL(0x1234, f1.getSubqueries(10)); } TEST_F("require that msb subqueries can be obtained", RankFixture(1, 0, "subqueries(foo).msb")) { f1.setFooSubqueries(0, 10, 0x123412345678ULL); EXPECT_EQUAL(0x1234, f1.getSubqueries(10)); } TEST_F("require that multiple subqueries are accumulated", RankFixture(3, 0)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 10, 2); f1.setFooSubqueries(2, 10, 4); EXPECT_EQUAL(7, f1.getSubqueries(10)); } TEST_F("require that stale subqueries are ignored", RankFixture(3, 0)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 9, 2); f1.setFooSubqueries(2, 10, 4); EXPECT_EQUAL(5, f1.getSubqueries(10)); } TEST_F("require that subqueries from other fields are ignored", RankFixture(2, 2)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 10, 2); f1.setBarSubqueries(0, 10, 4); f1.setBarSubqueries(1, 10, 8); EXPECT_EQUAL(3, f1.getSubqueries(10)); } TEST_MAIN() { TEST_RUN_ALL(); }
#include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/features/setup.h> #include <vespa/searchlib/fef/test/indexenvironment.h> #include <vespa/searchlib/fef/test/indexenvironmentbuilder.h> #include <vespa/searchlib/fef/test/queryenvironment.h> #include <vespa/searchlib/features/subqueries_feature.h> #include <vespa/searchlib/fef/fef.h> #include <vespa/searchlib/fef/test/dummy_dependency_handler.h> #include <vespa/vespalib/util/stringfmt.h> using search::feature_t; using namespace search::fef; using namespace search::fef::test; using namespace search::features; using CollectionType = FieldInfo::CollectionType; struct BlueprintFactoryFixture { BlueprintFactory factory; BlueprintFactoryFixture() : factory() { setup_search_features(factory); } }; struct IndexFixture { IndexEnvironment indexEnv; IndexFixture() : indexEnv() { IndexEnvironmentBuilder builder(indexEnv); builder.addField(FieldType::INDEX, CollectionType::SINGLE, "foo"); builder.addField(FieldType::ATTRIBUTE, CollectionType::SINGLE, "bar"); } }; struct FeatureDumpFixture : public IDumpFeatureVisitor { virtual void visitDumpFeature(const vespalib::string &) override { TEST_ERROR("no features should be dumped"); } FeatureDumpFixture() : IDumpFeatureVisitor() {} }; struct RankFixture : BlueprintFactoryFixture, IndexFixture { QueryEnvironment queryEnv; RankSetup rankSetup; MatchDataLayout mdl; MatchData::UP match_data; RankProgram::UP rankProgram; std::vector<TermFieldHandle> fooHandles; std::vector<TermFieldHandle> barHandles; RankFixture(size_t fooCnt, size_t barCnt, std::string featureName = "subqueries(foo)") : queryEnv(&indexEnv), rankSetup(factory, indexEnv), mdl(), match_data(), rankProgram(), fooHandles(), barHandles() { fooHandles = addFields(fooCnt, indexEnv.getFieldByName("foo")->id()); barHandles = addFields(barCnt, indexEnv.getFieldByName("bar")->id()); rankSetup.setFirstPhaseRank(featureName); rankSetup.setIgnoreDefaultRankFeatures(true); ASSERT_TRUE(rankSetup.compile()); match_data = mdl.createMatchData(); rankProgram = rankSetup.create_first_phase_program(); rankProgram->setup(*match_data, queryEnv); } std::vector<TermFieldHandle> addFields(size_t count, uint32_t fieldId) { std::vector<TermFieldHandle> handles; for (size_t i = 0; i < count; ++i) { handles.push_back(mdl.allocTermField(fieldId)); SimpleTermData term; term.addField(fieldId).setHandle(handles.back()); queryEnv.getTerms().push_back(term); } return handles; } feature_t getSubqueries(uint32_t docId) { return Utils::getScoreFeature(*rankProgram, docId); } void setSubqueries(TermFieldHandle handle, uint32_t docId, uint64_t subqueries) { match_data->resolveTermField(handle)->setSubqueries(docId, subqueries); } void setFooSubqueries(uint32_t i, uint32_t docId, uint64_t subqueries) { ASSERT_LESS(i, fooHandles.size()); setSubqueries(fooHandles[i], docId, subqueries); } void setBarSubqueries(uint32_t i, uint32_t docId, uint64_t subqueries) { ASSERT_LESS(i, barHandles.size()); setSubqueries(barHandles[i], docId, subqueries); } }; TEST_F("require that blueprint can be created from factory", BlueprintFactoryFixture) { Blueprint::SP bp = f.factory.createBlueprint("subqueries"); EXPECT_TRUE(bp.get() != 0); EXPECT_TRUE(dynamic_cast<SubqueriesBlueprint*>(bp.get()) != 0); } TEST_FFF("require that no features are dumped", SubqueriesBlueprint, IndexFixture, FeatureDumpFixture) { f1.visitDumpFeatures(f2.indexEnv, f3); } TEST_FF("require that setup can be done on index field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(foo)", f1.getBaseName().c_str())); EXPECT_TRUE(((Blueprint&)f1).setup(f2.indexEnv, {"f
())); EXPECT_FALSE(((Blueprint&)f1).setup(f2.indexEnv, {"unknown"})); } TEST_F("require that not searching a field will give it 0 subqueries", RankFixture(0, 3)) { EXPECT_EQUAL(0, f1.getSubqueries(10)); } TEST_F("require that subqueries can be obtained", RankFixture(1, 0)) { f1.setFooSubqueries(0, 10, 0x1234); EXPECT_EQUAL(0x1234, f1.getSubqueries(10)); } TEST_F("require that msb subqueries can be obtained", RankFixture(1, 0, "subqueries(foo).msb")) { f1.setFooSubqueries(0, 10, 0x123412345678ULL); EXPECT_EQUAL(0x1234, f1.getSubqueries(10)); } TEST_F("require that multiple subqueries are accumulated", RankFixture(3, 0)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 10, 2); f1.setFooSubqueries(2, 10, 4); EXPECT_EQUAL(7, f1.getSubqueries(10)); } TEST_F("require that stale subqueries are ignored", RankFixture(3, 0)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 9, 2); f1.setFooSubqueries(2, 10, 4); EXPECT_EQUAL(5, f1.getSubqueries(10)); } TEST_F("require that subqueries from other fields are ignored", RankFixture(2, 2)) { f1.setFooSubqueries(0, 10, 1); f1.setFooSubqueries(1, 10, 2); f1.setBarSubqueries(0, 10, 4); f1.setBarSubqueries(1, 10, 8); EXPECT_EQUAL(3, f1.getSubqueries(10)); } TEST_MAIN() { TEST_RUN_ALL(); }
oo"})); } TEST_FF("require that setup can be done on attribute field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(bar)", f1.getBaseName().c_str())); EXPECT_TRUE(((Blueprint&)f1).setup(f2.indexEnv, {"bar"})); } TEST_FF("require that setup fails for unknown field", SubqueriesBlueprint, IndexFixture) { DummyDependencyHandler deps(f1); f1.setName(vespalib::make_string("%s(unknown)", f1.getBaseName().c_str
random
[]
C++
Engine/src/CotQuaternion.cpp
TeamNut/CotEngine
d7f8c39715b8828eb8b4295c8ad844bdc7ab6849
#include "math/CotQuaternion.h" #include "math/CotVec3.h" #include "math/CotVec4.h" namespace Cot { Quaternion::Quaternion() : x(0.0f), y(0.0f), z(0.0f), w(1.0f) { } Quaternion::Quaternion(const float value) : x(value), y(value), z(value), w(value) { } Quaternion::Quaternion(const float xx, const float yy, const float zz, const float ww) : x(xx), y(yy), z(zz), w(ww) { } Quaternion::Quaternion(const float* array) : x(array[0]), y(array[1]), z(array[2]), w(array[3]) { } Quaternion::Quaternion(const Vec3& v, float ww) : x(v.x), y(v.y), z(v.z), w(ww) { } Quaternion::Quaternion(const Vec4& v) : x(v.x), y(v.y), z(v.z), w(v.w) { } Quaternion::Quaternion(const Quaternion& other) : x(other.x), y(other.y), z(other.z), w(other.w) { } Quaternion::Quaternion(const Quaternion&& other) : x(other.x), y(other.y), z(other.z), w(other.w) { } Quaternion::~Quaternion() { } void Quaternion::SetXYZ(const Vec3& v) { x = v.x; y = v.y; z = v.z; } Vec3 Quaternion::GetXYZ() const { return Vec3(x, y, z); } void Quaternion::SetEuler(const Vec3& euler) { Quaternion pitch(1.0f, 0.0f, 0.0f, euler.x); Quaternion yaw(0.0f, 1.0f, 1.0f, euler.y); Quaternion roll(0.0f, 0.0f, 1.0f, euler.z); (*this) = pitch * yaw * roll; } Vec3 Quaternion::GetEuler() const { return Vec3( atan2(2 * x * w - 2 * y * z, 1 - 2 * x * x - 2 * z * z), atan2(2 * y * w - 2 * x * z, 1 - 2 * y * y - 2 * z * z), asin(2 * x * y + 2 * z * w)); } float Quaternion::Length() const { return sqrt(x * x + y * y + z * z + w * w); } Vec3 Quaternion::GetAxis() const { float x = 1.0f - w * w; if (x <= 0.0f) { return Vec3::AxisX; } float x2 = x * x; Vec3 xyz = GetXYZ(); return GetXYZ() / x2; } const Quaternion Quaternion::operator+(const Quaternion& other) const { return Quaternion(x + other.x, y + other.y, z + other.z, w + other.w); } const Quaternion Quaternion::operator-(const Quaternion& other) const { return Quaternion(x - other.x, y - other.y, z - other.z, w - other.w); } const Quaternion Quaternion::operator*(const Quaternion& other) const { return Quaternion::Normalize( Quaternion ( ((x * other.x) + (x * other.w)) + ((y * other.z) - (z * other.y)), ((x * other.y) + (y * other.w)) + ((z * other.x) - (x * other.z)), ((x * other.z) + (z * other.w)) + ((x * other.y) - (y * other.x)), ((w * other.w) + (x * other.x)) + ((y * other.y) - (z * other.z)) )); } const Quaternion Quaternion::operator/(const Quaternion& other) const { COT_ASSERT(other.x <= 0.0f, "Division by 0"); COT_ASSERT(other.y <= 0.0f, "Division by 0"); COT_ASSERT(other.z <= 0.0f, "Division by 0"); COT_ASSERT(other.w <= 0.0f, "Division by 0"); return Quaternion(x / other.x, y / other.y, z / other.z, w / other.w); } const Quaternion Quaternion::operator+(const float value) const { return Quaternion(x + value, y + value, z + value, w + value); } const Quaternion Quaternion::operator-(const float value) const { return Quaternion(x - value, y - value, z - value, w - value); } const Quaternion Quaternion::operator*(const float value) const { return Quaternion(x * value, y * value, z * value, w * value); } const Quaternion Quaternion::operator/(const float value) const { COT_ASSERT(value <= 0.0f, "Division by 0"); return Quaternion(x / value, y / value, z / value, w / value); } Quaternion& Quaternion::operator+=(const Quaternion& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Quaternion& Quaternion::operator-=(const Quaternion& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } Quaternion& Quaternion::operator*=(const Quaternion& other) { (*this) = (*this) * other; return *this; } Quaternion& Quaternion::operator/=(const Quaternion& other) { COT_ASSERT(other.x <= 0.0f, "Division by 0"); COT_ASSERT(other.y <= 0.0f, "Division by 0"); COT_ASSERT(other.z <= 0.0f, "Division by 0"); COT_ASSERT(other.w <= 0.0f, "Division by 0"); x /= other.x; y /= other.y; z /= other.z; w /= other.w; return *this; } Quaternion& Quaternion::operator=(const Quaternion& other) { x = other.x; y = other.y; z = other.z; w = other.w; return *this; } Quaternion& Quaternion::operator+=(const float value) { x += value; y += value; z += value; w += value; return *this; } Quaternion& Quaternion::operator-=(const float value) { x -= value; y -= value; z -= value; w -= value; return *this; } Quaternion& Quaternion::operator*=(const float value) { x *= value; y *= value; z *= value; w *= value; return *this; } Quaternion& Quaternion::operator/=(const float value) { COT_ASSERT(value <= 0.0f, "Division by 0"); x /= value; y /= value; z /= value; w /= value; return *this; } Quaternion& Quaternion::operator=(const float value) { x = value; y = value; z = value; w = value; return *this; } const Quaternion Quaternion::operator-() const { return Quaternion(-x, -y, -z, -w); } bool Quaternion::operator<(const Quaternion& other) const { return (x < other.x && y < other.y && z < other.z && w < other.w); } bool Quaternion::operator<=(const Quaternion& other) const { return (x <= other.x && y <= other.y && z <= other.z && w <= other.w); } bool Quaternion::operator>(const Quaternion& other) const { return (x > other.x && y > other.y && z > other.z && w > other.w); } bool Quaternion::operator>=(const Quaternion& other) const { return (x >= other.x && y >= other.y && z >= other.z && w >= other.w); } bool Quaternion::operator==(const Quaternion& other) const { return (x == other.x && y == other.y && z == other.z && w == other.w); } bool Quaternion::operator!=(const Quaternion& other) const { return (x != other.x || y != other.y || z != other.z, w != other.w); } bool Quaternion::IsZero() const { return (x == 0.0f && y == 0.0f && z == 0.0f && w == 0.0f); } bool Quaternion::IsOne() const { return (x == 1.0f && y == 1.0f && z == 1.0f && w == 1.0f); } const Vec3 Quaternion::Rotate(const Quaternion& quaternion, const Vec3& axis) { float tempX, tempY, tempZ, tempW; tempX = (((quaternion.w * axis.x) + (quaternion.y * axis.z)) - (quaternion.z * axis.y)); tempY = (((quaternion.w * axis.y) + (quaternion.z * axis.x)) - (quaternion.x * axis.z)); tempZ = (((quaternion.w * axis.z) + (quaternion.x * axis.y)) - (quaternion.y * axis.x)); tempW = (((quaternion.x * axis.x) + (quaternion.y * axis.y)) + (quaternion.z * axis.z)); return Vec3( ((((tempW * quaternion.x) + (tempX * quaternion.w)) - (tempY * quaternion.z)) + (tempZ * quaternion.y)), ((((tempW * quaternion.y) + (tempY * quaternion.w)) - (tempZ * quaternion.x)) + (tempX * quaternion.z)), ((((tempW * quaternion.z) + (tempZ * quaternion.w)) - (tempX * quaternion.y)) + (tempY * quaternion.x)) ); } const Quaternion Quaternion::Rotation(const Vec3& axis1, const Vec3& axis2) { float cosHalfAngle, recipCosHalfAngle; cosHalfAngle = sqrt((1.0f * (1.0f + axis1.Dot(axis2)))); recipCosHalfAngle = (1.0f / cosHalfAngle); return Quaternion ( (Vec3::Cross(axis1, axis2) * recipCosHalfAngle), (cosHalfAngle * 0.5f) ); } const Quaternion Quaternion::Rotation(const float r, const Vec3 axis) { float angle = r * 0.5f; return Quaternion( (axis * sin(r)), cos(r) ); } const Quaternion Quaternion::RotationX(const float r) { float angle = r * 0.5f; return Quaternion(sin(angle), 0.0f, 0.0f, cos(angle)); } const Quaternion Quaternion::RotationY(const float r) { float angle = r * 0.5f; return Quaternion(0.0f, sin(angle), 0.0f, cos(angle)); } const Quaternion Quaternion::RotationZ(const float r) { float angle = r * 0.5f; return Quaternion(0.0f, 0.0f, sin(angle), cos(angle)); } Quaternion Quaternion::Normalize() { float length = sqrt(x * x + y * y + z * z + w * w); return Quaternion(x / length, y / length, z / length, w / length); } Quaternion Quaternion::Normalize(const Quaternion& other) { float length = other.Length(); return Quaternion(other.x / length, other.y / length, other.z / length, other.w / length); } float Quaternion::Dot(const Quaternion& other) const { return x * other.x + y * other.y + z * other.z + w * other.w; } float Quaternion::Dot(const Quaternion& other1, const Quaternion& other2) { return other1.x * other2.x + other1.y * other2.y + other1.z + other2.z + other1.w * other2.w; } Quaternion Quaternion::Conjugate() const { return Quaternion(-x, -y, -z, w); } const Quaternion Quaternion::Zero(0.0f, 0.0f, 0.0f, 0.0f); const Quaternion Quaternion::Identity(0.0f, 0.0f, 0.0f, 1.0f); }
#include "math/CotQuaternion.h" #include "math/CotVec3.h" #include "math/CotVec4.h" namespace Cot { Quaternion::Quaternion() : x(0.0f), y(0.0f), z(0.0f), w(1.0f) { } Quaternion::Quaternion(const float value) : x(value), y(value), z(value), w(value) { } Quaternion::Quaternion(const float xx, const float yy, const float zz, const float ww) : x(xx), y(yy), z(zz), w(ww) { } Quaternion::Quaternion(const float* array) : x(array[0]), y(array[1]), z(array[2]), w(array[3]) { } Quaternion::Quaternion(const Vec3& v, float ww) : x(v.x), y(v.y), z(v.z), w(ww) { } Quaternion::Quaternion(const Vec4& v) : x(v.x), y(v.y), z(v.z), w(v.w) { } Quaternion::Quaternion(const Quaternion& other) : x(other.x), y(other.y), z(other.z), w(other.w) { } Quaternion::Quaternion(const Quaternion&& other) : x(other.x), y(other.y), z(other.z), w(other.w) { } Quaternion::~Quaternion() { } void Quaternion::SetXYZ(const Vec3& v) { x = v.x; y = v.y; z = v.z; } Vec3 Quaternion::GetXYZ() const { return Vec3(x, y, z); } void Quaternion::SetEuler(const Vec3& euler) { Quaternion pitch(1.0f, 0.0f, 0.0f, euler.x); Quaternion yaw(0.0f, 1.0f, 1.0f, euler.y); Quaternion roll(0.0f, 0.0f, 1.0f, euler.z); (*this) = pitch * yaw * roll; } Vec3 Quaternion::GetEuler() const { return Vec3( atan2(2 * x * w - 2 * y * z, 1 - 2 * x * x - 2 * z * z), atan2(2 * y * w - 2 * x * z, 1 - 2 * y * y - 2 * z * z), asin(2 * x * y + 2 * z * w)); } float Quaternion::Length() const { return sqrt(x * x + y * y + z * z + w * w); } Vec3 Quaternion::GetAxis() const { float x = 1.0f - w * w; if (x <= 0.0f) { return Vec3::AxisX; } float x2 = x * x; Vec3 xyz = GetXYZ(); return GetXYZ() / x2; } const Quaternion Quaternion::operator+(const Quaternion& other) const { return Quaternion(x + other.x, y + other.y, z + other.z, w + other.w); } const Quaternion Quaternion::operator-(const Quaternion& other) const { return Quaternion(x - other.x, y - other.y, z - other.z, w - other.w); } const Quaternion Quaternion::operator*(const Quaternion& other) const { return Quaternion::Normalize( Quaternion ( ((x * other.x) + (x * other.w)) + ((y * other.z) - (z * other.y)), ((x * other.y) + (y * other.w)) + ((z * other.x) - (x * other.z)), ((x * other.z) + (z * other.w)) + ((x * other.y) - (y * other.x)), ((w * other.w) + (x * other.x)) + ((y * other.y) - (z * other.z)) )); } const Quaternion Quaternion::operator/(const Quaternion& other) const { COT_ASSERT(other.x <= 0.0f, "Division by 0"); COT_ASSERT(other.y <= 0.0f, "Division by 0"); COT_ASSERT(other.z <= 0.0f, "Division by 0"); COT_ASSERT(other.w <= 0.0f, "Division by 0"); return Quaternion(x / other.x, y / other.y, z / other.z, w / other.w); } const Quaternion Quaternion::operator+(const float value) const { return Quaternion(x + value, y + value, z + value, w + value); } const Quaternion Quaternion::operator-(const float value) const { return Quaternion(x - value, y - value, z - value, w - value); } const Quaternion Quaternion::operator*(const float value) const { return Quaternion(x * value, y * value, z * value, w * value); } const Quaternion Quaternion::operator/(const float value) const { COT_ASSERT(value <= 0.0f, "Division by 0"); return Quaternion(x / value, y / value, z / value, w / value); } Quaternion& Quaternion::operator+=(const Quaternion& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Quaternion& Quaternion::operator-=(const Quaternion& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } Quaternion& Quaternion::operator*=(const Quaternion& other) { (*this) = (*this) * other; return *this; } Quaternion& Quaternion::operator/=(const Quaternion& other) { COT_ASSERT(other.x <= 0.0f, "Division by 0"); COT_ASSERT(other.y <= 0.0f, "Division by 0"); COT_ASSERT(other.z <= 0.0f, "Division by 0"); COT_ASSERT(other.w <= 0.0f, "Division by 0"); x /= other.x; y /= other.y; z /= other.z; w /= other.w; return *this; } Quaternion& Quaternion::operator=(const Quaternion& other) { x = other.x; y = other.y; z = other.z; w = other.w; return *this; }
Quaternion& Quaternion::operator-=(const float value) { x -= value; y -= value; z -= value; w -= value; return *this; } Quaternion& Quaternion::operator*=(const float value) { x *= value; y *= value; z *= value; w *= value; return *this; } Quaternion& Quaternion::operator/=(const float value) { COT_ASSERT(value <= 0.0f, "Division by 0"); x /= value; y /= value; z /= value; w /= value; return *this; } Quaternion& Quaternion::operator=(const float value) { x = value; y = value; z = value; w = value; return *this; } const Quaternion Quaternion::operator-() const { return Quaternion(-x, -y, -z, -w); } bool Quaternion::operator<(const Quaternion& other) const { return (x < other.x && y < other.y && z < other.z && w < other.w); } bool Quaternion::operator<=(const Quaternion& other) const { return (x <= other.x && y <= other.y && z <= other.z && w <= other.w); } bool Quaternion::operator>(const Quaternion& other) const { return (x > other.x && y > other.y && z > other.z && w > other.w); } bool Quaternion::operator>=(const Quaternion& other) const { return (x >= other.x && y >= other.y && z >= other.z && w >= other.w); } bool Quaternion::operator==(const Quaternion& other) const { return (x == other.x && y == other.y && z == other.z && w == other.w); } bool Quaternion::operator!=(const Quaternion& other) const { return (x != other.x || y != other.y || z != other.z, w != other.w); } bool Quaternion::IsZero() const { return (x == 0.0f && y == 0.0f && z == 0.0f && w == 0.0f); } bool Quaternion::IsOne() const { return (x == 1.0f && y == 1.0f && z == 1.0f && w == 1.0f); } const Vec3 Quaternion::Rotate(const Quaternion& quaternion, const Vec3& axis) { float tempX, tempY, tempZ, tempW; tempX = (((quaternion.w * axis.x) + (quaternion.y * axis.z)) - (quaternion.z * axis.y)); tempY = (((quaternion.w * axis.y) + (quaternion.z * axis.x)) - (quaternion.x * axis.z)); tempZ = (((quaternion.w * axis.z) + (quaternion.x * axis.y)) - (quaternion.y * axis.x)); tempW = (((quaternion.x * axis.x) + (quaternion.y * axis.y)) + (quaternion.z * axis.z)); return Vec3( ((((tempW * quaternion.x) + (tempX * quaternion.w)) - (tempY * quaternion.z)) + (tempZ * quaternion.y)), ((((tempW * quaternion.y) + (tempY * quaternion.w)) - (tempZ * quaternion.x)) + (tempX * quaternion.z)), ((((tempW * quaternion.z) + (tempZ * quaternion.w)) - (tempX * quaternion.y)) + (tempY * quaternion.x)) ); } const Quaternion Quaternion::Rotation(const Vec3& axis1, const Vec3& axis2) { float cosHalfAngle, recipCosHalfAngle; cosHalfAngle = sqrt((1.0f * (1.0f + axis1.Dot(axis2)))); recipCosHalfAngle = (1.0f / cosHalfAngle); return Quaternion ( (Vec3::Cross(axis1, axis2) * recipCosHalfAngle), (cosHalfAngle * 0.5f) ); } const Quaternion Quaternion::Rotation(const float r, const Vec3 axis) { float angle = r * 0.5f; return Quaternion( (axis * sin(r)), cos(r) ); } const Quaternion Quaternion::RotationX(const float r) { float angle = r * 0.5f; return Quaternion(sin(angle), 0.0f, 0.0f, cos(angle)); } const Quaternion Quaternion::RotationY(const float r) { float angle = r * 0.5f; return Quaternion(0.0f, sin(angle), 0.0f, cos(angle)); } const Quaternion Quaternion::RotationZ(const float r) { float angle = r * 0.5f; return Quaternion(0.0f, 0.0f, sin(angle), cos(angle)); } Quaternion Quaternion::Normalize() { float length = sqrt(x * x + y * y + z * z + w * w); return Quaternion(x / length, y / length, z / length, w / length); } Quaternion Quaternion::Normalize(const Quaternion& other) { float length = other.Length(); return Quaternion(other.x / length, other.y / length, other.z / length, other.w / length); } float Quaternion::Dot(const Quaternion& other) const { return x * other.x + y * other.y + z * other.z + w * other.w; } float Quaternion::Dot(const Quaternion& other1, const Quaternion& other2) { return other1.x * other2.x + other1.y * other2.y + other1.z + other2.z + other1.w * other2.w; } Quaternion Quaternion::Conjugate() const { return Quaternion(-x, -y, -z, w); } const Quaternion Quaternion::Zero(0.0f, 0.0f, 0.0f, 0.0f); const Quaternion Quaternion::Identity(0.0f, 0.0f, 0.0f, 1.0f); }
Quaternion& Quaternion::operator+=(const float value) { x += value; y += value; z += value; w += value; return *this; }
function_block-full_function
[ { "content": "\tclass Vec4;\n", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 0, "score": 178629.8132119183 }, { "content": "\tclass Vec3;\n", "file_path": "Engine/include/math/CotQuaternion.h", "rank": 1, "score": 178621.05006660835 }, { "content": "\tclass...
C++
trunk/third_party/webrtc/modules/rtp_rtcp/test/testAPI/test_api_audio.cc
goddino/libjingle
9516bee51c73af4c3082e74b88ed1198a0eb2bb1
#include <algorithm> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/rtp_rtcp/test/testAPI/test_api.h" #include "webrtc/common_types.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp_defines.h" using namespace webrtc; #define test_rate 64000u class VerifyingAudioReceiver : public RtpData { public: virtual int32_t OnReceivedPayloadData( const uint8_t* payloadData, const uint16_t payloadSize, const webrtc::WebRtcRTPHeader* rtpHeader) { if (rtpHeader->header.payloadType == 98 || rtpHeader->header.payloadType == 99) { EXPECT_EQ(4, payloadSize); char str[5]; memcpy(str, payloadData, payloadSize); str[4] = 0; EXPECT_STRCASEEQ("test", str); return 0; } if (rtpHeader->header.payloadType == 100 || rtpHeader->header.payloadType == 101 || rtpHeader->header.payloadType == 102) { if (rtpHeader->type.Audio.channel == 1) { if (payloadData[0] == 0xff) { return 0; } } ADD_FAILURE() << "This code path should never happen."; return -1; } return 0; } }; class RTPCallback : public RtpFeedback { public: virtual int32_t OnInitializeDecoder( const int32_t id, const int8_t payloadType, const char payloadName[RTP_PAYLOAD_NAME_SIZE], const int frequency, const uint8_t channels, const uint32_t rate) { if (payloadType == 96) { EXPECT_EQ(test_rate, rate) << "The rate should be 64K for this payloadType"; } return 0; } virtual void OnPacketTimeout(const int32_t id) { } virtual void OnReceivedPacket(const int32_t id, const RtpRtcpPacketType packetType) { } virtual void OnPeriodicDeadOrAlive(const int32_t id, const RTPAliveType alive) { } virtual void OnIncomingSSRCChanged(const int32_t id, const uint32_t SSRC) { } virtual void OnIncomingCSRCChanged(const int32_t id, const uint32_t CSRC, const bool added) { } }; class AudioFeedback : public RtpAudioFeedback { virtual void OnReceivedTelephoneEvent(const int32_t id, const uint8_t event, const bool end) { static uint8_t expectedEvent = 0; if (end) { uint8_t oldEvent = expectedEvent-1; if (expectedEvent == 32) { oldEvent = 15; } EXPECT_EQ(oldEvent, event); } else { EXPECT_EQ(expectedEvent, event); expectedEvent++; } if (expectedEvent == 16) { expectedEvent = 32; } } virtual void OnPlayTelephoneEvent(const int32_t id, const uint8_t event, const uint16_t lengthMs, const uint8_t volume) { }; }; class RtpRtcpAudioTest : public ::testing::Test { protected: RtpRtcpAudioTest() : fake_clock(123456) { test_CSRC[0] = 1234; test_CSRC[2] = 2345; test_id = 123; test_ssrc = 3456; test_timestamp = 4567; test_sequence_number = 2345; } ~RtpRtcpAudioTest() {} virtual void SetUp() { audioFeedback = new AudioFeedback(); data_receiver1 = new VerifyingAudioReceiver(); data_receiver2 = new VerifyingAudioReceiver(); rtp_callback = new RTPCallback(); transport1 = new LoopBackTransport(); transport2 = new LoopBackTransport(); RtpRtcp::Configuration configuration; configuration.id = test_id; configuration.audio = true; configuration.clock = &fake_clock; configuration.incoming_data = data_receiver1; configuration.outgoing_transport = transport1; configuration.audio_messages = audioFeedback; module1 = RtpRtcp::CreateRtpRtcp(configuration); configuration.id = test_id + 1; configuration.incoming_data = data_receiver2; configuration.incoming_messages = rtp_callback; configuration.outgoing_transport = transport2; configuration.audio_messages = audioFeedback; module2 = RtpRtcp::CreateRtpRtcp(configuration); transport1->SetSendModule(module2); transport2->SetSendModule(module1); } virtual void TearDown() { delete module1; delete module2; delete transport1; delete transport2; delete audioFeedback; delete data_receiver1; delete data_receiver2; delete rtp_callback; } int test_id; RtpRtcp* module1; RtpRtcp* module2; VerifyingAudioReceiver* data_receiver1; VerifyingAudioReceiver* data_receiver2; LoopBackTransport* transport1; LoopBackTransport* transport2; AudioFeedback* audioFeedback; RTPCallback* rtp_callback; uint32_t test_ssrc; uint32_t test_timestamp; uint16_t test_sequence_number; uint32_t test_CSRC[webrtc::kRtpCsrcSize]; SimulatedClock fake_clock; }; TEST_F(RtpRtcpAudioTest, Basic) { EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module2->SetTelephoneEventForwardToDecoder(true)); EXPECT_EQ(0, module1->SetSendingStatus(true)); EXPECT_EQ(-1, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 0, -1, NULL, 0)); CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); printf("4\n"); const uint8_t test[5] = "test"; EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 0, -1, test, 4)); EXPECT_EQ(test_ssrc, module2->RemoteSSRC()); EXPECT_EQ(test_timestamp, module2->RemoteTimestamp()); } TEST_F(RtpRtcpAudioTest, RED) { CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module1->SetSendingStatus(true)); voiceCodec.pltype = 127; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "RED", 4); EXPECT_EQ(0, module1->SetSendREDPayloadType(voiceCodec.pltype)); int8_t red = 0; EXPECT_EQ(0, module1->SendREDPayloadType(red)); EXPECT_EQ(voiceCodec.pltype, red); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); RTPFragmentationHeader fragmentation; fragmentation.fragmentationVectorSize = 2; fragmentation.fragmentationLength = new uint32_t[2]; fragmentation.fragmentationLength[0] = 4; fragmentation.fragmentationLength[1] = 4; fragmentation.fragmentationOffset = new uint32_t[2]; fragmentation.fragmentationOffset[0] = 0; fragmentation.fragmentationOffset[1] = 4; fragmentation.fragmentationTimeDiff = new uint16_t[2]; fragmentation.fragmentationTimeDiff[0] = 0; fragmentation.fragmentationTimeDiff[1] = 0; fragmentation.fragmentationPlType = new uint8_t[2]; fragmentation.fragmentationPlType[0] = 96; fragmentation.fragmentationPlType[1] = 96; const uint8_t test[5] = "test"; EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 160, -1, test, 4, &fragmentation)); EXPECT_EQ(0, module1->SetSendREDPayloadType(-1)); EXPECT_EQ(-1, module1->SendREDPayloadType(red)); } TEST_F(RtpRtcpAudioTest, DTMF) { CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module1->SetSendingStatus(true)); voiceCodec.pltype = 97; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "telephone-event", 16); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); uint32_t timeStamp = 160; for (int i = 0; i < 16; i++) { EXPECT_EQ(0, module1->SendTelephoneEventOutband(i, timeStamp, 10)); } timeStamp += 160; const uint8_t test[9] = "test"; for (;timeStamp <= 250 * 160; timeStamp += 160) { EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, timeStamp, -1, test, 4)); fake_clock.AdvanceTimeMilliseconds(20); module1->Process(); } EXPECT_EQ(0, module1->SendTelephoneEventOutband(32, 9000, 10)); for (;timeStamp <= 740 * 160; timeStamp += 160) { EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, timeStamp, -1, test, 4)); fake_clock.AdvanceTimeMilliseconds(20); module1->Process(); } }
#include <algorithm> #include <vector> #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/rtp_rtcp/test/testAPI/test_api.h" #include "webrtc/common_types.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h" #include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp_defines.h" using namespace webrtc; #define test_rate 64000u class VerifyingAudioReceiver : public RtpData { public: virtual int32_t OnReceivedPayloadData( const uint8_t* payloadData, const uint16_t payloadSize, const webrtc::WebRtcRTPHeader* rtpHeader) { if (rtpHeader->header.payloadType == 98 || rtpHeader->header.payloadType == 99) { EXPECT_EQ(4, payloadSize); char str[5]; memcpy(str, payloadData, payloadSize); str[4] = 0; EXPECT_STRCASEEQ("test", str); return 0; } if (rtpHeader->header.payloadType == 100 || rtpHeader->header.payloadType == 101 || rtpHeader->header.payloadType == 102) { if (rtpHeader->type.Audio.channel == 1) { if (payloadData[0] == 0xff) { return 0; } } ADD_FAILURE() << "This code path should never happen."; return -1; } return 0; } }; class RTPCallback : public RtpFeedback { public: virtual int32_t OnInitializeDecoder( const int32_t id, const int8_t payloadType, const char payloadName[RTP_PAYLOAD_NAME_SIZE], const int frequency, const uint8_t channels, const uint32_t rate) { if (payloadType == 96) { EXPECT_EQ(test_rate, rate) << "The rate should be 64K for this payloadType"; } return 0; } virtual void OnPacketTimeout(const int32_t id) { } virtual void OnReceivedPacket(const int32_t id, const RtpRtcpPacketType packetType) { } virtual void OnPeriodicDeadOrAlive(const int32_t id, const RTPAliveType alive) { } virtual void OnIncomingSSRCChanged(const int32_t id, const uint32_t SSRC) { } virtual void OnIncomingCSRCChanged(const int32_t id, const uint32_t CSRC, const bool added) { } }; class AudioFeedback : public RtpAudioFeedback { virtual void OnReceivedTelephoneEvent(const int32_t id, const uint8_t event, const bool end) { static uint8_t expectedEvent = 0; if (end) { uint8_t oldEvent = expectedEvent-1; if (expectedEvent == 32) { oldEvent = 15; } EXPECT_EQ(oldEvent, event); } else { EXPECT_EQ(expectedEvent, event); expectedEvent++; } if (expectedEvent == 16) { expectedEvent = 32; } } virtual void OnPlayTelephoneEvent(const int32_t id, const uint8_t event, const uint16_t lengthMs, const uint8_t volume) { }; }; class RtpRtcpAudioTest : public ::testing::Test { protected: RtpRtcpAudioTest() : fake_clock(123456) { test_CSRC[0] = 1234; test_CSRC[2] = 2345; test_id = 123; test_ssrc = 3456; test_timestamp = 4567; test_sequence_number = 2345; } ~RtpRtcpAudioTest() {} virtual void SetUp() { audioFeedback = new AudioFeedback(); data_receiver1 = new VerifyingAudioReceiver(); data_receiver2 = new VerifyingAudioReceiver(); rtp_callback = new RTPCallback(); transport1 = new LoopBackTransport(); transport2 = new LoopBackTransport(); RtpRtcp::Configuration configuration; configuration.id = test_id; configuration.audio = true; configuration.clock = &fake_clock; configuration.incoming_data = data_receiver1; configuration.outgoing_transport = transport1; configuration.audio_messages = audioFeedback; module1 = RtpRtcp::CreateRtpRtcp(configuration); configuration.id = test_id + 1; configuration.incoming_data = data_receiver2; configuration.incoming_messages = rtp_callback; configuration.outgoing_transport = transport2; configuration.audio_messages = audioFeedback; module2 = RtpRtcp::CreateRtpRtcp(configuration); transport1->SetSendModule(module2); transport2->SetSendModule(module1); } virtual void TearDown() { delete module1; delete module2; delete transport1; delete transport2; delete audioFeedback; delete data_receiver1; delete data_receiver2; delete rtp_callback; } int test_id; RtpRtcp* module1; RtpRtcp* module2; VerifyingAudioReceiver* data_receiver1; VerifyingAudioReceiver* data_receiver2; LoopBackTransport* transport1; LoopBackTransport* transport2; AudioFeedback* audioFeedback; RTPCallback* rtp_callback; uint32_t test_ssrc; uint32_t test_timestamp; uint16_t test_sequence_number; uint32_t test_CSRC[webrtc::kRtpCsrcSize]; SimulatedClock fake_clock; }; TEST_F(RtpRtcpAudioTest, Basic) { EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module2->SetTelephoneEventForwardToDecoder(true)); EXPECT_EQ(0, module1->SetSendingStatus(true)); EXPECT_EQ(-1, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 0, -1, NULL, 0)); CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); printf("4\n"); const uint8_t test[5] = "test"; EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 0, -1, test, 4)); EXPECT_EQ(test_ssrc, module2->RemoteSSRC()); EXPECT_EQ(test_timestamp, module2->RemoteTimestamp()); } TEST_F(RtpRtcpAudioTest, RED) { CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module1->SetSSRC(test_ssrc
160; timeStamp += 160) { EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, timeStamp, -1, test, 4)); fake_clock.AdvanceTimeMilliseconds(20); module1->Process(); } }
)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module1->SetSendingStatus(true)); voiceCodec.pltype = 127; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "RED", 4); EXPECT_EQ(0, module1->SetSendREDPayloadType(voiceCodec.pltype)); int8_t red = 0; EXPECT_EQ(0, module1->SendREDPayloadType(red)); EXPECT_EQ(voiceCodec.pltype, red); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); RTPFragmentationHeader fragmentation; fragmentation.fragmentationVectorSize = 2; fragmentation.fragmentationLength = new uint32_t[2]; fragmentation.fragmentationLength[0] = 4; fragmentation.fragmentationLength[1] = 4; fragmentation.fragmentationOffset = new uint32_t[2]; fragmentation.fragmentationOffset[0] = 0; fragmentation.fragmentationOffset[1] = 4; fragmentation.fragmentationTimeDiff = new uint16_t[2]; fragmentation.fragmentationTimeDiff[0] = 0; fragmentation.fragmentationTimeDiff[1] = 0; fragmentation.fragmentationPlType = new uint8_t[2]; fragmentation.fragmentationPlType[0] = 96; fragmentation.fragmentationPlType[1] = 96; const uint8_t test[5] = "test"; EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, 160, -1, test, 4, &fragmentation)); EXPECT_EQ(0, module1->SetSendREDPayloadType(-1)); EXPECT_EQ(-1, module1->SendREDPayloadType(red)); } TEST_F(RtpRtcpAudioTest, DTMF) { CodecInst voiceCodec; voiceCodec.pltype = 96; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "PCMU", 5); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module1->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterSendPayload(voiceCodec)); voiceCodec.rate = test_rate; EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); EXPECT_EQ(0, module1->SetSSRC(test_ssrc)); EXPECT_EQ(0, module1->SetStartTimestamp(test_timestamp)); EXPECT_EQ(0, module1->SetSendingStatus(true)); voiceCodec.pltype = 97; voiceCodec.plfreq = 8000; memcpy(voiceCodec.plname, "telephone-event", 16); EXPECT_EQ(0, module1->RegisterSendPayload(voiceCodec)); EXPECT_EQ(0, module2->RegisterReceivePayload(voiceCodec)); uint32_t timeStamp = 160; for (int i = 0; i < 16; i++) { EXPECT_EQ(0, module1->SendTelephoneEventOutband(i, timeStamp, 10)); } timeStamp += 160; const uint8_t test[9] = "test"; for (;timeStamp <= 250 * 160; timeStamp += 160) { EXPECT_EQ(0, module1->SendOutgoingData(webrtc::kAudioFrameSpeech, 96, timeStamp, -1, test, 4)); fake_clock.AdvanceTimeMilliseconds(20); module1->Process(); } EXPECT_EQ(0, module1->SendTelephoneEventOutband(32, 9000, 10)); for (;timeStamp <= 740 *
random
[]
C++
lib/fiber/element_pair_topology.hpp
nicolas-chaulet/bempp
0f5cc72e0e542437e787db5704978456b0ad9e35
#ifndef fiber_element_pair_topology_hpp #define fiber_element_pair_topology_hpp #include "../common/common.hpp" #include "../common/armadillo_fwd.hpp" #include <cassert> #include <iostream> #include <boost/tuple/tuple_comparison.hpp> namespace Fiber { struct ElementPairTopology { ElementPairTopology() : type(Disjoint), testVertexCount(0), trialVertexCount(0), testSharedVertex0(-1), testSharedVertex1(-1), trialSharedVertex0(-1), trialSharedVertex1(-1) {} enum Type { Disjoint, SharedVertex, SharedEdge, Coincident }; Type type; unsigned char testVertexCount; unsigned char trialVertexCount; signed char testSharedVertex0; signed char testSharedVertex1; signed char trialSharedVertex0; signed char trialSharedVertex1; bool operator<(const ElementPairTopology& other) const { using boost::tuples::make_tuple; return make_tuple(type, testVertexCount, trialVertexCount, testSharedVertex0, testSharedVertex1, trialSharedVertex0, trialSharedVertex1) < make_tuple(other.type, other.testVertexCount, other.trialVertexCount, other.testSharedVertex0, other.testSharedVertex1, other.trialSharedVertex0, other.trialSharedVertex1); } bool operator==(const ElementPairTopology& other) const { return type == other.type && testVertexCount == other.testVertexCount && trialVertexCount == other.trialVertexCount && testSharedVertex0 == other.testSharedVertex0 && testSharedVertex1 == other.testSharedVertex1 && trialSharedVertex0 == other.trialSharedVertex0 && trialSharedVertex1 == other.trialSharedVertex1; } bool operator!=(const ElementPairTopology& other) const { return !operator==(other); } friend std::ostream& operator<< (std::ostream& dest, const ElementPairTopology& obj) { dest << obj.type << " " << (int)obj.testVertexCount << " " << (int)obj.trialVertexCount << " " << (int)obj.testSharedVertex0 << " " << (int)obj.testSharedVertex1 << " " << (int)obj.trialSharedVertex0 << " " << (int)obj.trialSharedVertex1; return dest; } }; inline ElementPairTopology determineElementPairTopologyIn3D( const arma::Col<int>& testElementCornerIndices, const arma::Col<int>& trialElementCornerIndices) { ElementPairTopology topology; #ifndef NDEBUG const int MIN_VERTEX_COUNT = 3; #endif const int MAX_VERTEX_COUNT = 4; topology.testVertexCount = testElementCornerIndices.n_rows; assert(MIN_VERTEX_COUNT <= topology.testVertexCount && topology.testVertexCount <= MAX_VERTEX_COUNT); topology.trialVertexCount = trialElementCornerIndices.n_rows; assert(MIN_VERTEX_COUNT <= topology.trialVertexCount && topology.trialVertexCount <= MAX_VERTEX_COUNT); int testSharedVertices[MAX_VERTEX_COUNT]; int trialSharedVertices[MAX_VERTEX_COUNT]; int hits = 0; for (int trialV = 0; trialV < topology.trialVertexCount; ++trialV) for (int testV = 0; testV < topology.testVertexCount; ++testV) if (testElementCornerIndices(testV) == trialElementCornerIndices(trialV)) { testSharedVertices[hits] = testV; trialSharedVertices[hits] = trialV; ++hits; break; } if (hits == 0) { topology.type = ElementPairTopology::Disjoint; } else if (hits == 1) { topology.type = ElementPairTopology::SharedVertex; topology.testSharedVertex0 = testSharedVertices[0]; topology.trialSharedVertex0 = trialSharedVertices[0]; } else if (hits == 2) { topology.type = ElementPairTopology::SharedEdge; topology.testSharedVertex0 = testSharedVertices[0]; topology.testSharedVertex1 = testSharedVertices[1]; topology.trialSharedVertex0 = trialSharedVertices[0]; topology.trialSharedVertex1 = trialSharedVertices[1]; } else if (hits == topology.testVertexCount && hits == topology.trialVertexCount) { for (int i = 0; i < hits; ++i) assert(testSharedVertices[i] == trialSharedVertices[i]); topology.type = ElementPairTopology::Coincident; } else throw std::runtime_error( "Standard3DIntegrationManager::" "selectTestKernelTrialQuadratureRules() :" "Invalid element configuration"); return topology; } } #endif
#ifndef fiber_element_pair_topology_hpp #define fiber_element_pair_topology_hpp #include "../common/common.hpp" #include "../common/armadillo_fwd.hpp" #include <cassert> #include <iostream> #include <boost/tuple/tuple_comparison.hpp> namespace Fiber { struct ElementPairTopology { ElementPairTopology() : type(Disjoint), testVertexCount(0), trialVertexCount(0), testSharedVertex0(-1), testSharedVertex1(-1), trialSharedVertex0(-1), trialSharedVertex1(-1) {} enum Type { Disjoint, SharedVertex, SharedEdge, Coincident }; Type type; unsigned char testVertexCount; unsigned char trialVertexCount; signed char testSharedVertex0; signed char testSharedVertex1; signed char trialSharedVertex0; signed char trialSharedVertex1; bool operator<(const ElementPairTopology& other) const { using boost::tuples::make_tuple; return make_tuple(type, testVertexCount, trialVertexCount, testSharedVertex0, testSharedVertex1, trialSharedVertex0, trialSharedVertex1) < make_tuple(other.type, other.testVertexCount, other.trialVertexCount, other.testSharedVertex0, other.testSharedVertex1, other.trialSharedVertex0, other.trialSharedVertex1); } bool operator==(const ElementPairTopology& o
+testV) if (testElementCornerIndices(testV) == trialElementCornerIndices(trialV)) { testSharedVertices[hits] = testV; trialSharedVertices[hits] = trialV; ++hits; break; } if (hits == 0) { topology.type = ElementPairTopology::Disjoint; } else if (hits == 1) { topology.type = ElementPairTopology::SharedVertex; topology.testSharedVertex0 = testSharedVertices[0]; topology.trialSharedVertex0 = trialSharedVertices[0]; } else if (hits == 2) { topology.type = ElementPairTopology::SharedEdge; topology.testSharedVertex0 = testSharedVertices[0]; topology.testSharedVertex1 = testSharedVertices[1]; topology.trialSharedVertex0 = trialSharedVertices[0]; topology.trialSharedVertex1 = trialSharedVertices[1]; } else if (hits == topology.testVertexCount && hits == topology.trialVertexCount) { for (int i = 0; i < hits; ++i) assert(testSharedVertices[i] == trialSharedVertices[i]); topology.type = ElementPairTopology::Coincident; } else throw std::runtime_error( "Standard3DIntegrationManager::" "selectTestKernelTrialQuadratureRules() :" "Invalid element configuration"); return topology; } } #endif
ther) const { return type == other.type && testVertexCount == other.testVertexCount && trialVertexCount == other.trialVertexCount && testSharedVertex0 == other.testSharedVertex0 && testSharedVertex1 == other.testSharedVertex1 && trialSharedVertex0 == other.trialSharedVertex0 && trialSharedVertex1 == other.trialSharedVertex1; } bool operator!=(const ElementPairTopology& other) const { return !operator==(other); } friend std::ostream& operator<< (std::ostream& dest, const ElementPairTopology& obj) { dest << obj.type << " " << (int)obj.testVertexCount << " " << (int)obj.trialVertexCount << " " << (int)obj.testSharedVertex0 << " " << (int)obj.testSharedVertex1 << " " << (int)obj.trialSharedVertex0 << " " << (int)obj.trialSharedVertex1; return dest; } }; inline ElementPairTopology determineElementPairTopologyIn3D( const arma::Col<int>& testElementCornerIndices, const arma::Col<int>& trialElementCornerIndices) { ElementPairTopology topology; #ifndef NDEBUG const int MIN_VERTEX_COUNT = 3; #endif const int MAX_VERTEX_COUNT = 4; topology.testVertexCount = testElementCornerIndices.n_rows; assert(MIN_VERTEX_COUNT <= topology.testVertexCount && topology.testVertexCount <= MAX_VERTEX_COUNT); topology.trialVertexCount = trialElementCornerIndices.n_rows; assert(MIN_VERTEX_COUNT <= topology.trialVertexCount && topology.trialVertexCount <= MAX_VERTEX_COUNT); int testSharedVertices[MAX_VERTEX_COUNT]; int trialSharedVertices[MAX_VERTEX_COUNT]; int hits = 0; for (int trialV = 0; trialV < topology.trialVertexCount; ++trialV) for (int testV = 0; testV < topology.testVertexCount; +
random
[ { "content": "enum CallVariant\n\n{\n\n TEST_TRIAL = 0,\n\n TRIAL_TEST = 1\n\n};\n\n\n\ntypedef int LocalDofIndex;\n\nconst LocalDofIndex ALL_DOFS = -1;\n\n\n\n}\n\n\n\n#endif\n", "file_path": "lib/fiber/types.hpp", "rank": 0, "score": 187458.7934374725 }, { "content": "enum Geometrica...
C++
src/automaton/core/testnet/testnet.cc
sept-en/automaton
b7448dfe578cf52df37ec7c86536d1e51017c548
#include "automaton/core/testnet/testnet.h" #include <set> #include "automaton/core/io/io.h" #include "automaton/core/node/node.h" namespace automaton { namespace core { namespace testnet { static const uint32_t STARTING_PORT = 12300; std::unordered_map<std::string, std::shared_ptr<testnet>> testnet::testnets; bool testnet::create_testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id, network_protocol_type ntype, uint32_t number_nodes, std::unordered_map<uint32_t, std::vector<uint32_t> > peer_list) { auto it = testnets.find(id); if (it != testnets.end()) { LOG(ERROR) << "Testnet with id " << id << " already exists!"; return false; } auto net = std::unique_ptr<testnet>(new testnet(node_type, id, smart_protocol_id, ntype, number_nodes)); bool initialised = net->init(); if (!initialised) { LOG(ERROR) << "Testnet " << id << " initialization failed!"; return false; } net->connect(peer_list); testnets[id] = std::move(net); return true; } void testnet::destroy_testnet(const std::string& id) { auto it = testnets.find(id); if (it != testnets.end()) { testnets.erase(it); } } std::shared_ptr<testnet> testnet::get_testnet(const std::string& id) { auto it = testnets.find(id); if (it != testnets.end()) { return it->second; } return nullptr; } std::vector<std::string> testnet::list_testnets() { std::vector<std::string> result; for (auto it = testnets.begin(); it != testnets.end(); it++) { result.push_back(it->first); } return result; } testnet::~testnet() { for (uint32_t i = 0; i < node_ids_list.size(); ++i) { automaton::core::node::node::remove_node(node_ids_list[i]); } } void testnet::connect(const std::unordered_map<uint32_t, std::vector<uint32_t> >& peers_list) const { std::string id = network_id + "_"; std::string address = ""; uint32_t port = 0; if (network_type == network_protocol_type::localhost) { address = "tcp://127.0.0.1:"; port = STARTING_PORT; } else { address = "sim://1:20:10000:"; } for (auto it = peers_list.begin(); it != peers_list.end(); it++) { std::stringstream nid; nid << id << it->first; std::shared_ptr<automaton::core::node::node> n = automaton::core::node::node::get_node(nid.str()); if (n == nullptr) { LOG(ERROR) << "No such node: " << nid.str(); continue; } const std::vector<uint32_t>& peers = it->second; for (uint32_t i = 0; i < peers.size(); ++i) { std::stringstream ss; ss << address << (port + peers[i]); uint32_t pid = n->add_peer(ss.str()); n->connect(pid); } } } std::vector<std::string> testnet::list_nodes() { return node_ids_list; } testnet::testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id, network_protocol_type ntype, uint32_t number_nodes): node_type(node_type), network_id(id), protocol_id(smart_protocol_id), network_type(ntype), number_nodes(number_nodes), node_ids_list(number_nodes, "") {} bool testnet::init() { std::string address = ""; uint32_t port = 0; if (network_type == network_protocol_type::localhost) { address = "tcp://127.0.0.1:"; port = STARTING_PORT; } else { address = "sim://100:10000:"; } for (uint32_t i = 1; i <= number_nodes; ++i) { std::string node_id = network_id + "_" + std::to_string(i); bool res = automaton::core::node::node::launch_node(node_type, node_id, protocol_id, address + std::to_string(port + i)); if (!res) { return false; } node_ids_list[i-1] = node_id; } return true; } std::unordered_map<uint32_t, std::vector<uint32_t> > create_connections_vector(uint32_t n, uint32_t p) { std::unordered_map<uint32_t, std::vector<uint32_t> > result; if (p >= ((n + 1) / 2)) { LOG(ERROR) << "'p' is too big! Setting 'p' to max valid number of peers for 'n' = " << n << " : " << ((n + 1) / 2 - 1); return result; } for (uint32_t i = 1; i <= n; ++i) { std::vector<uint32_t> peers; for (uint32_t j = 0; j < p; ++j) { peers.push_back((i + j) % n + 1); } result[i] = std::move(peers); } return result; } std::unordered_map<uint32_t, std::vector<uint32_t> > create_rnd_connections_vector(uint32_t n, uint32_t p) { std::unordered_map<uint32_t, std::vector<uint32_t> > result; uint32_t k; if (p >= ((n + 1) / 2)) { LOG(ERROR) << "'p' is too big! Setting 'p' to max valid number of peers for 'n' = " << n << " : " << ((n + 1) / 2 - 1); return result; } for (uint32_t i = 1; i <= n; ++i) { std::set<uint32_t> peers; while (peers.size() < p) { k = std::rand() % n + 1; if (k == i) {continue;} peers.insert(k); } result[i] = std::vector<uint32_t>(peers.begin(), peers.end()); } return result; } } } }
#include "automaton/core/testnet/testnet.h" #include <set> #include "automaton/core/io/io.h" #include "automaton/core/node/node.h" namespace automaton { namespace core { namespace testnet { static const uint32_t STARTING_PORT = 12300; std::unordered_map<std::string, std::shared_ptr<testnet>> testnet::testnets; bool testnet::create_testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id, network_protocol_type ntype, uint32_t number_nodes, std::unordered_map<uint32_t, std::vector<uint32_t> > peer_list) { auto it = testnets.find(id); if (it != testnets.end()) { LOG(ERROR) << "Testnet with id " << id << " already exists!"; return false; } auto net = std::unique_ptr<testnet>(new testnet(node_type, id, smart_protocol_id, ntype, number_nodes)); bool initialised = net->init(); if (!initialised) { LOG(ERROR) << "Testnet " << id << " initialization failed!"; return false; } net->connect(peer_list); testnets
= ""; uint32_t port = 0; if (network_type == network_protocol_type::localhost) { address = "tcp://127.0.0.1:"; port = STARTING_PORT; } else { address = "sim://100:10000:"; } for (uint32_t i = 1; i <= number_nodes; ++i) { std::string node_id = network_id + "_" + std::to_string(i); bool res = automaton::core::node::node::launch_node(node_type, node_id, protocol_id, address + std::to_string(port + i)); if (!res) { return false; } node_ids_list[i-1] = node_id; } return true; } std::unordered_map<uint32_t, std::vector<uint32_t> > create_connections_vector(uint32_t n, uint32_t p) { std::unordered_map<uint32_t, std::vector<uint32_t> > result; if (p >= ((n + 1) / 2)) { LOG(ERROR) << "'p' is too big! Setting 'p' to max valid number of peers for 'n' = " << n << " : " << ((n + 1) / 2 - 1); return result; } for (uint32_t i = 1; i <= n; ++i) { std::vector<uint32_t> peers; for (uint32_t j = 0; j < p; ++j) { peers.push_back((i + j) % n + 1); } result[i] = std::move(peers); } return result; } std::unordered_map<uint32_t, std::vector<uint32_t> > create_rnd_connections_vector(uint32_t n, uint32_t p) { std::unordered_map<uint32_t, std::vector<uint32_t> > result; uint32_t k; if (p >= ((n + 1) / 2)) { LOG(ERROR) << "'p' is too big! Setting 'p' to max valid number of peers for 'n' = " << n << " : " << ((n + 1) / 2 - 1); return result; } for (uint32_t i = 1; i <= n; ++i) { std::set<uint32_t> peers; while (peers.size() < p) { k = std::rand() % n + 1; if (k == i) {continue;} peers.insert(k); } result[i] = std::vector<uint32_t>(peers.begin(), peers.end()); } return result; } } } }
[id] = std::move(net); return true; } void testnet::destroy_testnet(const std::string& id) { auto it = testnets.find(id); if (it != testnets.end()) { testnets.erase(it); } } std::shared_ptr<testnet> testnet::get_testnet(const std::string& id) { auto it = testnets.find(id); if (it != testnets.end()) { return it->second; } return nullptr; } std::vector<std::string> testnet::list_testnets() { std::vector<std::string> result; for (auto it = testnets.begin(); it != testnets.end(); it++) { result.push_back(it->first); } return result; } testnet::~testnet() { for (uint32_t i = 0; i < node_ids_list.size(); ++i) { automaton::core::node::node::remove_node(node_ids_list[i]); } } void testnet::connect(const std::unordered_map<uint32_t, std::vector<uint32_t> >& peers_list) const { std::string id = network_id + "_"; std::string address = ""; uint32_t port = 0; if (network_type == network_protocol_type::localhost) { address = "tcp://127.0.0.1:"; port = STARTING_PORT; } else { address = "sim://1:20:10000:"; } for (auto it = peers_list.begin(); it != peers_list.end(); it++) { std::stringstream nid; nid << id << it->first; std::shared_ptr<automaton::core::node::node> n = automaton::core::node::node::get_node(nid.str()); if (n == nullptr) { LOG(ERROR) << "No such node: " << nid.str(); continue; } const std::vector<uint32_t>& peers = it->second; for (uint32_t i = 0; i < peers.size(); ++i) { std::stringstream ss; ss << address << (port + peers[i]); uint32_t pid = n->add_peer(ss.str()); n->connect(pid); } } } std::vector<std::string> testnet::list_nodes() { return node_ids_list; } testnet::testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id, network_protocol_type ntype, uint32_t number_nodes): node_type(node_type), network_id(id), protocol_id(smart_protocol_id), network_type(ntype), number_nodes(number_nodes), node_ids_list(number_nodes, "") {} bool testnet::init() { std::string address
random
[ { "content": "class testnet {\n\n public:\n\n enum network_protocol_type {\n\n localhost = 1,\n\n simulation = 2\n\n };\n\n\n\n ~testnet();\n\n\n\n static bool create_testnet(const std::string& node_type, const std::string& id, const std::string& smart_protocol_id,\n\n network_protocol_type ntype...
C++
include/SctpSocket.hpp
GaborTimko/lsctp
cdc89010b1afcc2ed9cd811a61256749938a54dd
#ifndef LSSOCKET_HPP #define LSSOCKET_HPP #include <vector> #include <cstring> #include <cerrno> #include <type_traits> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/sctp.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include "Lua/Lua.hpp" namespace Sctp { namespace Socket { template<int IPVersion> class Base { static_assert(IPVersion == 4 or IPVersion == 6, ""); public: using SockAddrType = std::conditional_t<IPVersion == 4, sockaddr_in, sockaddr_in6>; using AddressArray = std::vector<SockAddrType>; static constexpr int IPv = IPVersion; protected: int fd; bool haveBoundAddresses; AddressArray boundAddresses; public: Base() noexcept; Base(int sock) noexcept; ~Base(); public: auto create() noexcept -> bool; auto bind(Lua::State*) noexcept -> int; auto close(Lua::State*) noexcept -> int; auto setNonBlocking(Lua::State*) noexcept -> int; protected: auto loadAddresses(Lua::State*, AddressArray&) noexcept -> int; private: auto bindFirst(Lua::State*) noexcept -> int; auto pushIPAddress(Lua::State*, AddressArray&, const char* ip, uint16_t port, int idx) noexcept -> int; auto checkIPConversionResult(Lua::State*, const char* ip, int result) noexcept -> int; }; template<int IPVersion> Base<IPVersion>::Base() noexcept : haveBoundAddresses(false) {} template<int IPVersion> auto Base<IPVersion>::create() noexcept -> bool { fd = ::socket(IPVersion == 4 ? AF_INET : AF_INET6, SOCK_STREAM, IPPROTO_SCTP); if(fd == -1) { return false; } int True = 1; setsockopt(fd, IPPROTO_SCTP, SO_REUSEADDR, &True, sizeof(int)); return true; } template<int IPVersion> Base<IPVersion>::Base(int sock) noexcept : fd(sock), haveBoundAddresses(false) {} template<int IPVersion> Base<IPVersion>::~Base() { ::close(fd); } template<int IPVersion> auto Base<IPVersion>::setNonBlocking(Lua::State* L) noexcept -> int { int flags = fcntl(fd, F_GETFL); if(flags < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "fcntl(get): %s", std::strerror(errno)); return 2; } flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK); if(flags < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "fcntl(set): %s", std::strerror(errno)); return 2; } Lua::PushBoolean(L, true); return 1; } template<int IPVersion> auto Base<IPVersion>::bind(Lua::State* L) noexcept -> int { int loadAddrResult = loadAddresses(L, boundAddresses); std::size_t addrCount = boundAddresses.size(); if(loadAddrResult > 0) { return loadAddrResult; } int retVal = bindFirst(L); if(retVal > 0) { return retVal; } if(addrCount > 1) { if(::sctp_bindx(fd, reinterpret_cast<sockaddr*>(boundAddresses.data() + 1), addrCount - 1, SCTP_BINDX_ADD_ADDR) < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "sctp_bindx: %s", std::strerror(errno)); return 2; } } haveBoundAddresses = true; Lua::PushBoolean(L, true); return 1; } template<int IPVersion> auto Base<IPVersion>::loadAddresses(Lua::State* L, AddressArray& addrs) noexcept -> int { uint16_t port = htons(Lua::ToInteger(L, 2)); int stackSize = Lua::GetTop(L); std::size_t addrCount = stackSize - 2; if(addrCount < 1) { Lua::PushBoolean(L, false); Lua::PushString(L, "No addresses were given"); return 2; } addrs.clear(); addrs.resize(addrCount); std::memset(addrs.data(), 0, sizeof(SockAddrType) * addrCount); for(int i = 3; i <= stackSize; i++) { int idx = i - 3; auto addrI = Lua::ToString(L, i); int pushResult = pushIPAddress(L, addrs, addrI, port, idx); if(pushResult > 0) { return pushResult; } } return 0; } template<int IPVersion> auto Base<IPVersion>::bindFirst(Lua::State* L) noexcept -> int { int bindRes = ::bind(fd, reinterpret_cast<sockaddr*>(boundAddresses.data()), sizeof(SockAddrType)); if(bindRes < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "bind: %s", std::strerror(errno)); return 2; } return bindRes; } template<> inline auto Base<4>::pushIPAddress(Lua::State* L, AddressArray& addrs, const char* ip, uint16_t port, int idx) noexcept -> int { addrs[idx].sin_family = AF_INET; addrs[idx].sin_port = port; int conversion = ::inet_pton(AF_INET, ip, &addrs[idx].sin_addr); return checkIPConversionResult(L, ip, conversion); } template<> inline auto Base<6>::pushIPAddress(Lua::State* L, AddressArray& addrs, const char* ip, uint16_t port, int idx) noexcept -> int { addrs[idx].sin6_family = AF_INET6; addrs[idx].sin6_port = port; int conversion = ::inet_pton(AF_INET6, ip, &addrs[idx].sin6_addr); return checkIPConversionResult(L, ip, conversion); } template<int IPVersion> auto Base<IPVersion>::checkIPConversionResult(Lua::State* L, const char* ip, int result) noexcept -> int { if(result == 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "inet_pton: invalid IP: %s", ip); return 2; } else if (result < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "inet_pton: %s", std::strerror(errno)); return 2; } return 0; } template<int IPVersion> auto Base<IPVersion>::close(Lua::State* L) noexcept -> int { if(fd > -1 and ::close(fd) < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "close: %s", std::strerror(errno)); fd = -1; return 2; } fd = -1; boundAddresses.clear(); Lua::PushBoolean(L, true); return 1; } } template<class Type> struct IsSctpSocket : public std::integral_constant<bool, std::is_same<Type, Socket::Base<4>>::value or std::is_same<Type, Socket::Base<6>>::value or std::is_base_of<Socket::Base<4>, Type>::value or std::is_base_of<Socket::Base<6>, Type>::value> { }; } #endif
#ifndef LSSOCKET_HPP #define LSSOCKET_HPP #include <vector> #include <cstring> #include <cerrno> #include <type_traits> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/sctp.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include "Lua/Lua.hpp" namespace Sctp { namespace Socket { template<int IPVersion> class Base { static_assert(IPVersion == 4 or IPVersion == 6, ""); public: using SockAddrType = std::conditional_t<IPVersion == 4, sockaddr_in, sockaddr_in6>; using AddressArray = std::vector<SockAddrType>; static constexpr int IPv = IPVersion; protected: int fd; bool haveBoundAddresses; AddressArray boundAddresses; public: Base() noexcept; Base(int sock) noexcept; ~Base(); public: auto create() noexcept -> bool; auto bind(Lua::State*) noexcept -> int; auto close(Lua::State*) noexcept -> int; auto setNonBlocking(Lua::State*) noexcept -> int; protected: auto loadAddresses(Lua::State*, AddressArray&) noexcept -> int; private: auto bindFirst(Lua::State*) noexcept -> int; auto pushIPAddress(Lua::State*, AddressArray&, const char* ip, uint16_t port, int idx) noexcept -> int; auto checkIPConversionResult(Lua::State*, const char* ip, int result) noexcept -> int; }; template<int IPVersion> Base<IPVersion>::Base() noexcept : haveBoundAddresses(false) {} template<int IPVersion> auto Base<IPVersion>::create() noexcept -> bool { fd = ::socket(IPVersion == 4 ? AF_INET : AF_INET6, SOCK_STREAM, IPPROTO_SCTP); if(fd == -1) { return false; } int True = 1; setsockopt(fd, IPPROTO_SCTP, SO_REUSEADDR, &True, sizeof(int)); return true; } template<int IPVersion> Base<IPVersion>::Base(int sock) noexcept : fd(sock), haveBoundAddresses(false) {} template<int IPVersion> Base<IPVersion>::~Base() { ::close(fd); } template<int IPVersion> auto Base<IPVersion>::setNonBlocking(Lua::State* L) noexcept -> int { int flags = fcntl(fd, F_GETFL); if(flags < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "fcntl(get): %s", std::strerror(errno)); return 2; } flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK); if(flags < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "fcntl(set): %s", std::strerror(errno)); return 2; } Lua::PushBoolean(L, true); return 1; } template<int IPVersion> auto Base<IPVersion>::bind(Lua::State* L) noexcept -> int { int loadAddrResult = loadAddresses(L, boundAddresses); std::size_t addrCount = boundAddresses.size(); if(loadAddrResult > 0) { return loadAddrResult; } int retVal = bindFirst(L); if(retVal > 0) { return retVal; } if(addrCount > 1) { if(::sctp_bindx(fd, reinterpret_cast<sockaddr*>(boundAddresses.data() + 1), addrCount - 1, SCTP_BINDX_ADD_ADDR) < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "sctp_bindx: %s", std::strerror(errno)); return 2; } } haveBoundAddresses = true; Lua::PushBoolean(L, true); return 1; } template<int IPVersion> auto Base<IPVersion>::loadAddresses(Lua::State* L, AddressArray& addrs) noexcept -> int { uint16_t port = htons(Lua::ToInteger(L, 2)); int stackSize = Lua::GetTop(L); std::size_t addrCount = stackSize - 2; if(addrCount < 1) { Lua::PushBoolean(L, false); Lua::PushString(L, "No addresses were given"); return 2; } addrs.clear(); addrs.resize(addrCount); std::memset(addrs.data(), 0, sizeof(SockAddrType) * addrCount); for(int i = 3; i <= stackSize; i++) { int idx = i - 3; auto addrI = Lua::ToString(L, i); int pushResult = pushIPAddress(L, addrs, addrI, port, idx); if(pushResult > 0) { return pushResult; } } return 0; } template<int IPVersion> auto Base<IPVersion>::bindFirst(Lua::State* L) noexcept -> int { int bindRes = ::bind(fd, reinterpret_cast<sockaddr*>(boundAddresses.data()), sizeof(SockAddrType)); if(bindRes < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "bind: %s", std::strerror(errno)); return 2; } return bindRes; } template<>
template<> inline auto Base<6>::pushIPAddress(Lua::State* L, AddressArray& addrs, const char* ip, uint16_t port, int idx) noexcept -> int { addrs[idx].sin6_family = AF_INET6; addrs[idx].sin6_port = port; int conversion = ::inet_pton(AF_INET6, ip, &addrs[idx].sin6_addr); return checkIPConversionResult(L, ip, conversion); } template<int IPVersion> auto Base<IPVersion>::checkIPConversionResult(Lua::State* L, const char* ip, int result) noexcept -> int { if(result == 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "inet_pton: invalid IP: %s", ip); return 2; } else if (result < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "inet_pton: %s", std::strerror(errno)); return 2; } return 0; } template<int IPVersion> auto Base<IPVersion>::close(Lua::State* L) noexcept -> int { if(fd > -1 and ::close(fd) < 0) { Lua::PushBoolean(L, false); Lua::PushFString(L, "close: %s", std::strerror(errno)); fd = -1; return 2; } fd = -1; boundAddresses.clear(); Lua::PushBoolean(L, true); return 1; } } template<class Type> struct IsSctpSocket : public std::integral_constant<bool, std::is_same<Type, Socket::Base<4>>::value or std::is_same<Type, Socket::Base<6>>::value or std::is_base_of<Socket::Base<4>, Type>::value or std::is_base_of<Socket::Base<6>, Type>::value> { }; } #endif
inline auto Base<4>::pushIPAddress(Lua::State* L, AddressArray& addrs, const char* ip, uint16_t port, int idx) noexcept -> int { addrs[idx].sin_family = AF_INET; addrs[idx].sin_port = port; int conversion = ::inet_pton(AF_INET, ip, &addrs[idx].sin_addr); return checkIPConversionResult(L, ip, conversion); }
function_block-full_function
[ { "content": "class Server final : public Base<IPVersion> {\n\npublic:\n\n static constexpr int DefaultBackLogSize = 1000;\n\n static const char* MetaTableName;\n\npublic:\n\n Server() : Base<IPVersion>() {}\n\npublic:\n\n auto listen(Lua::State*) noexcept -> int;\n\n auto accept(Lua::State*) noexcept -> i...
C++
SM_RayIntersect.cpp
xzrunner/sm
e31351c4fcd4470efa4dbec5bb6ee02c21ae42f8
#include "SM_RayIntersect.h" namespace sm { bool ray_ray_intersect(const Ray& ray0, const Ray& ray1, vec3* cross) { auto& da = ray0.dir; auto& db = ray1.dir; auto dc = ray1.origin - ray0.origin; auto cross_ab = da.Cross(db); if (fabs(dc.Dot(cross_ab)) > SM_LARGE_EPSILON) { return false; } float d = cross_ab.LengthSquared(); if (d < std::numeric_limits<float>::epsilon()) { return false; } auto s = dc.Cross(db).Dot(cross_ab) / d; auto t = dc.Cross(da).Dot(cross_ab) / d; if (s >= 0 && t >= 0) { *cross = ray0.origin + ray0.dir * s; return true; } return false; } bool line_line_intersect(const sm::vec3& p1, const sm::vec3& p2, const sm::vec3& p3, const sm::vec3& p4, sm::vec3* pa, sm::vec3* pb, float* mua, float* mub) { sm::vec3 p13,p43,p21; float d1343,d4321,d1321,d4343,d2121; float numer,denom; float EPS = std::numeric_limits<float>::epsilon(); p13.x = p1.x - p3.x; p13.y = p1.y - p3.y; p13.z = p1.z - p3.z; p43.x = p4.x - p3.x; p43.y = p4.y - p3.y; p43.z = p4.z - p3.z; if (fabs(p43.x) < EPS && fabs(p43.y) < EPS && fabs(p43.z) < EPS) return false; p21.x = p2.x - p1.x; p21.y = p2.y - p1.y; p21.z = p2.z - p1.z; if (fabs(p21.x) < EPS && fabs(p21.y) < EPS && fabs(p21.z) < EPS) return false; d1343 = p13.x * p43.x + p13.y * p43.y + p13.z * p43.z; d4321 = p43.x * p21.x + p43.y * p21.y + p43.z * p21.z; d1321 = p13.x * p21.x + p13.y * p21.y + p13.z * p21.z; d4343 = p43.x * p43.x + p43.y * p43.y + p43.z * p43.z; d2121 = p21.x * p21.x + p21.y * p21.y + p21.z * p21.z; denom = d2121 * d4343 - d4321 * d4321; if (fabs(denom) < EPS) return false; numer = d1343 * d4321 - d1321 * d4343; *mua = numer / denom; *mub = (d1343 + d4321 * (*mua)) / d4343; pa->x = p1.x + *mua * p21.x; pa->y = p1.y + *mua * p21.y; pa->z = p1.z + *mua * p21.z; pb->x = p3.x + *mub * p43.x; pb->y = p3.y + *mub * p43.y; pb->z = p3.z + *mub * p43.z; return true; } #define NUMDIM 3 #define RIGHT 0 #define LEFT 1 #define MIDDLE 2 bool ray_aabb_intersect(const cube& aabb, const Ray& ray, vec3* _cross) { vec3 cross; char quadrant[3]; float candidate_plane[3]; bool inside = true; for (int i = 0; i < 3; ++i) { if (ray.origin[i] < aabb.Min()[i]) { quadrant[i] = LEFT; candidate_plane[i] = aabb.Min()[i]; inside = false; } else if (ray.origin[i] > aabb.Max()[i]) { quadrant[i] = RIGHT; candidate_plane[i] = aabb.Max()[i]; inside = false; } else { quadrant[i] = MIDDLE; } } if (inside) { cross = ray.origin; return true; } float max_t[3]; for (int i = 0; i < 3; ++i) { if (quadrant[i] != MIDDLE && ray.dir[i] != 0) { max_t[i] = (candidate_plane[i]-ray.origin[i])/ray.dir[i]; } else { max_t[i] = -1; } } int which_plane = 0; for (int i = 1; i < 3; ++i) { if (max_t[which_plane] < max_t[i]) { which_plane = i; } } if (max_t[which_plane] < 0) { return false; } for (int i = 0; i < 3; ++i) { if (which_plane != i) { cross[i] = ray.origin[i] + max_t[which_plane] * ray.dir[i]; if (cross[i] < aabb.Min()[i] || cross[i] > aabb.Max()[i]) { return false; } } else { cross[i] = candidate_plane[i]; } } if (_cross) { *_cross = cross; } return true; } bool ray_obb_intersect(const cube& aabb, const vec3& pos, const Quaternion& angle, const vec3& scale, const Ray& ray, vec3* cross) { mat4 rot_mat(-angle); vec3 start = rot_mat * (ray.origin - pos); vec3 dir = rot_mat * ray.dir; Ray ray_fix(start, dir); auto aabb_scaled = aabb; aabb_scaled.Scale(scale); return ray_aabb_intersect(aabb_scaled, ray_fix, cross); } bool ray_plane_intersect(const Ray& ray, const Plane& plane, vec3* cross) { float d = ray.dir.Dot(plane.normal); if (d < -std::numeric_limits<float>::epsilon()) { float dist = -(ray.origin.Dot(plane.normal) + plane.dist) / d; *cross = ray.origin + ray.dir * dist; return true; } return false; } bool ray_plane_intersect_both_faces(const Ray& ray, const Plane& plane, vec3* cross) { float d = ray.dir.Dot(plane.normal); if (d < -std::numeric_limits<float>::epsilon() || d > std::numeric_limits<float>::epsilon()) { float dist = -(ray.origin.Dot(plane.normal) + plane.dist) / d; *cross = ray.origin + ray.dir * dist; return true; } return false; } bool ray_triangle_intersect(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross) { auto _v0 = mat * v0; auto _v1 = mat * v1; auto _v2 = mat * v2; auto e1 = _v1 - _v0; auto e2 = _v2 - _v0; auto p = ray.dir.Cross(e2);; auto a = e1.Dot(p); auto epsilon = std::numeric_limits<float>::epsilon(); if (a < epsilon) { return false; } float f = 1.0f / a; auto s = ray.origin - _v0; cross->x = f * s.Dot(p); if (cross->x < 0.0f) { return false; } if (cross->x > 1.0f) { return false; } auto q = s.Cross(e1); cross->y = f * ray.dir.Dot(q); if (cross->y < 0.0f) { return false; } if (cross->y + cross->x > 1.0f) { return false; } cross->z = f * e2.Dot(q); return cross->z >= 0.0f; } bool ray_triangle_intersect_both_faces(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross) { auto _v0 = mat * v0; auto _v1 = mat * v1; auto _v2 = mat * v2; auto e1 = _v1 - _v0; auto e2 = _v2 - _v0; auto p = ray.dir.Cross(e2);; auto a = e1.Dot(p); float f = 1.0f / a; auto s = ray.origin - _v0; cross->x = f * s.Dot(p); if (cross->x < 0.0f) { return false; } if (cross->x > 1.0f) { return false; } auto q = s.Cross(e1); cross->y = f * ray.dir.Dot(q); if (cross->y < 0.0f) { return false; } if (cross->y + cross->x > 1.0f) { return false; } cross->z = f * e2.Dot(q); return cross->z >= 0.0f; } bool ray_polygon_intersect(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross) { for (size_t i = 1; i < polygon_n - 1; ++i) { if (ray_triangle_intersect(mat, polygon[0], polygon[i], polygon[i + 1], ray, cross)) { return true; } } return false; } bool ray_polygon_intersect_both_faces(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross) { for (size_t i = 1; i < polygon_n - 1; ++i) { if (ray_triangle_intersect_both_faces(mat, polygon[0], polygon[i], polygon[i + 1], ray, cross)) { return true; } } return false; } }
#include "SM_RayIntersect.h" namespace sm { bool ray_ray_intersect(const Ray& ray0, const Ray& ray1, vec3* cross) { auto& da = ray0.dir; auto& db = ray1.dir; auto dc = ray1.origin - ray0.origin; auto cross_ab = da.Cross(db); if (fabs(dc.Dot(cross_ab)) > SM_LARGE_EPSILON) { return false; } float d = cross_ab.LengthSquared(); if (d < std::numeric_limits<float>::epsilon()) { return false; } auto s = dc.Cross(db).Dot(cross_ab) / d; auto t = dc.Cross(da).Dot(cross_ab) / d; if (s >= 0 && t >= 0) { *cross = ray0.origin + ray0.dir * s; return true; } return false; } bool line_line_intersect(const sm::vec3& p1, const sm::vec3& p2, const sm::vec3& p3, const sm::vec3& p4, sm::vec3* pa, sm::vec3* pb, float* mua, float* mub) { sm::vec3 p13,p43,p21; float d1343,d4321,d1321,d4343,d2121; float numer,denom; float EPS = std::numeric_limits<float>::epsilon(); p13.x = p1.x - p3.x; p13.y = p1.y - p3.y; p13.z = p1.z - p3.z; p43.x = p4.x - p3.x; p43.y = p4.y - p3.y; p43.z = p4.z - p3.z; if (fabs(p43.x) < EPS && fabs(p43.y) < EPS && fabs(p43.z) < EPS) return false; p21.x = p2.x - p1.x; p21.y = p2.y - p1.y; p21.z = p2.z - p1.z; if (fabs(p21.x) < EPS && fabs(p21.y) < EPS && fabs(p21.z) < EPS) return false; d1343 = p13.x * p43.x + p13.y * p43.y + p13.z * p43.z; d4321 = p43.x * p21.x + p43.y * p21.y + p43.z * p21.z; d1321 = p13.x * p21.x + p13.y * p21.y + p13.z * p21.z; d4343 = p43.x * p43.x + p43.y * p43.y + p43.z * p43.z; d2121 = p21.x * p21.x + p21.y * p21.y + p21.z * p21.z; denom = d2121 * d4343 - d4321 * d4321; if (fabs(denom) < EPS) return false; numer = d1343 * d4321 - d1321 * d4343; *mua = numer / denom; *mub = (d1343 + d4321 * (*mua)) / d4343; pa->x = p1.x + *mua * p21.x; pa->y = p1.y + *mua * p21.y; pa->z = p1.z + *mua * p21.z; pb->x = p3.x + *mub * p43.x; pb->y = p3.y + *mub * p43.y; pb->z = p3.z + *mub * p43.z; return true; } #define NUMDIM 3 #define RIGHT 0 #define LEFT 1 #define MIDDLE 2 bool ray_aabb_intersect(const cube& aabb, const Ray& ray, vec3* _cross) { vec3 cross; char quadrant[3]; float candidate_plane[3]; bool inside = true; for (int i = 0; i < 3; ++i) { if (ray.origin[i] < aabb.Min()[i]) { quadrant[i] = LEFT; candidate_plane[i] = aabb.Min()[i]; inside = false; } else if (ray.origin[i] > aabb.Max()[i]) { quadrant[i] = RIGHT; candidate_plane[i] = aabb.Max()[i]; inside = false; } else { quadrant[i] = MIDDLE; } } if (inside) { cross = ray.origin; return true; } float max_t[3]; for (int i = 0; i < 3; ++i) { if (quadrant[i] != MIDDLE && ray.dir[i] != 0) { max_t[i] = (candidate_plane[i]-ray.origin[i])/ray.dir[i]; } else { max_t[i] = -1; } } int which_plane = 0; for (int i = 1; i < 3; ++i) { if (max_t[which_plane] < max_t[i]) { which_plane = i; } } if (max_t[which_plane] < 0) { return false; } for (int i = 0; i < 3; ++i) { if (which_plane != i) { cross[i] = ray.origin[i] + max_t[which_plane] * ray.dir[i]; if (cross[i] < aabb.Min()[i] || cross[i] > aabb.Max()[i]) { return false; } } else { cross[i] = candidate_plane[i]; } } if (_cross) { *_cross = cross; } return true; } bool ray_obb_intersect(const cube& aabb, const vec3& pos, const Quaternion& angle, const vec3& scale, const Ray& ray, vec3* cross) { mat4 rot_mat(-angle); vec3 start = rot_mat * (ray.origin - pos); vec3 dir = rot_mat * ray.dir; Ray ray_fix(start, dir); auto aabb_scaled = aabb; aabb_scaled.Scale(scale); return ray_aabb_intersect(aabb_scaled, ray_fix, cross); } bool ray_plane_intersect(const Ray& ray, const Plane& plane, vec3* cross) { float d = ray.dir.Dot(plane.normal); if (d < -std::numeric_limits<float>::epsilon()) { float dist = -(ray.origin.Dot(plane.normal) + plane.dist) / d; *cross = ray.origin + ray.dir * dist; return true; } return false; } bool ray_plane_intersect_both_faces(const Ray& ray, const Plane& plane, vec3* cross) { float d = ray.dir.Dot(plane.normal); if (d < -std::numeric_limits<float>::epsilon() || d > std::numeric_limits<float>::epsilon()) { float dist = -(ray.origin.Dot(plane.normal) + plane.dist) / d; *cross = ray.origin + ray.dir * dist; return true; } return false; } bool ray_triangle_intersect(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross) { auto _v0 = mat * v0; auto _v1 = mat * v1; auto _v2 = mat * v2; auto e1 = _v1 - _v0; auto e2 = _v2 - _v0; auto p = ray.dir.Cross(e2);; auto a = e1.Dot(p); auto epsilon = std::numeric_limits<float>::epsilon(); if (a < epsilon) { return false; } float f = 1.0f / a; auto s = ray.origin - _v0; cross->x = f * s.Dot(p); if (cross->x < 0.0f) { return false; } if (cross->x > 1.0f) { return false; }
bool ray_triangle_intersect_both_faces(const mat4& mat, const vec3& v0, const vec3& v1, const vec3& v2, const Ray& ray, vec3* cross) { auto _v0 = mat * v0; auto _v1 = mat * v1; auto _v2 = mat * v2; auto e1 = _v1 - _v0; auto e2 = _v2 - _v0; auto p = ray.dir.Cross(e2);; auto a = e1.Dot(p); float f = 1.0f / a; auto s = ray.origin - _v0; cross->x = f * s.Dot(p); if (cross->x < 0.0f) { return false; } if (cross->x > 1.0f) { return false; } auto q = s.Cross(e1); cross->y = f * ray.dir.Dot(q); if (cross->y < 0.0f) { return false; } if (cross->y + cross->x > 1.0f) { return false; } cross->z = f * e2.Dot(q); return cross->z >= 0.0f; } bool ray_polygon_intersect(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross) { for (size_t i = 1; i < polygon_n - 1; ++i) { if (ray_triangle_intersect(mat, polygon[0], polygon[i], polygon[i + 1], ray, cross)) { return true; } } return false; } bool ray_polygon_intersect_both_faces(const mat4& mat, const vec3* polygon, size_t polygon_n, const Ray& ray, vec3* cross) { for (size_t i = 1; i < polygon_n - 1; ++i) { if (ray_triangle_intersect_both_faces(mat, polygon[0], polygon[i], polygon[i + 1], ray, cross)) { return true; } } return false; } }
auto q = s.Cross(e1); cross->y = f * ray.dir.Dot(q); if (cross->y < 0.0f) { return false; } if (cross->y + cross->x > 1.0f) { return false; } cross->z = f * e2.Dot(q); return cross->z >= 0.0f; }
function_block-function_prefix_line
[ { "content": "struct sm_vec3* sm_vec3_vector(struct sm_vec3* v, const struct sm_vec3* p1, const struct sm_vec3* p2)\n\n{\n\n\t*(vec3*)v = (*(const vec3*)p1) - (*(const vec3*)p2);\n\n\treturn v;\n\n}\n\n\n\nextern \"C\"\n", "file_path": "sm_c_vector.cpp", "rank": 0, "score": 127451.4694807237 }, ...
C++
Source/VoxelWorld/World/Chunk/ChunkLoader.cpp
AirGuanZ/VoxelWorld
8defdee9e2b8fb20607d33ba0f3a316b95273693
#include <algorithm> #include <cassert> #include <Utility\HelperFunctions.h> #include <World\Land\V0\LandGenerator_V0.h> #include <World\Land\V1\LandGenerator_V1.h> #include <World\Land\V2\LandGenerator_V2.h> #include <World\Land\V3\LandGenerator_V3.h> #include "ChunkLoader.h" #include "ChunkManager.h" #include "ChunkModelBuilder.h" ChunkLoader::ChunkLoader(size_t ckPoolSize) : ckPool_(ckPoolSize), landGen_(std::make_unique<LandGenerator_V0::LandGenerator>(4792539)) { } ChunkLoader::~ChunkLoader(void) { Destroy(); } void ChunkLoader::Initialize(int threadNum) { assert(threads_.empty()); if(threadNum <= 0) threadNum = (std::max)(4u, std::thread::hardware_concurrency()) - 2; running_ = true; while(threadNum-- > 0) threads_.emplace_back(&ChunkLoader::TaskThreadEntry, this); } void ChunkLoader::Destroy(void) { running_ = false; for(std::thread &th : threads_) { if(th.joinable()) th.join(); } threads_.clear(); loaderTasks_.ForEach([](ChunkLoaderTask *t) { Helper::SafeDeleteObjects(t); }); loaderTasks_.Clear(); ckPool_.Destroy(); } void ChunkLoader::AddTask(ChunkLoaderTask *task) { assert(task != nullptr); std::lock_guard<std::mutex> lk(taskQueueMutex_); loaderTasks_.PushFront(task->GetPosition(), task); } void ChunkLoader::AddMsg(ChunkLoaderMessage *msg) { assert(msg != nullptr); std::lock_guard<std::mutex> lk(msgQueueMutex_); loaderMsgs_.push(msg); } ChunkLoaderMessage *ChunkLoader::FetchMsg(void) { std::lock_guard<std::mutex> lk(msgQueueMutex_); if(loaderMsgs_.empty()) return nullptr; ChunkLoaderMessage *rt = loaderMsgs_.front(); loaderMsgs_.pop(); return rt; } std::queue<ChunkLoaderMessage*> ChunkLoader::FetchAllMsgs(void) { std::lock_guard<std::mutex> lk(msgQueueMutex_); return std::move(loaderMsgs_); } void ChunkLoader::TaskThreadEntry(void) { while(running_) { ChunkLoaderTask *task = nullptr; { std::lock_guard<std::mutex> lk(taskQueueMutex_); if(loaderTasks_.Size()) { task = loaderTasks_.Back(); loaderTasks_.PopBack(); } } if(task) { task->Run(this); Helper::SafeDeleteObjects(task); } else std::this_thread::sleep_for(std::chrono::milliseconds(2)); } } ChunkLoaderTask::ChunkLoaderTask(Chunk *ck) : ck_(ck) { assert(ck != nullptr); } void ChunkLoaderTask::Run(ChunkLoader *loader) { assert(loader != nullptr); std::vector<IntVector3> lightUpdates; loader->LoadChunkData(ck_); ChunkLoaderMessage *msg = new ChunkLoaderMessage; msg->type = ChunkLoaderMessage::ChunkLoaded; msg->ckLoaded = ck_; ck_ = nullptr; loader->AddMsg(msg); } ChunkLoaderTask::~ChunkLoaderTask(void) { Helper::SafeDeleteObjects(ck_); } namespace { inline bool OutOfBound(int x, int y, int z) { return (x | y | z | (3 * CHUNK_SECTION_SIZE - 1 - x) | (3 * CHUNK_SECTION_SIZE - 1 - z) | (CHUNK_MAX_HEIGHT - 1 - y)) < 0; } inline BlockLight GetLight(Chunk *(&cks)[3][3], int x, int y, int z) { if(OutOfBound(x, y, z)) return LIGHT_ALL_MAX; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetBlockLight(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE); } inline int GetHeight(Chunk *(&cks)[3][3], int x, int z) { if(OutOfBound(x, 0, z)) return 0; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetHeight(x % CHUNK_SECTION_SIZE, z % CHUNK_SECTION_SIZE); } inline BlockType GetType(Chunk *(&cks)[3][3], int x, int y, int z) { if(OutOfBound(x, y, z)) return BlockType::Air; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetBlockType(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE); } inline void SetLight(Chunk *(&cks)[3][3], int x, int y, int z, BlockLight light) { if(OutOfBound(x, y, z)) return; cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->SetBlockLight(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE, light); } void LightProg(Chunk *(&cks)[3][3]) { BlockInfoManager &infoMgr = BlockInfoManager::GetInstance(); std::deque<IntVector3> progQueue; auto DirectionalUpdate = [&](BlockLight cenLight, int ax, int ay, int az) -> void { BlockLight nX = GetLight(cks, ax, ay, az); BlockLight newNX = BlockLightMax(nX, BlockLightMinus( cenLight, infoMgr.GetBlockInfo(GetType(cks, ax, ay, az)).lightDec)); if(newNX != nX) { SetLight(cks, ax, ay, az, newNX); if(!OutOfBound(ax, ay, az)) progQueue.push_back({ ax, ay, az }); } }; auto TryAsSource = [&](int x, int y, int z) { if(!OutOfBound(x, y, z) && GetLight(cks, x, y, z) != LIGHT_ALL_MIN) { progQueue.push_back({ x, y, z }); while(progQueue.size()) { auto [x, y, z] = progQueue.front(); progQueue.pop_front(); BlockLight cenLight = GetLight(cks, x, y, z); DirectionalUpdate(cenLight, x - 1, y, z); DirectionalUpdate(cenLight, x + 1, y, z); DirectionalUpdate(cenLight, x, y - 1, z); DirectionalUpdate(cenLight, x, y + 1, z); DirectionalUpdate(cenLight, x, y, z - 1); DirectionalUpdate(cenLight, x, y, z + 1); } } }; for(int x = 0; x < 3 * CHUNK_SECTION_SIZE; ++x) { for(int z = 0; z < 3 * CHUNK_SECTION_SIZE; ++z) { int H = GetHeight(cks, x, z); for(int y = 0; y <= H; ++y) { if(infoMgr.GetBlockInfo(GetType(cks, x, y, z)).lightDec < LIGHT_COMPONENT_MAX) { TryAsSource(x - 1, y, z); TryAsSource(x + 1, y, z); TryAsSource(x, y - 1, z); TryAsSource(x, y + 1, z); TryAsSource(x, y, z - 1); TryAsSource(x, y, z + 1); } } } } } } void ChunkLoader::LoadChunkData(Chunk *ck) { IntVectorXZ ckPos = ck->GetPosition(); Chunk *neis = new Chunk[8] { { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z } }, { ck->GetChunkManager(), { ckPos.x, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x, ckPos.z + 1 } }, { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z + 1 } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z + 1 } }, }; for(int i = 0; i != 8; ++i) { Chunk &dst = neis[i]; if(!ckPool_.GetChunk(dst)) { landGen_->GenerateLand(&dst); Chunk *addedCk = new Chunk(dst.GetChunkManager(), dst.GetPosition()); CopyChunkData(*addedCk, dst); ckPool_.AddChunk(addedCk); } } if(!ckPool_.GetChunk(*ck)) { landGen_->GenerateLand(ck); Chunk *addedCk = new Chunk(ck->GetChunkManager(), ck->GetPosition()); CopyChunkData(*addedCk, *ck); ckPool_.AddChunk(addedCk); } Chunk *cks[3][3] = { { neis + 4, neis + 0, neis + 5 }, { neis + 2, ck, neis + 3 }, { neis + 6, neis + 1, neis + 7 } }; LightProg(cks); for(int section = 0; section != CHUNK_SECTION_NUM; ++section) ck->SetModels(section, BackgroundChunkModelBuilder().Build(cks, section)); delete[] neis; } void ChunkLoader::TryAddLoadingTask(ChunkManager *ckMgr, int x, int z) { assert(ckMgr != nullptr); std::lock_guard<std::mutex> lk(taskQueueMutex_); ChunkLoaderTask *oldTask = nullptr; if(!loaderTasks_.Exists({ x, z })) { loaderTasks_.PushFront( IntVectorXZ{ x, z }, new ChunkLoaderTask(new Chunk(ckMgr, { x, z }))); } }
#include <algorithm> #include <cassert> #include <Utility\HelperFunctions.h> #include <World\Land\V0\LandGenerator_V0.h> #include <World\Land\V1\LandGenerator_V1.h> #include <World\Land\V2\LandGenerator_V2.h> #include <World\Land\V3\LandGenerator_V3.h> #include "ChunkLoader.h" #include "ChunkManager.h" #include "ChunkModelBuilder.h" ChunkLoader::ChunkLoader(size_t ckPoolSize) : ckPool_(ckPoolSize), landGen_(std::make_unique<LandGenerator_V0::LandGenerator>(4792539)) { } ChunkLoader::~ChunkLoader(void) { Destroy(); } void ChunkLoader::Initialize(int threadNum) { assert(threads_.empty()); if(threadNum <= 0) threadNum = (std::max)(4u, std::thread::hardware_concurrency()) - 2; running_ = true; while(threadNum-- > 0) threads_.emplace_back(&ChunkLoader::TaskThreadEntry, this); } void ChunkLoader::Destroy(void) { running_ = false; for(std::thread &th : threads_) { if(th.joinable()) th.join(); } threads_.clear(); loaderTasks_.ForEach([](ChunkLoaderTask *t) { Helper::SafeDeleteObjects(t); }); loaderTasks_.Clear(); ckPool_.Destroy(); } void ChunkLoader::AddTask(ChunkLoaderTask *task) { assert(task != nullptr); std::lock_guard<std::mutex> lk(taskQueueMutex_); loaderTasks_.PushFront(task->GetPosition(), task); } void ChunkLoader::AddMsg(ChunkLoaderMessage *msg) { assert(msg != nullptr); std::lock_guard<std::mutex> lk(msgQueueMutex_); loaderMsgs_.push(msg); } ChunkLoaderMessage *ChunkLoader::FetchMsg(void) { std::lock_guard<std::mutex> lk(msgQueueMutex_); if(loaderMsgs_.empty()) return nullptr; ChunkLoaderMessage *rt = loaderMsgs_.front(); loaderMsgs_.pop(); return rt; } std::queue<ChunkLoaderMessage*> ChunkLoader::FetchAllMsgs(void) { std::lock_guard<std::mutex> lk(msgQueueMutex_); return std::move(loaderMsgs_); } void ChunkLoade
{ if(infoMgr.GetBlockInfo(GetType(cks, x, y, z)).lightDec < LIGHT_COMPONENT_MAX) { TryAsSource(x - 1, y, z); TryAsSource(x + 1, y, z); TryAsSource(x, y - 1, z); TryAsSource(x, y + 1, z); TryAsSource(x, y, z - 1); TryAsSource(x, y, z + 1); } } } } } } void ChunkLoader::LoadChunkData(Chunk *ck) { IntVectorXZ ckPos = ck->GetPosition(); Chunk *neis = new Chunk[8] { { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z } }, { ck->GetChunkManager(), { ckPos.x, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x, ckPos.z + 1 } }, { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x - 1, ckPos.z + 1 } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z - 1 } }, { ck->GetChunkManager(), { ckPos.x + 1, ckPos.z + 1 } }, }; for(int i = 0; i != 8; ++i) { Chunk &dst = neis[i]; if(!ckPool_.GetChunk(dst)) { landGen_->GenerateLand(&dst); Chunk *addedCk = new Chunk(dst.GetChunkManager(), dst.GetPosition()); CopyChunkData(*addedCk, dst); ckPool_.AddChunk(addedCk); } } if(!ckPool_.GetChunk(*ck)) { landGen_->GenerateLand(ck); Chunk *addedCk = new Chunk(ck->GetChunkManager(), ck->GetPosition()); CopyChunkData(*addedCk, *ck); ckPool_.AddChunk(addedCk); } Chunk *cks[3][3] = { { neis + 4, neis + 0, neis + 5 }, { neis + 2, ck, neis + 3 }, { neis + 6, neis + 1, neis + 7 } }; LightProg(cks); for(int section = 0; section != CHUNK_SECTION_NUM; ++section) ck->SetModels(section, BackgroundChunkModelBuilder().Build(cks, section)); delete[] neis; } void ChunkLoader::TryAddLoadingTask(ChunkManager *ckMgr, int x, int z) { assert(ckMgr != nullptr); std::lock_guard<std::mutex> lk(taskQueueMutex_); ChunkLoaderTask *oldTask = nullptr; if(!loaderTasks_.Exists({ x, z })) { loaderTasks_.PushFront( IntVectorXZ{ x, z }, new ChunkLoaderTask(new Chunk(ckMgr, { x, z }))); } }
r::TaskThreadEntry(void) { while(running_) { ChunkLoaderTask *task = nullptr; { std::lock_guard<std::mutex> lk(taskQueueMutex_); if(loaderTasks_.Size()) { task = loaderTasks_.Back(); loaderTasks_.PopBack(); } } if(task) { task->Run(this); Helper::SafeDeleteObjects(task); } else std::this_thread::sleep_for(std::chrono::milliseconds(2)); } } ChunkLoaderTask::ChunkLoaderTask(Chunk *ck) : ck_(ck) { assert(ck != nullptr); } void ChunkLoaderTask::Run(ChunkLoader *loader) { assert(loader != nullptr); std::vector<IntVector3> lightUpdates; loader->LoadChunkData(ck_); ChunkLoaderMessage *msg = new ChunkLoaderMessage; msg->type = ChunkLoaderMessage::ChunkLoaded; msg->ckLoaded = ck_; ck_ = nullptr; loader->AddMsg(msg); } ChunkLoaderTask::~ChunkLoaderTask(void) { Helper::SafeDeleteObjects(ck_); } namespace { inline bool OutOfBound(int x, int y, int z) { return (x | y | z | (3 * CHUNK_SECTION_SIZE - 1 - x) | (3 * CHUNK_SECTION_SIZE - 1 - z) | (CHUNK_MAX_HEIGHT - 1 - y)) < 0; } inline BlockLight GetLight(Chunk *(&cks)[3][3], int x, int y, int z) { if(OutOfBound(x, y, z)) return LIGHT_ALL_MAX; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetBlockLight(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE); } inline int GetHeight(Chunk *(&cks)[3][3], int x, int z) { if(OutOfBound(x, 0, z)) return 0; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetHeight(x % CHUNK_SECTION_SIZE, z % CHUNK_SECTION_SIZE); } inline BlockType GetType(Chunk *(&cks)[3][3], int x, int y, int z) { if(OutOfBound(x, y, z)) return BlockType::Air; return cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->GetBlockType(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE); } inline void SetLight(Chunk *(&cks)[3][3], int x, int y, int z, BlockLight light) { if(OutOfBound(x, y, z)) return; cks[x / CHUNK_SECTION_SIZE][z / CHUNK_SECTION_SIZE] ->SetBlockLight(x % CHUNK_SECTION_SIZE, y, z % CHUNK_SECTION_SIZE, light); } void LightProg(Chunk *(&cks)[3][3]) { BlockInfoManager &infoMgr = BlockInfoManager::GetInstance(); std::deque<IntVector3> progQueue; auto DirectionalUpdate = [&](BlockLight cenLight, int ax, int ay, int az) -> void { BlockLight nX = GetLight(cks, ax, ay, az); BlockLight newNX = BlockLightMax(nX, BlockLightMinus( cenLight, infoMgr.GetBlockInfo(GetType(cks, ax, ay, az)).lightDec)); if(newNX != nX) { SetLight(cks, ax, ay, az, newNX); if(!OutOfBound(ax, ay, az)) progQueue.push_back({ ax, ay, az }); } }; auto TryAsSource = [&](int x, int y, int z) { if(!OutOfBound(x, y, z) && GetLight(cks, x, y, z) != LIGHT_ALL_MIN) { progQueue.push_back({ x, y, z }); while(progQueue.size()) { auto [x, y, z] = progQueue.front(); progQueue.pop_front(); BlockLight cenLight = GetLight(cks, x, y, z); DirectionalUpdate(cenLight, x - 1, y, z); DirectionalUpdate(cenLight, x + 1, y, z); DirectionalUpdate(cenLight, x, y - 1, z); DirectionalUpdate(cenLight, x, y + 1, z); DirectionalUpdate(cenLight, x, y, z - 1); DirectionalUpdate(cenLight, x, y, z + 1); } } }; for(int x = 0; x < 3 * CHUNK_SECTION_SIZE; ++x) { for(int z = 0; z < 3 * CHUNK_SECTION_SIZE; ++z) { int H = GetHeight(cks, x, z); for(int y = 0; y <= H; ++y)
random
[ { "content": "class BasicBufferSetter<true> : public BasicBufferView\n\n{\n\npublic:\n\n bool SetData(const void *data, int byteSize)\n\n {\n\n assert(data && byteSize > 0);\n\n\n\n D3D11_MAPPED_SUBRESOURCE rsc;\n\n HRESULT hr = Window::GetInstance().GetD3DDeviceContext()\n\n ...
C++
src/classical/aig.hpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
#ifndef AIG_HPP #define AIG_HPP #include <iostream> #include <map> #include <vector> #include <boost/dynamic_bitset.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/property_map/property_map.hpp> #include <core/properties.hpp> #include <core/utils/graph_utils.hpp> #include <classical/traits.hpp> namespace cirkit { namespace detail { using traits_t = boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS>; } struct aig_function { detail::traits_t::vertex_descriptor node; bool complemented; inline aig_function operator!() const { return {node, !complemented}; } inline bool operator==( const aig_function& other ) const { return node == other.node && complemented == other.complemented; } inline bool operator!=( const aig_function& other ) const { return !( this->operator==(other) ); } inline bool operator<( const aig_function& other ) const { return node < other.node || ( node == other.node && complemented < other.complemented ); } inline aig_function operator^( bool value ) const { return {node, complemented != value }; } }; namespace detail { using node_pair = std::pair<traits_t::vertex_descriptor, traits_t::vertex_descriptor>; } struct aig_graph_info { std::string model_name; detail::traits_t::vertex_descriptor constant; bool constant_used = false; bool enable_strashing = true; bool enable_local_optimization = true; std::map<detail::traits_t::vertex_descriptor, std::string> node_names; std::vector<std::pair<aig_function, std::string> > outputs; std::vector<detail::traits_t::vertex_descriptor> inputs; std::vector<aig_function> cos; std::vector<detail::traits_t::vertex_descriptor> cis; std::map<std::pair<aig_function, aig_function>, aig_function> strash; std::map<aig_function, aig_function> latch; boost::dynamic_bitset<> unateness; std::vector<detail::node_pair> input_symmetries; std::vector<std::vector<detail::traits_t::vertex_descriptor>> trans_words; }; namespace detail { using vertex_properties_t = boost::property<boost::vertex_name_t, unsigned, boost::property<boost::vertex_annotation_t, std::map<std::string, std::string>>>; using edge_properties_t = boost::property<boost::edge_complement_t, bool>; using graph_properties_t = boost::property<boost::graph_name_t, aig_graph_info>; } using aig_graph = digraph_t<detail::vertex_properties_t, detail::edge_properties_t, detail::graph_properties_t>; using aig_node = vertex_t<aig_graph>; using aig_edge = edge_t<aig_graph>; void aig_initialize( aig_graph& aig, const std::string& model_name = std::string() ); aig_function aig_get_constant( aig_graph& aig, bool value ); bool aig_is_constant_used( const aig_graph& aig ); aig_function aig_create_pi( aig_graph& aig, const std::string& name ); void aig_create_po( aig_graph& aig, const aig_function& f, const std::string& name ); void aig_remove_po( aig_graph& aig ); aig_function aig_create_ci( aig_graph& aig, const std::string& name ); void aig_create_co( aig_graph& aig, const aig_function& f ); aig_function aig_create_and( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_nand( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_or( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_nor( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_xor( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_ite( aig_graph& aig, const aig_function& cond, const aig_function& t, const aig_function& e ); aig_function aig_create_implies( aig_graph& aig, const aig_function& a, const aig_function& b ); aig_function aig_create_maj( aig_graph& aig, const aig_function& a, const aig_function& b, const aig_function& c ); aig_function aig_create_lat( aig_graph& aig, const aig_function& in, const std::string& name ); aig_function aig_create_nary_and( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_nand( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_or( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_nor( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_xor( aig_graph& aig, const std::vector< aig_function >& v ); void write_dot( const aig_graph& aig, std::ostream& os, const properties::ptr& settings = properties::ptr() ); void write_dot( const aig_graph& aig, const std::string& filename, const properties::ptr& settings = properties::ptr() ); unsigned aig_to_literal( const aig_graph& aig, const aig_function& f ); unsigned aig_to_literal( const aig_graph& aig, const aig_node& node ); aig_function aig_to_function( const aig_graph& aig, const aig_edge& edge ); std::ostream& operator<<( std::ostream& os, const aig_function &f ); template<> struct circuit_traits<aig_graph> { using node = aig_node; using edge = aig_edge; using node_color_map = std::map<aig_node, boost::default_color_type>; }; } #endif
#ifndef AIG_HPP #define AIG_HPP #include <iostream> #include <map> #include <vector> #include <boost/dynamic_bitset.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/property_map/property_map.hpp> #include <core/properties.hpp> #include <core/utils/graph_utils.hpp> #include <classical/traits.hpp> namespace cirkit { namespace detail { using traits_t = boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS>; } struct aig_function { detail::traits_t::vertex_descriptor node; bool complemented; inline aig_function operator!() const { return {node, !complemented}; } inline bool operator==( const aig_function& other ) const { return node == other.node && complemented == other.complemented; } inline bool operator!=( const aig_function& other ) const { return !( this->operator==(other) ); } inline bool operator<( const aig_function& other ) const { return node < other.node || ( node == other.node && complemented < other.complemented ); } inline aig_function operator^( bool value ) const { return {node, complemented != value }; } }; namespace detail { using node_pair = std::pair<traits_t::vertex_descriptor, traits_t::vertex_descriptor>; } struct aig_graph_info { std::string model_name; detail::traits_t::vertex_descriptor constant; bool constant_used = false; bool enable_strashing = true; bool enable_local_optimization = true; std::map<detail::traits_t::vertex_descriptor, std::string> node_names; std::vector<std::pair<aig_function, std::string> > outputs; std::vector<detail::traits_t::vertex_descriptor> inputs; std::vector<aig_function> cos; std::vector<detail::traits_t::vertex_descriptor> cis; std::map<std::pair<aig_function, aig_function>, aig_function> strash; std::map<aig_function, aig_function> latch; boost::dynamic_bitset<> unateness; std::vector<detail::node_pair> input_symmetries; std::vector<std::vector<detail::traits_t::vertex_descriptor>> trans_words; }; namespace detail { using vertex_properties_t = boost::property<boost::vertex_name_t, unsigned, boost::property<boost::vertex_annotation_t, std::map<std::string, std::string>>>; using edge_properties_t = boost::property<boost::edge_complement_t, bool>; using graph_properties_t = boost::property<boost::graph_name_t, aig_graph_info>; } using aig_graph = digraph_t<detail::vertex_properties_t,
onst std::string& name ); void aig_remove_po( aig_graph& aig ); aig_function aig_create_ci( aig_graph& aig, const std::string& name ); void aig_create_co( aig_graph& aig, const aig_function& f ); aig_function aig_create_and( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_nand( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_or( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_nor( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_xor( aig_graph& aig, const aig_function& left, const aig_function& right ); aig_function aig_create_ite( aig_graph& aig, const aig_function& cond, const aig_function& t, const aig_function& e ); aig_function aig_create_implies( aig_graph& aig, const aig_function& a, const aig_function& b ); aig_function aig_create_maj( aig_graph& aig, const aig_function& a, const aig_function& b, const aig_function& c ); aig_function aig_create_lat( aig_graph& aig, const aig_function& in, const std::string& name ); aig_function aig_create_nary_and( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_nand( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_or( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_nor( aig_graph& aig, const std::vector< aig_function >& v ); aig_function aig_create_nary_xor( aig_graph& aig, const std::vector< aig_function >& v ); void write_dot( const aig_graph& aig, std::ostream& os, const properties::ptr& settings = properties::ptr() ); void write_dot( const aig_graph& aig, const std::string& filename, const properties::ptr& settings = properties::ptr() ); unsigned aig_to_literal( const aig_graph& aig, const aig_function& f ); unsigned aig_to_literal( const aig_graph& aig, const aig_node& node ); aig_function aig_to_function( const aig_graph& aig, const aig_edge& edge ); std::ostream& operator<<( std::ostream& os, const aig_function &f ); template<> struct circuit_traits<aig_graph> { using node = aig_node; using edge = aig_edge; using node_color_map = std::map<aig_node, boost::default_color_type>; }; } #endif
detail::edge_properties_t, detail::graph_properties_t>; using aig_node = vertex_t<aig_graph>; using aig_edge = edge_t<aig_graph>; void aig_initialize( aig_graph& aig, const std::string& model_name = std::string() ); aig_function aig_get_constant( aig_graph& aig, bool value ); bool aig_is_constant_used( const aig_graph& aig ); aig_function aig_create_pi( aig_graph& aig, const std::string& name ); void aig_create_po( aig_graph& aig, const aig_function& f, c
random
[ { "content": "struct store_info<std::vector<aig_node>>\n\n{\n\n static constexpr const char* key = \"gates\";\n\n static constexpr const char* option = \"gate\";\n\n static constexpr const char* mnemonic = \"\";\n\n static constexpr const char* name = \"gate\";\n\n static constexpr c...
C++
src/orbital/software/self.cpp
Klern28/orbital
3e0a669e550e1d9a36eef24c9e77f40782bc5381
#include "self.h" #include <orbital/crypto_ps4.h> #include <zlib.h> #include <stdexcept> constexpr U32 SELF_MAGIC = '\x4F\x15\x3D\x1D'; enum SelfEndian { LITTLE = 1, }; enum ProgramAuthID : U64 { PAID_KERNEL = UINT64_C(0x3C00000000000001), }; enum ProgramType : U64 { PTYPE_FAKE = 0x1, PTYPE_NPDRM_EXEC = 0x4, PTYPE_NPDRM_DYNLIB = 0x5, PTYPE_SYSTEM_EXEC = 0x8, PTYPE_SYSTEM_DYNLIB = 0x9, PTYPE_HOST_KERNEL = 0xC, PTYPE_SECURE_MODULE = 0xE, PTYPE_SECURE_KERNEL = 0xF, }; static Key getKey(const SelfInfo& info) { const auto& crypto = ps4Crypto(); switch (info.paid) { case PAID_KERNEL: if (info.version_app >= 0x00000900'00000000) { return crypto.get("self.80010002.900"); } else if (info.version_app >= 0x00000850'00000000) { return crypto.get("self.80010002.8xx"); } else if (info.version_app >= 0x00000800'00000000) { return crypto.get("self.80010002.800"); } else if (info.version_app >= 0x00000750'00000000) { return crypto.get("self.80010002.7xx"); } else if (info.version_app >= 0x00000700'00000000) { return crypto.get("self.80010002.700"); } else if (info.version_app >= 0x00000650'00000000) { return crypto.get("self.80010002.6xx"); } else if (info.version_app >= 0x00000600'00000000) { return crypto.get("self.80010002.600"); } else if (info.version_app >= 0x00000550'00000000) { return crypto.get("self.80010002.550"); } else if (info.version_app >= 0x00000500'00000000) { return crypto.get("self.80010002.500"); } else if (info.version_app >= 0x00000450'00000000) { return crypto.get("self.80010002.450"); } else if (info.version_app >= 0x00000406'00000000) { return crypto.get("self.80010002.406"); } else if (info.version_app >= 0x00000400'00000000) { return crypto.get("self.80010002.400"); } else if (info.version_app >= 0x00000350'00000000) { return crypto.get("self.80010002.350"); } else if (info.version_app >= 0x00000150'00000000) { return crypto.get("self.80010002.1xx"); } else { throw std::runtime_error("Unsupported"); } break; default: throw std::runtime_error("Unsupported"); } } SelfParser::SelfParser(Stream& s) : CfParser(s) { const auto& crypto = ps4Crypto(); s.seek(0, StreamSeek::Set); header = s.read_t<SelfHeader>(); assert(header.magic == SELF_MAGIC); assert(header.version == 0); assert(header.mode == 1); assert(header.endian == SelfEndian::LITTLE); assert(header.attr == 0x12); segments.resize(header.segment_count); s.read(sizeof(SelfSegment) * segments.size(), segments.data()); const auto elf_offset = s.tell(); elf = std::make_unique<ElfParser>(s); const auto ehdr = elf->get_ehdr(); const auto info_offset = elf_offset + ehdr.e_phoff + ehdr.e_phentsize * ehdr.e_phnum; s.seek(align(info_offset, 16), StreamSeek::Set); info = s.read_t<SelfInfo>(); assert(s.tell() == header.header_size, "NPDRM Control Blocks are unsupported"); Buffer buffer(header.meta_size); s.read(buffer.size(), buffer.data()); crypto.decrypt(buffer.data(), buffer.size(), getKey(info)); auto* meta_entries = reinterpret_cast<const SelfMeta*>(&buffer[0]); metas.clear(); for (size_t i = 0; i < header.segment_count; i++) { metas.push_back(meta_entries[i]); } } SelfParser::~SelfParser() { } Elf_Ehdr<> SelfParser::get_ehdr() { return elf->get_ehdr(); } Elf_Phdr<> SelfParser::get_phdr(size_t i) { return elf->get_phdr(i); } Buffer SelfParser::get_pdata(size_t i) { const auto segment_idx = find_segment(i); if (segments[segment_idx].has_blocks()) { return get_segment_blocked(i); } else { return get_segment_nonblocked(i); } } U64 SelfParser::find_segment(U64 phdr_idx) const { for (size_t i = 0; i < header.segment_count; i++) { if (segments[i].id() == phdr_idx) { return i; } } throw std::out_of_range("SELF segment not found"); } Buffer SelfParser::get_segment_blocked(U64 index) { throw std::runtime_error("Unimplemented"); } Buffer SelfParser::get_segment_nonblocked(U64 index) { const auto segment_idx = find_segment(index); const auto& segment = segments[segment_idx]; const auto& meta = metas[segment_idx]; s.seek(segment.offset, StreamSeek::Set); Buffer buffer = s.read_b(segment.mem_size); if (segment.is_encrypted()) { decrypt(buffer, meta); } if (segment.is_compressed()) { const auto size = segment.mem_size; unsigned long cur_zsize = (size & ~0xF) - (size & 0xF); unsigned long cur_usize = segment.file_size; Buffer result(segment.file_size); int zerr = uncompress(result.data(), &cur_usize, buffer.data(), cur_zsize); assert(zerr == 0); buffer = std::move(result); } return buffer; }
#include "self.h" #include <orbital/crypto_ps4.h> #include <zlib.h> #include <stdexcept> constexpr U32 SELF_MAGIC = '\x4F\x15\x3D\x1D'; enum SelfEndian { LITTLE = 1, }; enum ProgramAuthID : U64 { PAID_KERNEL = UINT64_C(0x3C00000000000001), }; enum ProgramType : U64 { PTYPE_FAKE = 0x1, PTYPE_NPDRM_EXEC = 0x4, PTYPE_NPDRM_DYNLIB = 0x5, PTYPE_SYSTEM_EXEC = 0x8, PTYPE_SYSTEM_DYNLIB = 0x9, PTYPE_HOST_KERNEL = 0xC, PTYPE_SECURE_MODULE = 0xE, PTYPE_SECURE_KERNEL = 0xF, }; static Key getKey(const SelfInfo& info) { const auto& crypto = ps4Crypto(); switch (info.paid) { case PAID_KERNEL: if (info.version_app >= 0x00000900'00000000) { return crypto.get("self.80010002.900"); } else if (info.version_app >= 0x00000850'00000000) { return crypto.get("self.80010002.8xx"); } else if (info.version_app >= 0x00000800'00000000) { return crypto.get("self.80010002.800"); } else if (info.version_app >= 0x00000750'00000000) { return crypto.get("self.80010002.7xx"); } else if (info.version_app >= 0x00000700'00000000) { return crypto.get("self.80010002.700"); } else if (info.version_app >= 0x00000650'00000000) { return crypto.get("self.80010002.6xx"); } else if (info.version_app >= 0x00000600'00000000) { return crypto.get("self.80010002.600"); } else if (info.version_app >= 0x00000550'00000000) { return crypto.get("self.80010002.550"); } else if (info.version_app >= 0x00000500'00000000) { return crypto.get("self.80010002.500"); } else if (info.version_app >= 0x00000450'00000000) { return crypto.get("self.80010002.450"); } else if (info.version_app >= 0x00000406'00000000) { return crypto.get("self.80010002.406"); } else if (info.version_app >= 0x00000400'00000000) { return crypto.get("self.80010002.400"); } else if (info.version_app >= 0x00000350'00000000) { return crypto.get("self.80010002.350"); } else if (info.version_app >= 0x00000150'00000000) { return crypto.get("self.80010002.1xx"); } else { throw std::runtime_error("Unsupported"); } break; default: throw std::runtime_error("Unsupported"); } } SelfParser::SelfParser(Stream& s) : CfParser(s) { const auto& cryp
d_segment(index); const auto& segment = segments[segment_idx]; const auto& meta = metas[segment_idx]; s.seek(segment.offset, StreamSeek::Set); Buffer buffer = s.read_b(segment.mem_size); if (segment.is_encrypted()) { decrypt(buffer, meta); } if (segment.is_compressed()) { const auto size = segment.mem_size; unsigned long cur_zsize = (size & ~0xF) - (size & 0xF); unsigned long cur_usize = segment.file_size; Buffer result(segment.file_size); int zerr = uncompress(result.data(), &cur_usize, buffer.data(), cur_zsize); assert(zerr == 0); buffer = std::move(result); } return buffer; }
to = ps4Crypto(); s.seek(0, StreamSeek::Set); header = s.read_t<SelfHeader>(); assert(header.magic == SELF_MAGIC); assert(header.version == 0); assert(header.mode == 1); assert(header.endian == SelfEndian::LITTLE); assert(header.attr == 0x12); segments.resize(header.segment_count); s.read(sizeof(SelfSegment) * segments.size(), segments.data()); const auto elf_offset = s.tell(); elf = std::make_unique<ElfParser>(s); const auto ehdr = elf->get_ehdr(); const auto info_offset = elf_offset + ehdr.e_phoff + ehdr.e_phentsize * ehdr.e_phnum; s.seek(align(info_offset, 16), StreamSeek::Set); info = s.read_t<SelfInfo>(); assert(s.tell() == header.header_size, "NPDRM Control Blocks are unsupported"); Buffer buffer(header.meta_size); s.read(buffer.size(), buffer.data()); crypto.decrypt(buffer.data(), buffer.size(), getKey(info)); auto* meta_entries = reinterpret_cast<const SelfMeta*>(&buffer[0]); metas.clear(); for (size_t i = 0; i < header.segment_count; i++) { metas.push_back(meta_entries[i]); } } SelfParser::~SelfParser() { } Elf_Ehdr<> SelfParser::get_ehdr() { return elf->get_ehdr(); } Elf_Phdr<> SelfParser::get_phdr(size_t i) { return elf->get_phdr(i); } Buffer SelfParser::get_pdata(size_t i) { const auto segment_idx = find_segment(i); if (segments[segment_idx].has_blocks()) { return get_segment_blocked(i); } else { return get_segment_nonblocked(i); } } U64 SelfParser::find_segment(U64 phdr_idx) const { for (size_t i = 0; i < header.segment_count; i++) { if (segments[i].id() == phdr_idx) { return i; } } throw std::out_of_range("SELF segment not found"); } Buffer SelfParser::get_segment_blocked(U64 index) { throw std::runtime_error("Unimplemented"); } Buffer SelfParser::get_segment_nonblocked(U64 index) { const auto segment_idx = fin
random
[ { "content": "struct Key {\n\n enum Type {\n\n NONE,\n\n AES_128_EBC,\n\n AES_128_CBC,\n\n } type;\n\n\n\n Botan::SymmetricKey key;\n\n Botan::InitializationVector iv;\n\n\n\n Key() : type(NONE) {}\n\n Key(Type type, const void* key_buf, size_t key_len, const void* iv_buf,...
C++
include/svg_reader.hpp
phonxvzf/svg2scad
eb458df6cee6a65fbabbe5a5600f50551532adb4
#ifndef SVG_READER_HPP #define SVG_READER_HPP #include <string> #include <memory> #include "svgpp/svgpp.hpp" #include "rapidxml_ns/rapidxml_ns_utils.hpp" #include "svgpp/policy/xml/rapidxml_ns.hpp" #include "math/util.hpp" namespace svg { using namespace math; namespace action { enum type { ACTION_MOVE_TO, ACTION_LINE_TO, ACTION_QUAD_BEZIER_TO, ACTION_CUBIC_BEZIER_TO, ACTION_ELLIPTIC_ARC_TO, ACTION_UNKNOWN }; struct base { virtual ~base() {} }; struct move_to : base { union { vector2f p1, dst; }; move_to() = delete; move_to(const vector2f& _p1) : p1(_p1) {} }; struct line_to : base { union { vector2f p1, dst; }; line_to() = delete; line_to(const vector2f& _p1) : p1(_p1) {} }; struct quadratic_bezier_to : base { vector2f p1; union { vector2f p2, dst; }; quadratic_bezier_to() = delete; quadratic_bezier_to(const vector2f& _p1, const vector2f& _p2) : p1(_p1), p2(_p2) {} }; struct cubic_bezier_to : base { vector2f p1, p2; union { vector2f p3, dst; }; cubic_bezier_to() = delete; cubic_bezier_to(const vector2f& _p1, const vector2f& _p2, const vector2f& _p3) : p1(_p1), p2(_p2), p3(_p3) {} }; struct elliptic_arc_to : base { vector2f r; float x_axis_rotation; union { vector2f p1, dst; }; bool large_arc; bool sweep; elliptic_arc_to() = delete; elliptic_arc_to( const vector2f& _r, float _x_axis_rotation, const vector2f& _p1, bool _large_arc, bool _sweep) : r(_r), x_axis_rotation(_x_axis_rotation), p1(_p1), large_arc(_large_arc), sweep(_sweep) {} }; inline type get_type(const std::shared_ptr<base>& action) { base* base_ptr = action.get(); if (dynamic_cast<move_to*>(base_ptr)) return ACTION_MOVE_TO; if (dynamic_cast<line_to*>(base_ptr)) return ACTION_LINE_TO; if (dynamic_cast<quadratic_bezier_to*>(base_ptr)) return ACTION_QUAD_BEZIER_TO; if (dynamic_cast<cubic_bezier_to*>(base_ptr)) return ACTION_CUBIC_BEZIER_TO; if (dynamic_cast<elliptic_arc_to*>(base_ptr)) return ACTION_ELLIPTIC_ARC_TO; return ACTION_UNKNOWN; } } class reader { private: class context { private: std::vector<std::shared_ptr<action::base>> m_actions; public: context() = default; ~context(); const std::vector<std::shared_ptr<action::base>>& actions() const; void path_move_to(float x, float y, svgpp::tag::coordinate::absolute); void path_line_to(float x, float y, svgpp::tag::coordinate::absolute); void path_quadratic_bezier_to( float x1, float y1, float x, float y, svgpp::tag::coordinate::absolute); void path_cubic_bezier_to( float x1, float y1, float x2, float y2, float x, float y, svgpp::tag::coordinate::absolute); void path_elliptical_arc_to( float rx, float ry, float x_axis_rotation, bool large_arc_flag, bool sweep_flag, float x, float y, svgpp::tag::coordinate::absolute); void path_close_subpath(); void path_exit(); void on_enter_element(svgpp::tag::element::any); void on_exit_element(); static const bool convert_only_rounded_rect_to_path = false; } m_context; float m_width = 0.0f; float m_height = 0.0f; public: reader(); reader(const std::string& fpath); ~reader(); const std::vector<std::shared_ptr<action::base>>& actions() const; const std::vector<std::shared_ptr<action::base>>& load_file(const std::string& fpath); float width() const; float height() const; }; using processed_element_t = boost::mpl::set< svgpp::tag::element::svg, svgpp::tag::element::g, svgpp::tag::element::circle, svgpp::tag::element::ellipse, svgpp::tag::element::line, svgpp::tag::element::path, svgpp::tag::element::polygon, svgpp::tag::element::polyline, svgpp::tag::element::rect >; } #endif
#ifndef SVG_READER_HPP #define SVG_READER_HPP #include <string> #include <memory> #include "svgpp/svgpp.hpp" #include "rapidxml_ns/rapidxml_ns_utils.hpp" #include "svgpp/policy/xml/rapidxml_ns.hpp" #include "math/util.hpp" namespace svg { using namespace math; namespace action { enum type { ACTION_MOVE_TO, ACTION_LINE_TO, ACTION_QUAD_BEZIER_TO, ACTION_CUBIC_BEZIER_TO, ACTION_ELLIPTIC_ARC_TO, ACTION_UNKNOWN }; struct base { virtual ~base() {} }; struct move_to : base { union { vector2f p1, dst; }; move_to() = delete; move_to(const vector2f& _p1) : p1(_p1) {} }; struct line_to : base { union { vector2f p1, dst; }; line_to() = delete; line_to(const vector2f& _p1) : p1(_p1) {} }; struct quadratic_bezier_to : base { vector2f p1; union { vector2f p2, dst; }; quadratic_bezier_to() = delete; quadratic_bezier_to(const vector2f& _p1, const vector2f& _p2) : p1(_p1), p2(_p2) {} }; struct cubic_bezier_to : base { vector2f p1, p2; union { vector2f p3, dst; }; cubic_bezier_to() = delete; cubic_bezier_to(const vector2f& _p1, const vector2f& _p2, const vector2f& _p3) : p1(_p1), p2(_p2), p3(_p3) {} }; struct elliptic_arc_to : base { vector2f r; float x_axis_rotation; union { vector2f p1, dst; }; bool large_arc; bool sweep; elliptic_arc_to() = delete; elliptic_arc_to( const vector2f& _r, float _x_axis_rotation, const vector2f& _p1, bool _large_arc, bool _sweep) : r(_r), x_axis_rotation(_x_axis_rotation), p1(_p1), large_arc(_large_arc), sweep(_sweep) {} }; inline type get_type(const std::shared_ptr<base>& action) { base* base_ptr = action.get(); if (dynamic_cast<move_to*>(base_ptr)) return ACTION_MOVE_T
} class reader { private: class context { private: std::vector<std::shared_ptr<action::base>> m_actions; public: context() = default; ~context(); const std::vector<std::shared_ptr<action::base>>& actions() const; void path_move_to(float x, float y, svgpp::tag::coordinate::absolute); void path_line_to(float x, float y, svgpp::tag::coordinate::absolute); void path_quadratic_bezier_to( float x1, float y1, float x, float y, svgpp::tag::coordinate::absolute); void path_cubic_bezier_to( float x1, float y1, float x2, float y2, float x, float y, svgpp::tag::coordinate::absolute); void path_elliptical_arc_to( float rx, float ry, float x_axis_rotation, bool large_arc_flag, bool sweep_flag, float x, float y, svgpp::tag::coordinate::absolute); void path_close_subpath(); void path_exit(); void on_enter_element(svgpp::tag::element::any); void on_exit_element(); static const bool convert_only_rounded_rect_to_path = false; } m_context; float m_width = 0.0f; float m_height = 0.0f; public: reader(); reader(const std::string& fpath); ~reader(); const std::vector<std::shared_ptr<action::base>>& actions() const; const std::vector<std::shared_ptr<action::base>>& load_file(const std::string& fpath); float width() const; float height() const; }; using processed_element_t = boost::mpl::set< svgpp::tag::element::svg, svgpp::tag::element::g, svgpp::tag::element::circle, svgpp::tag::element::ellipse, svgpp::tag::element::line, svgpp::tag::element::path, svgpp::tag::element::polygon, svgpp::tag::element::polyline, svgpp::tag::element::rect >; } #endif
O; if (dynamic_cast<line_to*>(base_ptr)) return ACTION_LINE_TO; if (dynamic_cast<quadratic_bezier_to*>(base_ptr)) return ACTION_QUAD_BEZIER_TO; if (dynamic_cast<cubic_bezier_to*>(base_ptr)) return ACTION_CUBIC_BEZIER_TO; if (dynamic_cast<elliptic_arc_to*>(base_ptr)) return ACTION_ELLIPTIC_ARC_TO; return ACTION_UNKNOWN; }
function_block-function_prefixed
[ { "content": "struct value_parser<tag::type::string, SVGPP_TEMPLATE_ARGS_PASS>\n\n{\n\n template<class AttributeTag, class Context, class AttributeValue, class PropertySource>\n\n static bool parse(AttributeTag tag, Context & context, AttributeValue const & attribute_value, \n\n ...
C++
src/graphics/examples/vkproto/cmd-buf-benchmark/main.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
#include <unistd.h> #include <memory> #include <vector> #include "src/graphics/examples/vkproto/common/command_buffers.h" #include "src/graphics/examples/vkproto/common/command_pool.h" #include "src/graphics/examples/vkproto/common/debug_utils_messenger.h" #include "src/graphics/examples/vkproto/common/device.h" #include "src/graphics/examples/vkproto/common/framebuffers.h" #include "src/graphics/examples/vkproto/common/graphics_pipeline.h" #include "src/graphics/examples/vkproto/common/image_view.h" #include "src/graphics/examples/vkproto/common/instance.h" #include "src/graphics/examples/vkproto/common/physical_device.h" #include "src/graphics/examples/vkproto/common/render_pass.h" #include "src/graphics/examples/vkproto/common/swapchain.h" #include "src/graphics/examples/vkproto/common/utils.h" #include <vulkan/vulkan.hpp> static bool DrawAllFrames(const vkp::Device& vkp_device, const vkp::CommandBuffers& vkp_command_buffers); int main(int argc, char* argv[]) { #ifndef NDEBUG printf("Warning - benchmarking debug build.\n"); const bool kEnableValidation = true; #else const bool kEnableValidation = false; #endif vkp::Instance vkp_instance(kEnableValidation); RTN_IF_MSG(1, !vkp_instance.Init(), "Instance Initialization Failed.\n"); if (kEnableValidation) { vkp::DebugUtilsMessenger vkp_debug_messenger(vkp_instance.shared()); RTN_IF_MSG(1, !vkp_debug_messenger.Init(), "Debug Messenger Initialization Failed.\n"); } vkp::PhysicalDevice vkp_physical_device(vkp_instance.shared()); RTN_IF_MSG(1, !vkp_physical_device.Init(), "Phys Device Initialization Failed.\n"); vkp::Device vkp_device(vkp_physical_device.get()); RTN_IF_MSG(1, !vkp_device.Init(), "Logical Device Initialization Failed.\n"); std::shared_ptr<vk::Device> device = vkp_device.shared(); vk::Format image_format; vk::Extent2D extent; std::vector<std::shared_ptr<vkp::ImageView>> vkp_image_views; std::vector<vk::ImageView> image_views; constexpr uint32_t kCommandBufferCount = 100; for (uint32_t i = 0; i < kCommandBufferCount; i++) { auto vkp_offscreen_image_view = std::make_shared<vkp::ImageView>(device, vkp_physical_device.get(), vk::Extent2D{64, 64}); RTN_IF_MSG(1, !vkp_offscreen_image_view->Init(), "Image View Initialization Failed.\n"); image_format = vkp_offscreen_image_view->format(); extent = vkp_offscreen_image_view->extent(); image_views.emplace_back(vkp_offscreen_image_view->get()); vkp_image_views.emplace_back(std::move(vkp_offscreen_image_view)); } auto vkp_render_pass = std::make_shared<vkp::RenderPass>(device, image_format, true); RTN_IF_MSG(1, !vkp_render_pass->Init(), "Render Pass Initialization Failed.\n"); auto vkp_pipeline = std::make_unique<vkp::GraphicsPipeline>(device, extent, vkp_render_pass); RTN_IF_MSG(1, !vkp_pipeline->Init(), "Graphics Pipeline Initialization Failed.\n"); auto vkp_framebuffer = std::make_unique<vkp::Framebuffers>(device, extent, vkp_render_pass->get(), image_views); RTN_IF_MSG(1, !vkp_framebuffer->Init(), "Framebuffers Initialization Failed.\n"); auto vkp_command_pool = std::make_shared<vkp::CommandPool>(device, vkp_device.queue_family_index()); RTN_IF_MSG(1, !vkp_command_pool->Init(), "Command Pool Initialization Failed.\n"); auto vkp_command_buffers = std::make_unique<vkp::CommandBuffers>( device, vkp_command_pool, vkp_framebuffer->framebuffers(), vkp_pipeline->get(), vkp_render_pass->get(), extent); RTN_IF_MSG(1, !vkp_command_buffers->Init(), "Command Buffer Initialization Failed.\n"); sleep(1); if (!DrawAllFrames(vkp_device, *vkp_command_buffers)) { RTN_MSG(1, "First DrawAllFrames Failed.\n"); } device->waitIdle(); auto start_time = std::chrono::steady_clock::now(); if (!DrawAllFrames(vkp_device, *vkp_command_buffers)) { RTN_MSG(1, "Second DrawAllFrames Failed.\n"); } device->waitIdle(); auto end_time = std::chrono::steady_clock::now(); fprintf(stderr, "End time: %lld\n", std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count()); return 0; } bool DrawAllFrames(const vkp::Device& device, const vkp::CommandBuffers& command_buffers) { vk::SubmitInfo submit_info; submit_info.commandBufferCount = static_cast<uint32_t>(command_buffers.command_buffers().size()); std::vector<vk::CommandBuffer> command_buffer(submit_info.commandBufferCount); for (uint32_t i = 0; i < submit_info.commandBufferCount; i++) { command_buffer[i] = command_buffers.command_buffers()[i].get(); } submit_info.pCommandBuffers = command_buffer.data(); if (device.queue().submit(1, &submit_info, vk::Fence()) != vk::Result::eSuccess) { RTN_MSG(false, "Failed to submit draw command buffer.\n"); } return true; }
#include <unistd.h> #include <memory> #include <vector> #include "src/graphics/examples/vkproto/common/command_buffers.h" #include "src/graphics/examples/vkproto/common/command_pool.h" #include "src/graphics/examples/vkproto/common/debug_utils_messenger.h" #include "src/graphics/examples/vkproto/common/device.h" #include "src/graphics/examples/vkproto/common/framebuffers.h" #include "src/graphics/examples/vkproto/common/graphics_pipeline.h" #include "src/graphics/examples/vkproto/common/image_view.h" #include "src/graphics/examples/vkproto/common/instance.h" #include "src/graphics/examples/vkproto/common/physical_device.h" #include "src/graphics/examples/vkproto/common/render_pass.h" #include "src/graphics/examples/vkproto/common/swapchain.h" #include "src/graphics/examples/vkproto/common/utils.h" #include <vulkan/vulkan.hpp> static bool DrawAllFrames(const vkp::Device& vkp_device, const vkp::CommandBuffers& vkp_command_buffers); int main(int argc, char* argv[]) { #ifndef NDEBUG printf("Warning - benchmarking debug build.\n"); const bool kEnableValidation = true; #else const bool kEnableValidation = false; #endif vkp::Instance vkp_instance(kEnableValidation); RTN_IF_MSG(1, !vkp_instance.Init(), "Instance Initialization Failed.\n");
vkp::PhysicalDevice vkp_physical_device(vkp_instance.shared()); RTN_IF_MSG(1, !vkp_physical_device.Init(), "Phys Device Initialization Failed.\n"); vkp::Device vkp_device(vkp_physical_device.get()); RTN_IF_MSG(1, !vkp_device.Init(), "Logical Device Initialization Failed.\n"); std::shared_ptr<vk::Device> device = vkp_device.shared(); vk::Format image_format; vk::Extent2D extent; std::vector<std::shared_ptr<vkp::ImageView>> vkp_image_views; std::vector<vk::ImageView> image_views; constexpr uint32_t kCommandBufferCount = 100; for (uint32_t i = 0; i < kCommandBufferCount; i++) { auto vkp_offscreen_image_view = std::make_shared<vkp::ImageView>(device, vkp_physical_device.get(), vk::Extent2D{64, 64}); RTN_IF_MSG(1, !vkp_offscreen_image_view->Init(), "Image View Initialization Failed.\n"); image_format = vkp_offscreen_image_view->format(); extent = vkp_offscreen_image_view->extent(); image_views.emplace_back(vkp_offscreen_image_view->get()); vkp_image_views.emplace_back(std::move(vkp_offscreen_image_view)); } auto vkp_render_pass = std::make_shared<vkp::RenderPass>(device, image_format, true); RTN_IF_MSG(1, !vkp_render_pass->Init(), "Render Pass Initialization Failed.\n"); auto vkp_pipeline = std::make_unique<vkp::GraphicsPipeline>(device, extent, vkp_render_pass); RTN_IF_MSG(1, !vkp_pipeline->Init(), "Graphics Pipeline Initialization Failed.\n"); auto vkp_framebuffer = std::make_unique<vkp::Framebuffers>(device, extent, vkp_render_pass->get(), image_views); RTN_IF_MSG(1, !vkp_framebuffer->Init(), "Framebuffers Initialization Failed.\n"); auto vkp_command_pool = std::make_shared<vkp::CommandPool>(device, vkp_device.queue_family_index()); RTN_IF_MSG(1, !vkp_command_pool->Init(), "Command Pool Initialization Failed.\n"); auto vkp_command_buffers = std::make_unique<vkp::CommandBuffers>( device, vkp_command_pool, vkp_framebuffer->framebuffers(), vkp_pipeline->get(), vkp_render_pass->get(), extent); RTN_IF_MSG(1, !vkp_command_buffers->Init(), "Command Buffer Initialization Failed.\n"); sleep(1); if (!DrawAllFrames(vkp_device, *vkp_command_buffers)) { RTN_MSG(1, "First DrawAllFrames Failed.\n"); } device->waitIdle(); auto start_time = std::chrono::steady_clock::now(); if (!DrawAllFrames(vkp_device, *vkp_command_buffers)) { RTN_MSG(1, "Second DrawAllFrames Failed.\n"); } device->waitIdle(); auto end_time = std::chrono::steady_clock::now(); fprintf(stderr, "End time: %lld\n", std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count()); return 0; } bool DrawAllFrames(const vkp::Device& device, const vkp::CommandBuffers& command_buffers) { vk::SubmitInfo submit_info; submit_info.commandBufferCount = static_cast<uint32_t>(command_buffers.command_buffers().size()); std::vector<vk::CommandBuffer> command_buffer(submit_info.commandBufferCount); for (uint32_t i = 0; i < submit_info.commandBufferCount; i++) { command_buffer[i] = command_buffers.command_buffers()[i].get(); } submit_info.pCommandBuffers = command_buffer.data(); if (device.queue().submit(1, &submit_info, vk::Fence()) != vk::Result::eSuccess) { RTN_MSG(false, "Failed to submit draw command buffer.\n"); } return true; }
if (kEnableValidation) { vkp::DebugUtilsMessenger vkp_debug_messenger(vkp_instance.shared()); RTN_IF_MSG(1, !vkp_debug_messenger.Init(), "Debug Messenger Initialization Failed.\n"); }
if_condition
[]
C++
src/resources/track.hpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
#pragma once #include "tile_library.hpp" #include "terrain_library.hpp" #include "texture_library.hpp" #include "path_library.hpp" #include "track_layer.hpp" #include "start_point.hpp" #include "control_point.hpp" #include "track_path.hpp" #include "utility/vector2.hpp" #include <boost/range/iterator_range.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/indirect_iterator.hpp> #include <vector> #include <list> #include <memory> #include <string> #include <cstdint> #include <cstddef> #include <map> namespace ts { namespace resources { namespace detail { struct ConstPathRangeTransform { const resources::TrackPath* operator()(const std::unique_ptr<TrackPath>& p) const { return p.get(); } }; struct PathRangeTransform { resources::TrackPath* operator()(const std::unique_ptr<TrackPath>& p) const { return p.get(); } }; } class Track { public: Track() = default; Track(const Track&) = default; Track& operator=(const Track&) = default; Track(Track&&) = default; Track& operator=(Track&&) = default; void set_path(const std::string& path); const std::string& path() const noexcept; void set_author(std::string author); const std::string& author() const noexcept; Vector2i size() const; void set_size(const Vector2i& size); void set_height_level_count(std::int32_t height_levels) noexcept; std::int32_t height_level_count() const noexcept; TileLibrary& tile_library() noexcept; const TileLibrary& tile_library() const noexcept; TextureLibrary& texture_library() noexcept; const TextureLibrary& texture_library() const noexcept; TerrainLibrary& terrain_library() noexcept; const TerrainLibrary& terrain_library() const noexcept; PathLibrary& path_library() noexcept; const PathLibrary& path_library() const noexcept; using LayerId = std::uint32_t; TrackLayer* create_layer(TrackLayerType type, std::string layer_name, std::uint32_t level); void deactivate_layer(TrackLayer* layer); void activate_layer(TrackLayer* layer); std::size_t layer_count() const noexcept; void set_layer_level(TrackLayer* layer, std::uint32_t level); std::int32_t shift_towards_front(const TrackLayer* layer, std::int32_t amount = 1); std::int32_t shift_towards_back(const TrackLayer* layer, std::int32_t amount = 1); using LayerOrderInterface = boost::iterator_range<boost::indirect_iterator<TrackLayer* const*>>; using ConstLayerOrderInterface = boost::iterator_range<boost::indirect_iterator<const TrackLayer* const*>>; LayerOrderInterface layers(); ConstLayerOrderInterface layers() const; void add_control_point(const ControlPoint& point); void add_control_point(const ControlPoint& point, std::size_t idx); const std::vector<ControlPoint>& control_points() const; void remove_control_point(std::size_t idx); void update_control_point(std::size_t idx, const ControlPoint& cp); void add_start_point(const StartPoint& point); const std::vector<StartPoint>& custom_start_points() const; const std::vector<StartPoint>& start_points() const; void add_asset(const std::string& path); const std::vector<std::string>& assets() const; private: void insert_layer(TrackLayer* layer); void update_z_index(); std::string path_; std::string author_; Vector2i size_ = {}; std::int32_t height_level_count_ = 1; TileLibrary tile_library_; TerrainLibrary terrain_library_; TextureLibrary texture_library_; PathLibrary path_library_; std::vector<std::string> assets_; std::map<LayerId, TrackLayer> layers_; std::vector<TrackLayer*> layer_order_; std::vector<ControlPoint> control_points_; std::vector<StartPoint> custom_start_points_; mutable std::vector<StartPoint> start_points_; }; template<typename LayerType> struct LayerOrderInterface { private: friend Track; explicit LayerOrderInterface(LayerType** begin, LayerType** end); LayerType** begin_; LayerType** end_; }; } }
#pragma once #include "tile_library.hpp" #include "terrain_library.hpp" #include "texture_library.hpp" #include "path_library.hpp" #include "track_layer.hpp" #include "start_point.hpp" #include "control_point.hpp" #include "track_path.hpp" #include "utility/vector2.hpp" #include <boost/range/iterator_range.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/indirect_iterator.hpp> #include <vector> #include <list> #include <memory> #include <string> #include <
ult; Track& operator=(const Track&) = default; Track(Track&&) = default; Track& operator=(Track&&) = default; void set_path(const std::string& path); const std::string& path() const noexcept; void set_author(std::string author); const std::string& author() const noexcept; Vector2i size() const; void set_size(const Vector2i& size); void set_height_level_count(std::int32_t height_levels) noexcept; std::int32_t height_level_count() const noexcept; TileLibrary& tile_library() noexcept; const TileLibrary& tile_library() const noexcept; TextureLibrary& texture_library() noexcept; const TextureLibrary& texture_library() const noexcept; TerrainLibrary& terrain_library() noexcept; const TerrainLibrary& terrain_library() const noexcept; PathLibrary& path_library() noexcept; const PathLibrary& path_library() const noexcept; using LayerId = std::uint32_t; TrackLayer* create_layer(TrackLayerType type, std::string layer_name, std::uint32_t level); void deactivate_layer(TrackLayer* layer); void activate_layer(TrackLayer* layer); std::size_t layer_count() const noexcept; void set_layer_level(TrackLayer* layer, std::uint32_t level); std::int32_t shift_towards_front(const TrackLayer* layer, std::int32_t amount = 1); std::int32_t shift_towards_back(const TrackLayer* layer, std::int32_t amount = 1); using LayerOrderInterface = boost::iterator_range<boost::indirect_iterator<TrackLayer* const*>>; using ConstLayerOrderInterface = boost::iterator_range<boost::indirect_iterator<const TrackLayer* const*>>; LayerOrderInterface layers(); ConstLayerOrderInterface layers() const; void add_control_point(const ControlPoint& point); void add_control_point(const ControlPoint& point, std::size_t idx); const std::vector<ControlPoint>& control_points() const; void remove_control_point(std::size_t idx); void update_control_point(std::size_t idx, const ControlPoint& cp); void add_start_point(const StartPoint& point); const std::vector<StartPoint>& custom_start_points() const; const std::vector<StartPoint>& start_points() const; void add_asset(const std::string& path); const std::vector<std::string>& assets() const; private: void insert_layer(TrackLayer* layer); void update_z_index(); std::string path_; std::string author_; Vector2i size_ = {}; std::int32_t height_level_count_ = 1; TileLibrary tile_library_; TerrainLibrary terrain_library_; TextureLibrary texture_library_; PathLibrary path_library_; std::vector<std::string> assets_; std::map<LayerId, TrackLayer> layers_; std::vector<TrackLayer*> layer_order_; std::vector<ControlPoint> control_points_; std::vector<StartPoint> custom_start_points_; mutable std::vector<StartPoint> start_points_; }; template<typename LayerType> struct LayerOrderInterface { private: friend Track; explicit LayerOrderInterface(LayerType** begin, LayerType** end); LayerType** begin_; LayerType** end_; }; } }
cstdint> #include <cstddef> #include <map> namespace ts { namespace resources { namespace detail { struct ConstPathRangeTransform { const resources::TrackPath* operator()(const std::unique_ptr<TrackPath>& p) const { return p.get(); } }; struct PathRangeTransform { resources::TrackPath* operator()(const std::unique_ptr<TrackPath>& p) const { return p.get(); } }; } class Track { public: Track() = default; Track(const Track&) = defa
random
[ { "content": "/*\n\n * Created by Phil on 5/11/2010.\n\n * Copyright 2010 Two Blue Cubes Ltd. All rights reserved.\n\n *\n\n * Distributed under the Boost Software License, Version 1.0. (See accompanying\n\n * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n */\n\n#ifndef TWOBLUECUB...
C++
Samples/cuSolverDn_LinearSolver/cuSolverDn_LinearSolver.cpp
rob-opsi/cuda-samples
32943424ed7023f9168266d9fb7b76e8566fd054
#include <assert.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cuda_runtime.h> #include "cublas_v2.h" #include "cusolverDn.h" #include "helper_cuda.h" #include "helper_cusolver.h" template <typename T_ELEM> int loadMMSparseMatrix(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, T_ELEM **aVal, int **aRowInd, int **aColInd, int extendSymMatrix); void UsageDN(void) { printf("<options>\n"); printf("-h : display this help\n"); printf("-R=<name> : choose a linear solver\n"); printf(" chol (cholesky factorization), this is default\n"); printf(" qr (QR factorization)\n"); printf(" lu (LU factorization)\n"); printf("-lda=<int> : leading dimension of A , m by default\n"); printf("-file=<filename>: filename containing a matrix in MM format\n"); printf("-device=<device_id> : <device_id> if want to run on specific GPU\n"); exit(0); } int linearSolverCHOL(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { int bufferSize = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; int h_info = 0; double start, stop; double time_solve; cublasFillMode_t uplo = CUBLAS_FILL_MODE_LOWER; checkCudaErrors(cusolverDnDpotrf_bufferSize(handle, uplo, n, (double *)Acopy, lda, &bufferSize)); checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors( cusolverDnDpotrf(handle, uplo, n, A, lda, buffer, bufferSize, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: Cholesky factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cusolverDnDpotrs(handle, uplo, n, 1, A, lda, x, n, info)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: cholesky = %10.6f sec\n", time_solve); if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } return 0; } int linearSolverLU(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { int bufferSize = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; int *ipiv = NULL; int h_info = 0; double start, stop; double time_solve; checkCudaErrors(cusolverDnDgetrf_bufferSize(handle, n, n, (double *)Acopy, lda, &bufferSize)); checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors(cudaMalloc(&ipiv, sizeof(int) * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors(cusolverDnDgetrf(handle, n, n, A, lda, buffer, ipiv, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: LU factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors( cusolverDnDgetrs(handle, CUBLAS_OP_N, n, 1, A, lda, ipiv, x, n, info)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: LU = %10.6f sec\n", time_solve); if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } if (ipiv) { checkCudaErrors(cudaFree(ipiv)); } return 0; } int linearSolverQR(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { cublasHandle_t cublasHandle = NULL; int bufferSize = 0; int bufferSize_geqrf = 0; int bufferSize_ormqr = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; double *tau = NULL; int h_info = 0; double start, stop; double time_solve; const double one = 1.0; checkCudaErrors(cublasCreate(&cublasHandle)); checkCudaErrors(cusolverDnDgeqrf_bufferSize(handle, n, n, (double *)Acopy, lda, &bufferSize_geqrf)); checkCudaErrors(cusolverDnDormqr_bufferSize(handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_T, n, 1, n, A, lda, NULL, x, n, &bufferSize_ormqr)); printf("buffer_geqrf = %d, buffer_ormqr = %d \n", bufferSize_geqrf, bufferSize_ormqr); bufferSize = (bufferSize_geqrf > bufferSize_ormqr) ? bufferSize_geqrf : bufferSize_ormqr; checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors(cudaMalloc((void **)&tau, sizeof(double) * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors( cusolverDnDgeqrf(handle, n, n, A, lda, tau, buffer, bufferSize, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: LU factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cusolverDnDormqr(handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_T, n, 1, n, A, lda, tau, x, n, buffer, bufferSize, info)); checkCudaErrors(cublasDtrsm(cublasHandle, CUBLAS_SIDE_LEFT, CUBLAS_FILL_MODE_UPPER, CUBLAS_OP_N, CUBLAS_DIAG_NON_UNIT, n, 1, &one, A, lda, x, n)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: QR = %10.6f sec\n", time_solve); if (cublasHandle) { checkCudaErrors(cublasDestroy(cublasHandle)); } if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } if (tau) { checkCudaErrors(cudaFree(tau)); } return 0; } void parseCommandLineArguments(int argc, char *argv[], struct testOpts &opts) { memset(&opts, 0, sizeof(opts)); if (checkCmdLineFlag(argc, (const char **)argv, "-h")) { UsageDN(); } if (checkCmdLineFlag(argc, (const char **)argv, "R")) { char *solverType = NULL; getCmdLineArgumentString(argc, (const char **)argv, "R", &solverType); if (solverType) { if ((STRCASECMP(solverType, "chol") != 0) && (STRCASECMP(solverType, "lu") != 0) && (STRCASECMP(solverType, "qr") != 0)) { printf("\nIncorrect argument passed to -R option\n"); UsageDN(); } else { opts.testFunc = solverType; } } } if (checkCmdLineFlag(argc, (const char **)argv, "file")) { char *fileName = 0; getCmdLineArgumentString(argc, (const char **)argv, "file", &fileName); if (fileName) { opts.sparse_mat_filename = fileName; } else { printf("\nIncorrect filename passed to -file \n "); UsageDN(); } } if (checkCmdLineFlag(argc, (const char **)argv, "lda")) { opts.lda = getCmdLineArgumentInt(argc, (const char **)argv, "lda"); } } int main(int argc, char *argv[]) { struct testOpts opts; cusolverDnHandle_t handle = NULL; cublasHandle_t cublasHandle = NULL; cudaStream_t stream = NULL; int rowsA = 0; int colsA = 0; int nnzA = 0; int baseA = 0; int lda = 0; int *h_csrRowPtrA = NULL; int *h_csrColIndA = NULL; double *h_csrValA = NULL; double *h_A = NULL; double *h_x = NULL; double *h_b = NULL; double *h_r = NULL; double *d_A = NULL; double *d_x = NULL; double *d_b = NULL; double *d_r = NULL; const double minus_one = -1.0; const double one = 1.0; double x_inf = 0.0; double r_inf = 0.0; double A_inf = 0.0; int errors = 0; parseCommandLineArguments(argc, argv, opts); if (NULL == opts.testFunc) { opts.testFunc = "chol"; } findCudaDevice(argc, (const char **)argv); printf("step 1: read matrix market format\n"); if (opts.sparse_mat_filename == NULL) { opts.sparse_mat_filename = sdkFindFilePath("gr_900_900_crg.mtx", argv[0]); if (opts.sparse_mat_filename != NULL) printf("Using default input file [%s]\n", opts.sparse_mat_filename); else printf("Could not find gr_900_900_crg.mtx\n"); } else { printf("Using input file [%s]\n", opts.sparse_mat_filename); } if (opts.sparse_mat_filename == NULL) { fprintf(stderr, "Error: input matrix is not provided\n"); return EXIT_FAILURE; } if (loadMMSparseMatrix<double>(opts.sparse_mat_filename, 'd', true, &rowsA, &colsA, &nnzA, &h_csrValA, &h_csrRowPtrA, &h_csrColIndA, true)) { exit(EXIT_FAILURE); } baseA = h_csrRowPtrA[0]; printf("sparse matrix A is %d x %d with %d nonzeros, base=%d\n", rowsA, colsA, nnzA, baseA); if (rowsA != colsA) { fprintf(stderr, "Error: only support square matrix\n"); exit(EXIT_FAILURE); } printf("step 2: convert CSR(A) to dense matrix\n"); lda = opts.lda ? opts.lda : rowsA; if (lda < rowsA) { fprintf(stderr, "Error: lda must be greater or equal to dimension of A\n"); exit(EXIT_FAILURE); } h_A = (double *)malloc(sizeof(double) * lda * colsA); h_x = (double *)malloc(sizeof(double) * colsA); h_b = (double *)malloc(sizeof(double) * rowsA); h_r = (double *)malloc(sizeof(double) * rowsA); assert(NULL != h_A); assert(NULL != h_x); assert(NULL != h_b); assert(NULL != h_r); memset(h_A, 0, sizeof(double) * lda * colsA); for (int row = 0; row < rowsA; row++) { const int start = h_csrRowPtrA[row] - baseA; const int end = h_csrRowPtrA[row + 1] - baseA; for (int colidx = start; colidx < end; colidx++) { const int col = h_csrColIndA[colidx] - baseA; const double Areg = h_csrValA[colidx]; h_A[row + col * lda] = Areg; } } printf("step 3: set right hand side vector (b) to 1\n"); for (int row = 0; row < rowsA; row++) { h_b[row] = 1.0; } if (0 == strcmp(opts.testFunc, "chol")) { int issym = 1; for (int j = 0; j < colsA; j++) { for (int i = j; i < rowsA; i++) { double Aij = h_A[i + j * lda]; double Aji = h_A[j + i * lda]; if (Aij != Aji) { issym = 0; break; } } } if (!issym) { printf("Error: A has no symmetric pattern, please use LU or QR \n"); exit(EXIT_FAILURE); } } checkCudaErrors(cusolverDnCreate(&handle)); checkCudaErrors(cublasCreate(&cublasHandle)); checkCudaErrors(cudaStreamCreate(&stream)); checkCudaErrors(cusolverDnSetStream(handle, stream)); checkCudaErrors(cublasSetStream(cublasHandle, stream)); checkCudaErrors(cudaMalloc((void **)&d_A, sizeof(double) * lda * colsA)); checkCudaErrors(cudaMalloc((void **)&d_x, sizeof(double) * colsA)); checkCudaErrors(cudaMalloc((void **)&d_b, sizeof(double) * rowsA)); checkCudaErrors(cudaMalloc((void **)&d_r, sizeof(double) * rowsA)); printf("step 4: prepare data on device\n"); checkCudaErrors(cudaMemcpy(d_A, h_A, sizeof(double) * lda * colsA, cudaMemcpyHostToDevice)); checkCudaErrors( cudaMemcpy(d_b, h_b, sizeof(double) * rowsA, cudaMemcpyHostToDevice)); printf("step 5: solve A*x = b \n"); if (0 == strcmp(opts.testFunc, "chol")) { linearSolverCHOL(handle, rowsA, d_A, lda, d_b, d_x); } else if (0 == strcmp(opts.testFunc, "lu")) { linearSolverLU(handle, rowsA, d_A, lda, d_b, d_x); } else if (0 == strcmp(opts.testFunc, "qr")) { linearSolverQR(handle, rowsA, d_A, lda, d_b, d_x); } else { fprintf(stderr, "Error: %s is unknown function\n", opts.testFunc); exit(EXIT_FAILURE); } printf("step 6: evaluate residual\n"); checkCudaErrors( cudaMemcpy(d_r, d_b, sizeof(double) * rowsA, cudaMemcpyDeviceToDevice)); checkCudaErrors(cublasDgemm_v2(cublasHandle, CUBLAS_OP_N, CUBLAS_OP_N, rowsA, 1, colsA, &minus_one, d_A, lda, d_x, rowsA, &one, d_r, rowsA)); checkCudaErrors( cudaMemcpy(h_x, d_x, sizeof(double) * colsA, cudaMemcpyDeviceToHost)); checkCudaErrors( cudaMemcpy(h_r, d_r, sizeof(double) * rowsA, cudaMemcpyDeviceToHost)); x_inf = vec_norminf(colsA, h_x); r_inf = vec_norminf(rowsA, h_r); A_inf = mat_norminf(rowsA, colsA, h_A, lda); printf("|b - A*x| = %E \n", r_inf); printf("|A| = %E \n", A_inf); printf("|x| = %E \n", x_inf); printf("|b - A*x|/(|A|*|x|) = %E \n", r_inf / (A_inf * x_inf)); if (handle) { checkCudaErrors(cusolverDnDestroy(handle)); } if (cublasHandle) { checkCudaErrors(cublasDestroy(cublasHandle)); } if (stream) { checkCudaErrors(cudaStreamDestroy(stream)); } if (h_csrValA) { free(h_csrValA); } if (h_csrRowPtrA) { free(h_csrRowPtrA); } if (h_csrColIndA) { free(h_csrColIndA); } if (h_A) { free(h_A); } if (h_x) { free(h_x); } if (h_b) { free(h_b); } if (h_r) { free(h_r); } if (d_A) { checkCudaErrors(cudaFree(d_A)); } if (d_x) { checkCudaErrors(cudaFree(d_x)); } if (d_b) { checkCudaErrors(cudaFree(d_b)); } if (d_r) { checkCudaErrors(cudaFree(d_r)); } return 0; }
#include <assert.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cuda_runtime.h> #include "cublas_v2.h" #include "cusolverDn.h" #include "helper_cuda.h" #include "helper_cusolver.h" template <typename T_ELEM> int loadMMSparseMatrix(char *filename, char elem_type, bool csrFormat, int *m, int *n, int *nnz, T_ELEM **aVal, int **aRowInd, int **aColInd, int extendSymMatrix); void UsageDN(void) { printf("<options>\n"); printf("-h : display this help\n"); printf("-R=<name> : choose a linear solver\n"); printf(" chol (cholesky factorization), this is default\n"); printf(" qr (QR factorization)\n"); printf(" lu (LU factorization)\n"); printf("-lda=<int> : leading dimension of A , m by default\n"); printf("-file=<filename>: filename containing a matrix in MM format\n"); printf("-device=<device_id> : <device_id> if want to run on specific GPU\n"); exit(0); } int linearSolverCHOL(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { int bufferSize = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; int h_info = 0; double start, stop; double time_solve; cublasFillMode_t uplo = CUBLAS_FILL_MODE_LOWER; checkCudaErrors(cusolverDnDpotrf_bufferSize(handle, uplo, n, (double *)Acopy, lda, &bufferSize)); checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors( cusolverDnDpotrf(handle, uplo, n, A, lda, buffer, bufferSize, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: Cholesky factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cusolverDnDpotrs(handle, uplo, n, 1, A, lda, x, n, info)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: cholesky = %10.6f sec\n", time_solve); if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } return 0; } int linearSolverLU(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { int bufferSize = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; int *ipiv = NULL; int h_info = 0; double start, stop; double time_solve; checkCudaErrors(cusolverDnDgetrf_bufferSize(handle, n, n, (double *)Acopy, lda, &bufferSize)); checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors(cudaMalloc(&ipiv, sizeof(int) * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors(cusolverDnDgetrf(handle, n, n, A, lda, buffer, ipiv, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: LU factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors( cusolverDnDgetrs(handle, CUBLAS_OP_N, n, 1, A, lda, ipiv, x, n, info)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: LU = %10.6f sec\n", time_solve); if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } if (ipiv) { checkCudaErrors(cudaFree(ipiv)); } return 0; } int linearSolverQR(cusolverDnHandle_t handle, int n, const double *Acopy, int lda, const double *b, double *x) { cublasHandle_t cublasHandle = NULL; int bufferSize = 0; int bufferSize_geqrf = 0; int bufferSize_ormqr = 0; int *info = NULL; double *buffer = NULL; double *A = NULL; double *tau = NULL; int h_info = 0; double start, stop; double time_solve; const double one = 1.0; checkCudaErrors(cublasCreate(&cublasHandle)); checkCudaErrors(cusolverDnDgeqrf_bufferSize(handle, n, n, (double *)Acopy, lda, &bufferSize_geqrf)); checkCudaErrors(cusolverDnDormqr_bufferSize(handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_T, n, 1, n, A, lda, NULL, x, n, &bufferSize_ormqr)); printf("buffer_geqrf = %d, buffer_ormqr = %d \n", bufferSize_geqrf, bufferSize_ormqr); bufferSize = (bufferSize_geqrf > bufferSize_ormqr) ? bufferSize_geqrf : bufferSize_ormqr; checkCudaErrors(cudaMalloc(&info, sizeof(int))); checkCudaErrors(cudaMalloc(&buffer, sizeof(double) * bufferSize)); checkCudaErrors(cudaMalloc(&A, sizeof(double) * lda * n)); checkCudaErrors(cudaMalloc((void **)&tau, sizeof(double) * n)); checkCudaErrors( cudaMemcpy(A, Acopy, sizeof(double) * lda * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cudaMemset(info, 0, sizeof(int))); start = second(); start = second(); checkCudaErrors( cusolverDnDgeqrf(handle, n, n, A, lda, tau, buffer, bufferSize, info)); checkCudaErrors( cudaMemcpy(&h_info, info, sizeof(int), cudaMemcpyDeviceToHost)); if (0 != h_info) { fprintf(stderr, "Error: LU factorization failed\n"); } checkCudaErrors( cudaMemcpy(x, b, sizeof(double) * n, cudaMemcpyDeviceToDevice)); checkCudaErrors(cusolverDnDormqr(handle, CUBLAS_SIDE_LEFT, CUBLAS_OP_T, n, 1, n, A, lda, tau, x, n, buffer, bufferSize, info)); checkCudaErrors(cublasDtrsm(cublasHandle, CUBLAS_SIDE_LEFT, CUBLAS_FILL_MODE_UPPER, CUBLAS_OP_N, CUBLAS_DIAG_NON_UNIT, n, 1, &one, A, lda, x, n)); checkCudaErrors(cudaDeviceSynchronize()); stop = second(); time_solve = stop - start; fprintf(stdout, "timing: QR = %10.6f sec\n", time_solve); if (cublasHandle) { checkCudaErrors(cublasDestroy(cublasHandle)); } if (info) { checkCudaErrors(cudaFree(info)); } if (buffer) { checkCudaErrors(cudaFree(buffer)); } if (A) { checkCudaErrors(cudaFree(A)); } if (tau) { checkCudaErrors(cudaFree(tau)); } return 0; } void parseCommandLineArguments(int argc, char *argv[], struct testOpts &opts) { memset(&opts, 0, sizeof(opts)); if (checkCmdLineFlag(argc, (const char **)argv, "-h")) { UsageDN(); } if (checkCmdLineFlag(argc, (const char **)argv, "R")) { char *solverType = NULL; getCmdLineArgumentString(argc, (const char **)argv, "R", &solverType); if (solverType) { if ((STRCASECMP(solverType, "chol") != 0) && (STRCASECMP(solverType, "lu") != 0) && (STRCASECMP(solverType, "qr") != 0)) { printf("\nIncorrect argument passed to -R option\n"); UsageDN(); } else { opts.testFunc = solverType; } } } if (checkCmdLineFlag(argc, (const char **)argv, "file")) { char *fileName = 0; getCmdLineArgumentString(argc, (const char **)argv, "file", &fileName); if (fileName) { opts.sparse_mat_filename = fileName; } else { printf("\nIncorrect filename passed to -file \n "); UsageDN(); } } if (checkCmdLineFlag(argc, (const char **)argv, "lda")) { opts.lda = getCmdLineArgumentInt(argc, (const char **)argv, "lda"); } }
int main(int argc, char *argv[]) { struct testOpts opts; cusolverDnHandle_t handle = NULL; cublasHandle_t cublasHandle = NULL; cudaStream_t stream = NULL; int rowsA = 0; int colsA = 0; int nnzA = 0; int baseA = 0; int lda = 0; int *h_csrRowPtrA = NULL; int *h_csrColIndA = NULL; double *h_csrValA = NULL; double *h_A = NULL; double *h_x = NULL; double *h_b = NULL; double *h_r = NULL; double *d_A = NULL; double *d_x = NULL; double *d_b = NULL; double *d_r = NULL; const double minus_one = -1.0; const double one = 1.0; double x_inf = 0.0; double r_inf = 0.0; double A_inf = 0.0; int errors = 0; parseCommandLineArguments(argc, argv, opts); if (NULL == opts.testFunc) { opts.testFunc = "chol"; } findCudaDevice(argc, (const char **)argv); printf("step 1: read matrix market format\n"); if (opts.sparse_mat_filename == NULL) { opts.sparse_mat_filename = sdkFindFilePath("gr_900_900_crg.mtx", argv[0]); if (opts.sparse_mat_filename != NULL) printf("Using default input file [%s]\n", opts.sparse_mat_filename); else printf("Could not find gr_900_900_crg.mtx\n"); } else { printf("Using input file [%s]\n", opts.sparse_mat_filename); } if (opts.sparse_mat_filename == NULL) { fprintf(stderr, "Error: input matrix is not provided\n"); return EXIT_FAILURE; } if (loadMMSparseMatrix<double>(opts.sparse_mat_filename, 'd', true, &rowsA, &colsA, &nnzA, &h_csrValA, &h_csrRowPtrA, &h_csrColIndA, true)) { exit(EXIT_FAILURE); } baseA = h_csrRowPtrA[0]; printf("sparse matrix A is %d x %d with %d nonzeros, base=%d\n", rowsA, colsA, nnzA, baseA); if (rowsA != colsA) { fprintf(stderr, "Error: only support square matrix\n"); exit(EXIT_FAILURE); } printf("step 2: convert CSR(A) to dense matrix\n"); lda = opts.lda ? opts.lda : rowsA; if (lda < rowsA) { fprintf(stderr, "Error: lda must be greater or equal to dimension of A\n"); exit(EXIT_FAILURE); } h_A = (double *)malloc(sizeof(double) * lda * colsA); h_x = (double *)malloc(sizeof(double) * colsA); h_b = (double *)malloc(sizeof(double) * rowsA); h_r = (double *)malloc(sizeof(double) * rowsA); assert(NULL != h_A); assert(NULL != h_x); assert(NULL != h_b); assert(NULL != h_r); memset(h_A, 0, sizeof(double) * lda * colsA); for (int row = 0; row < rowsA; row++) { const int start = h_csrRowPtrA[row] - baseA; const int end = h_csrRowPtrA[row + 1] - baseA; for (int colidx = start; colidx < end; colidx++) { const int col = h_csrColIndA[colidx] - baseA; const double Areg = h_csrValA[colidx]; h_A[row + col * lda] = Areg; } } printf("step 3: set right hand side vector (b) to 1\n"); for (int row = 0; row < rowsA; row++) { h_b[row] = 1.0; } if (0 == strcmp(opts.testFunc, "chol")) { int issym = 1; for (int j = 0; j < colsA; j++) { for (int i = j; i < rowsA; i++) { double Aij = h_A[i + j * lda]; double Aji = h_A[j + i * lda]; if (Aij != Aji) { issym = 0; break; } } } if (!issym) { printf("Error: A has no symmetric pattern, please use LU or QR \n"); exit(EXIT_FAILURE); } } checkCudaErrors(cusolverDnCreate(&handle)); checkCudaErrors(cublasCreate(&cublasHandle)); checkCudaErrors(cudaStreamCreate(&stream)); checkCudaErrors(cusolverDnSetStream(handle, stream)); checkCudaErrors(cublasSetStream(cublasHandle, stream)); checkCudaErrors(cudaMalloc((void **)&d_A, sizeof(double) * lda * colsA)); checkCudaErrors(cudaMalloc((void **)&d_x, sizeof(double) * colsA)); checkCudaErrors(cudaMalloc((void **)&d_b, sizeof(double) * rowsA)); checkCudaErrors(cudaMalloc((void **)&d_r, sizeof(double) * rowsA)); printf("step 4: prepare data on device\n"); checkCudaErrors(cudaMemcpy(d_A, h_A, sizeof(double) * lda * colsA, cudaMemcpyHostToDevice)); checkCudaErrors( cudaMemcpy(d_b, h_b, sizeof(double) * rowsA, cudaMemcpyHostToDevice)); printf("step 5: solve A*x = b \n"); if (0 == strcmp(opts.testFunc, "chol")) { linearSolverCHOL(handle, rowsA, d_A, lda, d_b, d_x); } else if (0 == strcmp(opts.testFunc, "lu")) { linearSolverLU(handle, rowsA, d_A, lda, d_b, d_x); } else if (0 == strcmp(opts.testFunc, "qr")) { linearSolverQR(handle, rowsA, d_A, lda, d_b, d_x); } else { fprintf(stderr, "Error: %s is unknown function\n", opts.testFunc); exit(EXIT_FAILURE); } printf("step 6: evaluate residual\n"); checkCudaErrors( cudaMemcpy(d_r, d_b, sizeof(double) * rowsA, cudaMemcpyDeviceToDevice)); checkCudaErrors(cublasDgemm_v2(cublasHandle, CUBLAS_OP_N, CUBLAS_OP_N, rowsA, 1, colsA, &minus_one, d_A, lda, d_x, rowsA, &one, d_r, rowsA)); checkCudaErrors( cudaMemcpy(h_x, d_x, sizeof(double) * colsA, cudaMemcpyDeviceToHost)); checkCudaErrors( cudaMemcpy(h_r, d_r, sizeof(double) * rowsA, cudaMemcpyDeviceToHost)); x_inf = vec_norminf(colsA, h_x); r_inf = vec_norminf(rowsA, h_r); A_inf = mat_norminf(rowsA, colsA, h_A, lda); printf("|b - A*x| = %E \n", r_inf); printf("|A| = %E \n", A_inf); printf("|x| = %E \n", x_inf); printf("|b - A*x|/(|A|*|x|) = %E \n", r_inf / (A_inf * x_inf)); if (handle) { checkCudaErrors(cusolverDnDestroy(handle)); } if (cublasHandle) { checkCudaErrors(cublasDestroy(cublasHandle)); } if (stream) { checkCudaErrors(cudaStreamDestroy(stream)); } if (h_csrValA) { free(h_csrValA); } if (h_csrRowPtrA) { free(h_csrRowPtrA); } if (h_csrColIndA) { free(h_csrColIndA); } if (h_A) { free(h_A); } if (h_x) { free(h_x); } if (h_b) { free(h_b); } if (h_r) { free(h_r); } if (d_A) { checkCudaErrors(cudaFree(d_A)); } if (d_x) { checkCudaErrors(cudaFree(d_x)); } if (d_b) { checkCudaErrors(cudaFree(d_b)); } if (d_r) { checkCudaErrors(cudaFree(d_r)); } return 0; }
function_block-full_function
[ { "content": "// structure defining the properties of a single buffer\n\nstruct bufferConfig {\n\n string name;\n\n GLenum format;\n\n int bits;\n\n};\n\n\n", "file_path": "Common/rendercheck_gl.h", "rank": 0, "score": 201948.48625693982 }, { "content": "class ArrayFileWriter<int> {\n\n p...
C++
common/sockets.cpp
kkamagui/TPM2.0-TSS
106e914dd285f1b152c127f1cad564744596cf2f
#include <tcti/tcti_socket.h> #include "debug.h" #include "sockets.h" #ifndef _WIN32 void WSACleanup() {} int WSAGetLastError() { return errno; } #endif void CloseSockets( SOCKET otherSock, SOCKET tpmSock) { closesocket(otherSock); closesocket(tpmSock); } TSS2_RC recvBytes( SOCKET tpmSock, unsigned char *data, int len ) { int iResult = 0; int length; int bytesRead; for( bytesRead = 0, length = len; bytesRead != len; length -= iResult, bytesRead += iResult ) { iResult = recv( tpmSock, (char *)&( data[bytesRead] ), length, 0); if ((iResult == SOCKET_ERROR) || (!iResult)) return TSS2_TCTI_RC_IO_ERROR; } return TSS2_RC_SUCCESS; } TSS2_RC sendBytes( SOCKET tpmSock, const unsigned char *data, int len ) { int iResult = 0; int sentLength = 0; for( sentLength = 0; sentLength < len; len -= iResult, sentLength += iResult ) { iResult = send( tpmSock, (char *)data, len, MSG_NOSIGNAL ); if (iResult == SOCKET_ERROR) return TSS2_TCTI_RC_IO_ERROR; } return TSS2_RC_SUCCESS; } #define SAFE_CALL(func, ...) (func != NULL) ? func(__VA_ARGS__) : 0 int InitSockets( const char *hostName, UINT16 port, UINT8 serverSockets, SOCKET *otherSock, SOCKET *tpmSock, TCTI_LOG_CALLBACK debugfunc, void* data ) { sockaddr_in otherService; sockaddr_in tpmService; int iResult = 0; #ifdef _WIN32 WSADATA wsaData = {0}; static UINT8 socketsEnabled = 0; if( socketsEnabled == 0 ) { iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { SAFE_CALL( debugfunc, data, NO_PREFIX, "WSAStartup failed: %d\n", iResult); return 1; } socketsEnabled = 1; } #endif *otherSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (*otherSock == INVALID_SOCKET) { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket creation failed with error = %d\n", WSAGetLastError() ); return(1); } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket created: 0x%x\n", *otherSock ); otherService.sin_family = AF_INET; otherService.sin_addr.s_addr = inet_addr( hostName ); otherService.sin_port = htons(port + 1); if( serverSockets ) { iResult = bind(*otherSock, (SOCKADDR *) &otherService, sizeof (otherService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind failed with error %u\n", WSAGetLastError()); closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind to IP address:port: %s:%d\n", hostName, port + 1 ); } iResult = listen( *otherSock, 4 ); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "listen failed with error %u\n", WSAGetLastError()); closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Other CMD server listening to socket: 0x%x\n", *otherSock ); } } } *tpmSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (*tpmSock == INVALID_SOCKET) { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket creation failed with error = %d\n", WSAGetLastError() ); closesocket( *otherSock ); return(1); } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket created: 0x%x\n", *tpmSock ); tpmService.sin_family = AF_INET; tpmService.sin_addr.s_addr = inet_addr( hostName ); tpmService.sin_port = htons( port ); if( serverSockets ) { iResult = bind(*tpmSock, (SOCKADDR *) &tpmService, sizeof (tpmService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind failed with error %u\n", WSAGetLastError()); closesocket(*tpmSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind to IP address:port: %s:%d\n", hostName, port ); } iResult = listen( *tpmSock, 4 ); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "listen failed with error %u\n", WSAGetLastError()); closesocket(*tpmSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "TPM CMD server listening to socket: 0x%x\n", *tpmSock ); } } } if( !serverSockets ) { iResult = connect(*otherSock, (SOCKADDR *) &otherService, sizeof (otherService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "connect function failed with error: %d\n", WSAGetLastError() ); iResult = closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Client connected to server on port: %d\n", port + 1 ); } iResult = connect(*tpmSock, (SOCKADDR *) &tpmService, sizeof (tpmService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "connect function failed with error: %d\n", WSAGetLastError() ); iResult = closesocket(*otherSock); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "closesocket function failed with error: %d\n", WSAGetLastError() ); } WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Client connected to server on port: %d\n", port ); } } return 0; }
#include <tcti/tcti_socket.h> #include "debug.h" #include "sockets.h" #ifndef _WIN32 void WSACleanup() {} int WSAGetLastError() { return errno; } #endif void CloseSockets( SOCKET otherSock, SOCKET tpmSock) { closesocket(otherSock); closesocket(tpmSock); } TSS2_RC recvBytes( SOCKET tpmSock, unsigned char *data, int len ) { int iResult = 0; int length; int bytesRead; for( bytesRead = 0, length = len; bytesRead != len; length -= iResult, bytesRead += iResult ) { iResult = recv( tpmSock, (char *)&( data[bytesRead] ), length, 0); if ((iResult == SOCKET_ERROR) || (!iResult)) return TSS2_TCTI_RC_IO_ERROR; } return TSS2_RC_SUCCESS; } TSS2_RC sendBytes( SOCKET tpmSock, const unsigned char *data, int len ) { int iResult = 0; int sentLength = 0; for( sentLength = 0; sentLength < len; len -= iResult, sentLength += iResult ) { iResult = send( tpmSock, (char *)data, len, MSG_NOSIGNAL ); if (iResult == SOCKET_ERROR) return TSS2_TCTI_RC_IO_ERROR; } return TSS2_RC_SUCCESS; } #define SAFE_CALL(func, ...) (func != NULL) ? func(__VA_ARGS__) : 0 int InitSockets( const char *hostName, UINT16 port, UINT8 serverSockets, SOCKET *otherSock, SOCKET *tpmSock, TCTI_LOG_CALLBACK debugfunc, void* data ) { sockaddr_in otherService; sockaddr_in tpmService; int iResult = 0; #ifdef _WIN32 WSADATA wsaData = {0}; static UINT8 socketsEnabled = 0; if( socketsEnabled == 0 ) { iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { SAFE_CALL( debugfunc, data, NO_PREFIX, "WSAStartup failed: %d\n", iResult); return 1; } socketsEnabled = 1; } #endif *otherSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (*otherSock == INVALID_SOCKET) { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket creation failed with error = %d\n", WSAGetLastError() ); return(1); } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket created: 0x%x\n", *otherSock ); otherService.sin_family = AF_INET; otherService.sin_addr.s_addr = inet_addr( hostName ); otherService.sin_port = htons(port + 1); if( serverSockets ) { iResult = bind(*otherSock, (SOCKADDR *) &otherService, sizeof (otherService));
bind to IP address:port: %s:%d\n", hostName, port + 1 ); } iResult = listen( *otherSock, 4 ); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "listen failed with error %u\n", WSAGetLastError()); closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Other CMD server listening to socket: 0x%x\n", *otherSock ); } } } *tpmSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (*tpmSock == INVALID_SOCKET) { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket creation failed with error = %d\n", WSAGetLastError() ); closesocket( *otherSock ); return(1); } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "socket created: 0x%x\n", *tpmSock ); tpmService.sin_family = AF_INET; tpmService.sin_addr.s_addr = inet_addr( hostName ); tpmService.sin_port = htons( port ); if( serverSockets ) { iResult = bind(*tpmSock, (SOCKADDR *) &tpmService, sizeof (tpmService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind failed with error %u\n", WSAGetLastError()); closesocket(*tpmSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind to IP address:port: %s:%d\n", hostName, port ); } iResult = listen( *tpmSock, 4 ); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "listen failed with error %u\n", WSAGetLastError()); closesocket(*tpmSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "TPM CMD server listening to socket: 0x%x\n", *tpmSock ); } } } if( !serverSockets ) { iResult = connect(*otherSock, (SOCKADDR *) &otherService, sizeof (otherService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "connect function failed with error: %d\n", WSAGetLastError() ); iResult = closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Client connected to server on port: %d\n", port + 1 ); } iResult = connect(*tpmSock, (SOCKADDR *) &tpmService, sizeof (tpmService)); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "connect function failed with error: %d\n", WSAGetLastError() ); iResult = closesocket(*otherSock); if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "closesocket function failed with error: %d\n", WSAGetLastError() ); } WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "Client connected to server on port: %d\n", port ); } } return 0; }
if (iResult == SOCKET_ERROR) { SAFE_CALL( debugfunc, data, NO_PREFIX, "bind failed with error %u\n", WSAGetLastError()); closesocket(*otherSock); WSACleanup(); return 1; } else { SAFE_CALL( debugfunc, data, NO_PREFIX, "
function_block-random_span
[ { "content": " uint16_t port;\n", "file_path": "include/tcti/tcti_socket.h", "rank": 0, "score": 158306.02717439883 }, { "content": " const char *hostname;\n", "file_path": "include/tcti/tcti_socket.h", "rank": 1, "score": 127279.91855985833 }, { "content": " voi...
C++
src/add-ons/media/media-add-ons/dvb/DVBCard.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <errno.h> #include <OS.h> #include "DVBCard.h" DVBCard::DVBCard(const char *path) : fInitStatus(B_OK) , fDev(-1) { printf("DVBCard opening %s\n", path); fDev = open(path, O_RDWR); if (fDev < 0) { printf("DVBCard opening %s failed\n", path); fInitStatus = B_ERROR; return; } dvb_frequency_info_t info; if (do_ioctl(fDev, DVB_GET_FREQUENCY_INFO, &info) < 0) { printf("DVB_GET_FREQUENCY_INFO failed with error %s\n", strerror(errno)); } fFreqMin = info.frequency_min; fFreqMax = info.frequency_max; fFreqStep = info.frequency_step; fCaptureActive = false; } DVBCard::~DVBCard() { if (fDev > 0) close(fDev); } status_t DVBCard::InitCheck() { return fInitStatus; } status_t DVBCard::GetCardType(dvb_type_t *type) { dvb_interface_info_t info; if (do_ioctl(fDev, DVB_GET_INTERFACE_INFO, &info) < 0) { printf("DVB_GET_INTERFACE_INFO failed with error %s\n", strerror(errno)); return errno; } if (info.version < 1) { printf("DVBCard::GetCardInfo wrong API version\n"); return B_ERROR; } *type = info.type; return B_OK; } status_t DVBCard::GetCardInfo(char *_name, int max_name_len, char *_info, int max_info_len) { dvb_interface_info_t info; if (do_ioctl(fDev, DVB_GET_INTERFACE_INFO, &info) < 0) { printf("DVB_GET_INTERFACE_INFO failed with error %s\n", strerror(errno)); return errno; } strcpy(_name, info.name); strcpy(_info, info.info); if (info.version < 1) { printf("DVBCard::GetCardInfo wrong API version\n"); return B_ERROR; } return B_OK; } status_t DVBCard::SetTuningParameter(const dvb_tuning_parameters_t& param) { if (fDev < 0) return B_NO_INIT; printf("DVBCard::SetTuningParameter:\n"); params = param; if (ioctl(fDev, DVB_SET_TUNING_PARAMETERS, (void *)(&param)) < 0) { printf("DVB_SET_TUNING_PARAMETERS failed with error %s\n", strerror(errno)); return errno; } dvb_status_t status; bigtime_t start = system_time(); bool has_lock = false; bool has_signal = false; bool has_carrier = false; do { if (do_ioctl(fDev, DVB_GET_STATUS, &status) < 0) { printf("DVB_GET_STATUS failed with error %s\n", strerror(errno)); return errno; } if (!has_signal && status & DVB_STATUS_SIGNAL) { has_signal = true; printf("got signal after %.6f\n", (system_time() - start) / 1e6); } if (!has_carrier && status & DVB_STATUS_CARRIER) { has_carrier = true; printf("got carrier after %.6f\n", (system_time() - start) / 1e6); } if (!has_lock && status & DVB_STATUS_LOCK) { has_lock = true; printf("got lock after %.6f\n", (system_time() - start) / 1e6); } if ((status & (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) == (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) break; snooze(25000); } while ((system_time() - start) < 5000000); if ((status & (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) != (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) { printf("DVB tuning failed! need these status flags: DVB_STATUS_SIGNAL, DVB_STATUS_CARRIER, DVB_STATUS_LOCK\n"); return B_ERROR; } return B_OK; } status_t DVBCard::GetTuningParameter(dvb_tuning_parameters_t *param) { *param = params; return B_OK; } status_t DVBCard::GetSignalInfo(uint32 *ss, uint32 *ber, uint32 *snr) { if (do_ioctl(fDev, DVB_GET_SS, ss) < 0) { printf("DVB_GET_SS failed with error %s\n", strerror(errno)); return errno; } if (do_ioctl(fDev, DVB_GET_BER, ber) < 0) { printf("DVB_GET_BER failed with error %s\n", strerror(errno)); return errno; } if (do_ioctl(fDev, DVB_GET_SNR, snr) < 0) { printf("DVB_GET_SNR failed with error %s\n", strerror(errno)); return errno; } printf("ss %08lx, ber %08lx, snr %08lx\n", *ss, *ber, *snr); printf("ss %lu%%, ber %lu%%, snr %lu%%\n", *ss / (0xffffffff / 100), *ber / (0xffffffff / 100), *snr / (0xffffffff / 100)); return B_OK; } status_t DVBCard::CaptureStart() { printf("DVBCard::CaptureStart\n"); if (fCaptureActive) { printf("CaptureStart already called, doing nothing\n"); return B_OK; } if (do_ioctl(fDev, DVB_START_CAPTURE, 0) < 0) { printf("DVB_START_CAPTURE failed with error %s\n", strerror(errno)); return errno; } fCaptureActive = true; return B_OK; } status_t DVBCard::CaptureStop() { printf("DVBCard::CaptureStop\n"); if (!fCaptureActive) { printf("CaptureStop already called, doing nothing\n"); return B_OK; } if (do_ioctl(fDev, DVB_STOP_CAPTURE, 0) < 0) { printf("DVB_STOP_CAPTURE failed with error %s\n", strerror(errno)); return errno; } fCaptureActive = false; return B_OK; } status_t DVBCard::Capture(void **data, size_t *size, bigtime_t *end_time) { dvb_capture_t cap; if (ioctl(fDev, DVB_CAPTURE, &cap) < 0) return errno; *data = cap.data; *size = cap.size; *end_time = cap.end_time; return B_OK; } int DVBCard::do_ioctl(int fDev, ulong op, void *arg) { int res = 0; int i; for (i = 0; i < 20; i++) { res = ioctl(fDev, op, arg); if (res >= 0) break; } if (i != 0) printf("ioctl %lx repeated %d times\n", op, i); return res; }
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <errno.h> #include <OS.h> #include "DVBCard.h" DVBCard::DVBCard(const char *path) : fInitStatus(B_OK) , fDev(-1) { printf("DVBCard opening %s\n", path); fDev = open(path, O_RDWR); if (fDev < 0) { printf("DVBCard opening %s failed\n", path); fInitStatus = B_ERROR; return; } dvb_frequency_info_t info; if (do_ioctl(fDev, DVB_GET_FREQUENCY_INFO, &info) < 0) { printf("DVB_GET_FREQUENCY_INFO failed with error %s\n", strerror(errno)); } fFreqMin = info.frequency_min; fFreqMax = info.frequency_max; fFreqStep = info.frequency_step; fCaptureActive = false; } DVBCard::~DVBCard() { if (fDev > 0) close(fDev); } status_t DVBCard::InitCheck() { return fInitStatus; } status_t DVBCard::GetCardType(dvb_type_t *ty
return B_OK; } int DVBCard::do_ioctl(int fDev, ulong op, void *arg) { int res = 0; int i; for (i = 0; i < 20; i++) { res = ioctl(fDev, op, arg); if (res >= 0) break; } if (i != 0) printf("ioctl %lx repeated %d times\n", op, i); return res; }
pe) { dvb_interface_info_t info; if (do_ioctl(fDev, DVB_GET_INTERFACE_INFO, &info) < 0) { printf("DVB_GET_INTERFACE_INFO failed with error %s\n", strerror(errno)); return errno; } if (info.version < 1) { printf("DVBCard::GetCardInfo wrong API version\n"); return B_ERROR; } *type = info.type; return B_OK; } status_t DVBCard::GetCardInfo(char *_name, int max_name_len, char *_info, int max_info_len) { dvb_interface_info_t info; if (do_ioctl(fDev, DVB_GET_INTERFACE_INFO, &info) < 0) { printf("DVB_GET_INTERFACE_INFO failed with error %s\n", strerror(errno)); return errno; } strcpy(_name, info.name); strcpy(_info, info.info); if (info.version < 1) { printf("DVBCard::GetCardInfo wrong API version\n"); return B_ERROR; } return B_OK; } status_t DVBCard::SetTuningParameter(const dvb_tuning_parameters_t& param) { if (fDev < 0) return B_NO_INIT; printf("DVBCard::SetTuningParameter:\n"); params = param; if (ioctl(fDev, DVB_SET_TUNING_PARAMETERS, (void *)(&param)) < 0) { printf("DVB_SET_TUNING_PARAMETERS failed with error %s\n", strerror(errno)); return errno; } dvb_status_t status; bigtime_t start = system_time(); bool has_lock = false; bool has_signal = false; bool has_carrier = false; do { if (do_ioctl(fDev, DVB_GET_STATUS, &status) < 0) { printf("DVB_GET_STATUS failed with error %s\n", strerror(errno)); return errno; } if (!has_signal && status & DVB_STATUS_SIGNAL) { has_signal = true; printf("got signal after %.6f\n", (system_time() - start) / 1e6); } if (!has_carrier && status & DVB_STATUS_CARRIER) { has_carrier = true; printf("got carrier after %.6f\n", (system_time() - start) / 1e6); } if (!has_lock && status & DVB_STATUS_LOCK) { has_lock = true; printf("got lock after %.6f\n", (system_time() - start) / 1e6); } if ((status & (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) == (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) break; snooze(25000); } while ((system_time() - start) < 5000000); if ((status & (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) != (DVB_STATUS_SIGNAL|DVB_STATUS_CARRIER|DVB_STATUS_LOCK)) { printf("DVB tuning failed! need these status flags: DVB_STATUS_SIGNAL, DVB_STATUS_CARRIER, DVB_STATUS_LOCK\n"); return B_ERROR; } return B_OK; } status_t DVBCard::GetTuningParameter(dvb_tuning_parameters_t *param) { *param = params; return B_OK; } status_t DVBCard::GetSignalInfo(uint32 *ss, uint32 *ber, uint32 *snr) { if (do_ioctl(fDev, DVB_GET_SS, ss) < 0) { printf("DVB_GET_SS failed with error %s\n", strerror(errno)); return errno; } if (do_ioctl(fDev, DVB_GET_BER, ber) < 0) { printf("DVB_GET_BER failed with error %s\n", strerror(errno)); return errno; } if (do_ioctl(fDev, DVB_GET_SNR, snr) < 0) { printf("DVB_GET_SNR failed with error %s\n", strerror(errno)); return errno; } printf("ss %08lx, ber %08lx, snr %08lx\n", *ss, *ber, *snr); printf("ss %lu%%, ber %lu%%, snr %lu%%\n", *ss / (0xffffffff / 100), *ber / (0xffffffff / 100), *snr / (0xffffffff / 100)); return B_OK; } status_t DVBCard::CaptureStart() { printf("DVBCard::CaptureStart\n"); if (fCaptureActive) { printf("CaptureStart already called, doing nothing\n"); return B_OK; } if (do_ioctl(fDev, DVB_START_CAPTURE, 0) < 0) { printf("DVB_START_CAPTURE failed with error %s\n", strerror(errno)); return errno; } fCaptureActive = true; return B_OK; } status_t DVBCard::CaptureStop() { printf("DVBCard::CaptureStop\n"); if (!fCaptureActive) { printf("CaptureStop already called, doing nothing\n"); return B_OK; } if (do_ioctl(fDev, DVB_STOP_CAPTURE, 0) < 0) { printf("DVB_STOP_CAPTURE failed with error %s\n", strerror(errno)); return errno; } fCaptureActive = false; return B_OK; } status_t DVBCard::Capture(void **data, size_t *size, bigtime_t *end_time) { dvb_capture_t cap; if (ioctl(fDev, DVB_CAPTURE, &cap) < 0) return errno; *data = cap.data; *size = cap.size; *end_time = cap.end_time;
random
[]
C++
cpdp/src/v20190820/model/CreateInvoiceItem.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
#include <tencentcloud/cpdp/v20190820/model/CreateInvoiceItem.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cpdp::V20190820::Model; using namespace rapidjson; using namespace std; CreateInvoiceItem::CreateInvoiceItem() : m_nameHasBeenSet(false), m_taxCodeHasBeenSet(false), m_totalPriceHasBeenSet(false), m_taxRateHasBeenSet(false), m_taxAmountHasBeenSet(false), m_taxTypeHasBeenSet(false), m_modelsHasBeenSet(false), m_unitHasBeenSet(false), m_totalHasBeenSet(false), m_priceHasBeenSet(false), m_discountHasBeenSet(false), m_preferentialPolicyFlagHasBeenSet(false), m_zeroTaxFlagHasBeenSet(false), m_vatSpecialManagementHasBeenSet(false) { } CoreInternalOutcome CreateInvoiceItem::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Name") && !value["Name"].IsNull()) { if (!value["Name"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Name` IsString=false incorrectly").SetRequestId(requestId)); } m_name = string(value["Name"].GetString()); m_nameHasBeenSet = true; } if (value.HasMember("TaxCode") && !value["TaxCode"].IsNull()) { if (!value["TaxCode"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxCode` IsString=false incorrectly").SetRequestId(requestId)); } m_taxCode = string(value["TaxCode"].GetString()); m_taxCodeHasBeenSet = true; } if (value.HasMember("TotalPrice") && !value["TotalPrice"].IsNull()) { if (!value["TotalPrice"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TotalPrice` IsInt64=false incorrectly").SetRequestId(requestId)); } m_totalPrice = value["TotalPrice"].GetInt64(); m_totalPriceHasBeenSet = true; } if (value.HasMember("TaxRate") && !value["TaxRate"].IsNull()) { if (!value["TaxRate"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxRate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_taxRate = value["TaxRate"].GetInt64(); m_taxRateHasBeenSet = true; } if (value.HasMember("TaxAmount") && !value["TaxAmount"].IsNull()) { if (!value["TaxAmount"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxAmount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_taxAmount = value["TaxAmount"].GetInt64(); m_taxAmountHasBeenSet = true; } if (value.HasMember("TaxType") && !value["TaxType"].IsNull()) { if (!value["TaxType"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxType` IsString=false incorrectly").SetRequestId(requestId)); } m_taxType = string(value["TaxType"].GetString()); m_taxTypeHasBeenSet = true; } if (value.HasMember("Models") && !value["Models"].IsNull()) { if (!value["Models"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Models` IsString=false incorrectly").SetRequestId(requestId)); } m_models = string(value["Models"].GetString()); m_modelsHasBeenSet = true; } if (value.HasMember("Unit") && !value["Unit"].IsNull()) { if (!value["Unit"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Unit` IsString=false incorrectly").SetRequestId(requestId)); } m_unit = string(value["Unit"].GetString()); m_unitHasBeenSet = true; } if (value.HasMember("Total") && !value["Total"].IsNull()) { if (!value["Total"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Total` IsString=false incorrectly").SetRequestId(requestId)); } m_total = string(value["Total"].GetString()); m_totalHasBeenSet = true; } if (value.HasMember("Price") && !value["Price"].IsNull()) { if (!value["Price"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Price` IsString=false incorrectly").SetRequestId(requestId)); } m_price = string(value["Price"].GetString()); m_priceHasBeenSet = true; } if (value.HasMember("Discount") && !value["Discount"].IsNull()) { if (!value["Discount"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Discount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_discount = value["Discount"].GetInt64(); m_discountHasBeenSet = true; } if (value.HasMember("PreferentialPolicyFlag") && !value["PreferentialPolicyFlag"].IsNull()) { if (!value["PreferentialPolicyFlag"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.PreferentialPolicyFlag` IsString=false incorrectly").SetRequestId(requestId)); } m_preferentialPolicyFlag = string(value["PreferentialPolicyFlag"].GetString()); m_preferentialPolicyFlagHasBeenSet = true; } if (value.HasMember("ZeroTaxFlag") && !value["ZeroTaxFlag"].IsNull()) { if (!value["ZeroTaxFlag"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.ZeroTaxFlag` IsString=false incorrectly").SetRequestId(requestId)); } m_zeroTaxFlag = string(value["ZeroTaxFlag"].GetString()); m_zeroTaxFlagHasBeenSet = true; } if (value.HasMember("VatSpecialManagement") && !value["VatSpecialManagement"].IsNull()) { if (!value["VatSpecialManagement"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.VatSpecialManagement` IsString=false incorrectly").SetRequestId(requestId)); } m_vatSpecialManagement = string(value["VatSpecialManagement"].GetString()); m_vatSpecialManagementHasBeenSet = true; } return CoreInternalOutcome(true); } void CreateInvoiceItem::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_nameHasBeenSet) { Value iKey(kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_name.c_str(), allocator).Move(), allocator); } if (m_taxCodeHasBeenSet) { Value iKey(kStringType); string key = "TaxCode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_taxCode.c_str(), allocator).Move(), allocator); } if (m_totalPriceHasBeenSet) { Value iKey(kStringType); string key = "TotalPrice"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_totalPrice, allocator); } if (m_taxRateHasBeenSet) { Value iKey(kStringType); string key = "TaxRate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taxRate, allocator); } if (m_taxAmountHasBeenSet) { Value iKey(kStringType); string key = "TaxAmount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taxAmount, allocator); } if (m_taxTypeHasBeenSet) { Value iKey(kStringType); string key = "TaxType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_taxType.c_str(), allocator).Move(), allocator); } if (m_modelsHasBeenSet) { Value iKey(kStringType); string key = "Models"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_models.c_str(), allocator).Move(), allocator); } if (m_unitHasBeenSet) { Value iKey(kStringType); string key = "Unit"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_unit.c_str(), allocator).Move(), allocator); } if (m_totalHasBeenSet) { Value iKey(kStringType); string key = "Total"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_total.c_str(), allocator).Move(), allocator); } if (m_priceHasBeenSet) { Value iKey(kStringType); string key = "Price"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_price.c_str(), allocator).Move(), allocator); } if (m_discountHasBeenSet) { Value iKey(kStringType); string key = "Discount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_discount, allocator); } if (m_preferentialPolicyFlagHasBeenSet) { Value iKey(kStringType); string key = "PreferentialPolicyFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_preferentialPolicyFlag.c_str(), allocator).Move(), allocator); } if (m_zeroTaxFlagHasBeenSet) { Value iKey(kStringType); string key = "ZeroTaxFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_zeroTaxFlag.c_str(), allocator).Move(), allocator); } if (m_vatSpecialManagementHasBeenSet) { Value iKey(kStringType); string key = "VatSpecialManagement"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_vatSpecialManagement.c_str(), allocator).Move(), allocator); } } string CreateInvoiceItem::GetName() const { return m_name; } void CreateInvoiceItem::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool CreateInvoiceItem::NameHasBeenSet() const { return m_nameHasBeenSet; } string CreateInvoiceItem::GetTaxCode() const { return m_taxCode; } void CreateInvoiceItem::SetTaxCode(const string& _taxCode) { m_taxCode = _taxCode; m_taxCodeHasBeenSet = true; } bool CreateInvoiceItem::TaxCodeHasBeenSet() const { return m_taxCodeHasBeenSet; } int64_t CreateInvoiceItem::GetTotalPrice() const { return m_totalPrice; } void CreateInvoiceItem::SetTotalPrice(const int64_t& _totalPrice) { m_totalPrice = _totalPrice; m_totalPriceHasBeenSet = true; } bool CreateInvoiceItem::TotalPriceHasBeenSet() const { return m_totalPriceHasBeenSet; } int64_t CreateInvoiceItem::GetTaxRate() const { return m_taxRate; } void CreateInvoiceItem::SetTaxRate(const int64_t& _taxRate) { m_taxRate = _taxRate; m_taxRateHasBeenSet = true; } bool CreateInvoiceItem::TaxRateHasBeenSet() const { return m_taxRateHasBeenSet; } int64_t CreateInvoiceItem::GetTaxAmount() const { return m_taxAmount; } void CreateInvoiceItem::SetTaxAmount(const int64_t& _taxAmount) { m_taxAmount = _taxAmount; m_taxAmountHasBeenSet = true; } bool CreateInvoiceItem::TaxAmountHasBeenSet() const { return m_taxAmountHasBeenSet; } string CreateInvoiceItem::GetTaxType() const { return m_taxType; } void CreateInvoiceItem::SetTaxType(const string& _taxType) { m_taxType = _taxType; m_taxTypeHasBeenSet = true; } bool CreateInvoiceItem::TaxTypeHasBeenSet() const { return m_taxTypeHasBeenSet; } string CreateInvoiceItem::GetModels() const { return m_models; } void CreateInvoiceItem::SetModels(const string& _models) { m_models = _models; m_modelsHasBeenSet = true; } bool CreateInvoiceItem::ModelsHasBeenSet() const { return m_modelsHasBeenSet; } string CreateInvoiceItem::GetUnit() const { return m_unit; } void CreateInvoiceItem::SetUnit(const string& _unit) { m_unit = _unit; m_unitHasBeenSet = true; } bool CreateInvoiceItem::UnitHasBeenSet() const { return m_unitHasBeenSet; } string CreateInvoiceItem::GetTotal() const { return m_total; } void CreateInvoiceItem::SetTotal(const string& _total) { m_total = _total; m_totalHasBeenSet = true; } bool CreateInvoiceItem::TotalHasBeenSet() const { return m_totalHasBeenSet; } string CreateInvoiceItem::GetPrice() const { return m_price; } void CreateInvoiceItem::SetPrice(const string& _price) { m_price = _price; m_priceHasBeenSet = true; } bool CreateInvoiceItem::PriceHasBeenSet() const { return m_priceHasBeenSet; } int64_t CreateInvoiceItem::GetDiscount() const { return m_discount; } void CreateInvoiceItem::SetDiscount(const int64_t& _discount) { m_discount = _discount; m_discountHasBeenSet = true; } bool CreateInvoiceItem::DiscountHasBeenSet() const { return m_discountHasBeenSet; } string CreateInvoiceItem::GetPreferentialPolicyFlag() const { return m_preferentialPolicyFlag; } void CreateInvoiceItem::SetPreferentialPolicyFlag(const string& _preferentialPolicyFlag) { m_preferentialPolicyFlag = _preferentialPolicyFlag; m_preferentialPolicyFlagHasBeenSet = true; } bool CreateInvoiceItem::PreferentialPolicyFlagHasBeenSet() const { return m_preferentialPolicyFlagHasBeenSet; } string CreateInvoiceItem::GetZeroTaxFlag() const { return m_zeroTaxFlag; } void CreateInvoiceItem::SetZeroTaxFlag(const string& _zeroTaxFlag) { m_zeroTaxFlag = _zeroTaxFlag; m_zeroTaxFlagHasBeenSet = true; } bool CreateInvoiceItem::ZeroTaxFlagHasBeenSet() const { return m_zeroTaxFlagHasBeenSet; } string CreateInvoiceItem::GetVatSpecialManagement() const { return m_vatSpecialManagement; } void CreateInvoiceItem::SetVatSpecialManagement(const string& _vatSpecialManagement) { m_vatSpecialManagement = _vatSpecialManagement; m_vatSpecialManagementHasBeenSet = true; } bool CreateInvoiceItem::VatSpecialManagementHasBeenSet() const { return m_vatSpecialManagementHasBeenSet; }
#include <tencentcloud/cpdp/v20190820/model/CreateInvoiceItem.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cpdp::V20190820::Model; using namespace rapidjson; using namespace std; CreateInvoiceItem::CreateInvoiceItem() : m_nameHasBeenSet(false), m_taxCodeHasBeenSet(false), m_totalPriceHasBeenSet(false), m_taxRateHasBeenSet(false), m_taxAmountHasBeenSet(false), m_taxTypeHasBeenSet(false), m_modelsHasBeenSet(false), m_unitHasBeenSet(false), m_totalHasBeenSet(false), m_priceHasBeenSet(false), m_discountHasBeenSet(false), m_preferentialPolicyFlagHasBeenSet(false), m_zeroTaxFlagHasBeenSet(false), m_vatSpecialManagementHasBeenSet(false) { }
void CreateInvoiceItem::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_nameHasBeenSet) { Value iKey(kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_name.c_str(), allocator).Move(), allocator); } if (m_taxCodeHasBeenSet) { Value iKey(kStringType); string key = "TaxCode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_taxCode.c_str(), allocator).Move(), allocator); } if (m_totalPriceHasBeenSet) { Value iKey(kStringType); string key = "TotalPrice"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_totalPrice, allocator); } if (m_taxRateHasBeenSet) { Value iKey(kStringType); string key = "TaxRate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taxRate, allocator); } if (m_taxAmountHasBeenSet) { Value iKey(kStringType); string key = "TaxAmount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taxAmount, allocator); } if (m_taxTypeHasBeenSet) { Value iKey(kStringType); string key = "TaxType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_taxType.c_str(), allocator).Move(), allocator); } if (m_modelsHasBeenSet) { Value iKey(kStringType); string key = "Models"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_models.c_str(), allocator).Move(), allocator); } if (m_unitHasBeenSet) { Value iKey(kStringType); string key = "Unit"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_unit.c_str(), allocator).Move(), allocator); } if (m_totalHasBeenSet) { Value iKey(kStringType); string key = "Total"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_total.c_str(), allocator).Move(), allocator); } if (m_priceHasBeenSet) { Value iKey(kStringType); string key = "Price"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_price.c_str(), allocator).Move(), allocator); } if (m_discountHasBeenSet) { Value iKey(kStringType); string key = "Discount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_discount, allocator); } if (m_preferentialPolicyFlagHasBeenSet) { Value iKey(kStringType); string key = "PreferentialPolicyFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_preferentialPolicyFlag.c_str(), allocator).Move(), allocator); } if (m_zeroTaxFlagHasBeenSet) { Value iKey(kStringType); string key = "ZeroTaxFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_zeroTaxFlag.c_str(), allocator).Move(), allocator); } if (m_vatSpecialManagementHasBeenSet) { Value iKey(kStringType); string key = "VatSpecialManagement"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_vatSpecialManagement.c_str(), allocator).Move(), allocator); } } string CreateInvoiceItem::GetName() const { return m_name; } void CreateInvoiceItem::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool CreateInvoiceItem::NameHasBeenSet() const { return m_nameHasBeenSet; } string CreateInvoiceItem::GetTaxCode() const { return m_taxCode; } void CreateInvoiceItem::SetTaxCode(const string& _taxCode) { m_taxCode = _taxCode; m_taxCodeHasBeenSet = true; } bool CreateInvoiceItem::TaxCodeHasBeenSet() const { return m_taxCodeHasBeenSet; } int64_t CreateInvoiceItem::GetTotalPrice() const { return m_totalPrice; } void CreateInvoiceItem::SetTotalPrice(const int64_t& _totalPrice) { m_totalPrice = _totalPrice; m_totalPriceHasBeenSet = true; } bool CreateInvoiceItem::TotalPriceHasBeenSet() const { return m_totalPriceHasBeenSet; } int64_t CreateInvoiceItem::GetTaxRate() const { return m_taxRate; } void CreateInvoiceItem::SetTaxRate(const int64_t& _taxRate) { m_taxRate = _taxRate; m_taxRateHasBeenSet = true; } bool CreateInvoiceItem::TaxRateHasBeenSet() const { return m_taxRateHasBeenSet; } int64_t CreateInvoiceItem::GetTaxAmount() const { return m_taxAmount; } void CreateInvoiceItem::SetTaxAmount(const int64_t& _taxAmount) { m_taxAmount = _taxAmount; m_taxAmountHasBeenSet = true; } bool CreateInvoiceItem::TaxAmountHasBeenSet() const { return m_taxAmountHasBeenSet; } string CreateInvoiceItem::GetTaxType() const { return m_taxType; } void CreateInvoiceItem::SetTaxType(const string& _taxType) { m_taxType = _taxType; m_taxTypeHasBeenSet = true; } bool CreateInvoiceItem::TaxTypeHasBeenSet() const { return m_taxTypeHasBeenSet; } string CreateInvoiceItem::GetModels() const { return m_models; } void CreateInvoiceItem::SetModels(const string& _models) { m_models = _models; m_modelsHasBeenSet = true; } bool CreateInvoiceItem::ModelsHasBeenSet() const { return m_modelsHasBeenSet; } string CreateInvoiceItem::GetUnit() const { return m_unit; } void CreateInvoiceItem::SetUnit(const string& _unit) { m_unit = _unit; m_unitHasBeenSet = true; } bool CreateInvoiceItem::UnitHasBeenSet() const { return m_unitHasBeenSet; } string CreateInvoiceItem::GetTotal() const { return m_total; } void CreateInvoiceItem::SetTotal(const string& _total) { m_total = _total; m_totalHasBeenSet = true; } bool CreateInvoiceItem::TotalHasBeenSet() const { return m_totalHasBeenSet; } string CreateInvoiceItem::GetPrice() const { return m_price; } void CreateInvoiceItem::SetPrice(const string& _price) { m_price = _price; m_priceHasBeenSet = true; } bool CreateInvoiceItem::PriceHasBeenSet() const { return m_priceHasBeenSet; } int64_t CreateInvoiceItem::GetDiscount() const { return m_discount; } void CreateInvoiceItem::SetDiscount(const int64_t& _discount) { m_discount = _discount; m_discountHasBeenSet = true; } bool CreateInvoiceItem::DiscountHasBeenSet() const { return m_discountHasBeenSet; } string CreateInvoiceItem::GetPreferentialPolicyFlag() const { return m_preferentialPolicyFlag; } void CreateInvoiceItem::SetPreferentialPolicyFlag(const string& _preferentialPolicyFlag) { m_preferentialPolicyFlag = _preferentialPolicyFlag; m_preferentialPolicyFlagHasBeenSet = true; } bool CreateInvoiceItem::PreferentialPolicyFlagHasBeenSet() const { return m_preferentialPolicyFlagHasBeenSet; } string CreateInvoiceItem::GetZeroTaxFlag() const { return m_zeroTaxFlag; } void CreateInvoiceItem::SetZeroTaxFlag(const string& _zeroTaxFlag) { m_zeroTaxFlag = _zeroTaxFlag; m_zeroTaxFlagHasBeenSet = true; } bool CreateInvoiceItem::ZeroTaxFlagHasBeenSet() const { return m_zeroTaxFlagHasBeenSet; } string CreateInvoiceItem::GetVatSpecialManagement() const { return m_vatSpecialManagement; } void CreateInvoiceItem::SetVatSpecialManagement(const string& _vatSpecialManagement) { m_vatSpecialManagement = _vatSpecialManagement; m_vatSpecialManagementHasBeenSet = true; } bool CreateInvoiceItem::VatSpecialManagementHasBeenSet() const { return m_vatSpecialManagementHasBeenSet; }
CoreInternalOutcome CreateInvoiceItem::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Name") && !value["Name"].IsNull()) { if (!value["Name"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Name` IsString=false incorrectly").SetRequestId(requestId)); } m_name = string(value["Name"].GetString()); m_nameHasBeenSet = true; } if (value.HasMember("TaxCode") && !value["TaxCode"].IsNull()) { if (!value["TaxCode"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxCode` IsString=false incorrectly").SetRequestId(requestId)); } m_taxCode = string(value["TaxCode"].GetString()); m_taxCodeHasBeenSet = true; } if (value.HasMember("TotalPrice") && !value["TotalPrice"].IsNull()) { if (!value["TotalPrice"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TotalPrice` IsInt64=false incorrectly").SetRequestId(requestId)); } m_totalPrice = value["TotalPrice"].GetInt64(); m_totalPriceHasBeenSet = true; } if (value.HasMember("TaxRate") && !value["TaxRate"].IsNull()) { if (!value["TaxRate"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxRate` IsInt64=false incorrectly").SetRequestId(requestId)); } m_taxRate = value["TaxRate"].GetInt64(); m_taxRateHasBeenSet = true; } if (value.HasMember("TaxAmount") && !value["TaxAmount"].IsNull()) { if (!value["TaxAmount"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxAmount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_taxAmount = value["TaxAmount"].GetInt64(); m_taxAmountHasBeenSet = true; } if (value.HasMember("TaxType") && !value["TaxType"].IsNull()) { if (!value["TaxType"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.TaxType` IsString=false incorrectly").SetRequestId(requestId)); } m_taxType = string(value["TaxType"].GetString()); m_taxTypeHasBeenSet = true; } if (value.HasMember("Models") && !value["Models"].IsNull()) { if (!value["Models"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Models` IsString=false incorrectly").SetRequestId(requestId)); } m_models = string(value["Models"].GetString()); m_modelsHasBeenSet = true; } if (value.HasMember("Unit") && !value["Unit"].IsNull()) { if (!value["Unit"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Unit` IsString=false incorrectly").SetRequestId(requestId)); } m_unit = string(value["Unit"].GetString()); m_unitHasBeenSet = true; } if (value.HasMember("Total") && !value["Total"].IsNull()) { if (!value["Total"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Total` IsString=false incorrectly").SetRequestId(requestId)); } m_total = string(value["Total"].GetString()); m_totalHasBeenSet = true; } if (value.HasMember("Price") && !value["Price"].IsNull()) { if (!value["Price"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Price` IsString=false incorrectly").SetRequestId(requestId)); } m_price = string(value["Price"].GetString()); m_priceHasBeenSet = true; } if (value.HasMember("Discount") && !value["Discount"].IsNull()) { if (!value["Discount"].IsInt64()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.Discount` IsInt64=false incorrectly").SetRequestId(requestId)); } m_discount = value["Discount"].GetInt64(); m_discountHasBeenSet = true; } if (value.HasMember("PreferentialPolicyFlag") && !value["PreferentialPolicyFlag"].IsNull()) { if (!value["PreferentialPolicyFlag"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.PreferentialPolicyFlag` IsString=false incorrectly").SetRequestId(requestId)); } m_preferentialPolicyFlag = string(value["PreferentialPolicyFlag"].GetString()); m_preferentialPolicyFlagHasBeenSet = true; } if (value.HasMember("ZeroTaxFlag") && !value["ZeroTaxFlag"].IsNull()) { if (!value["ZeroTaxFlag"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.ZeroTaxFlag` IsString=false incorrectly").SetRequestId(requestId)); } m_zeroTaxFlag = string(value["ZeroTaxFlag"].GetString()); m_zeroTaxFlagHasBeenSet = true; } if (value.HasMember("VatSpecialManagement") && !value["VatSpecialManagement"].IsNull()) { if (!value["VatSpecialManagement"].IsString()) { return CoreInternalOutcome(Error("response `CreateInvoiceItem.VatSpecialManagement` IsString=false incorrectly").SetRequestId(requestId)); } m_vatSpecialManagement = string(value["VatSpecialManagement"].GetString()); m_vatSpecialManagementHasBeenSet = true; } return CoreInternalOutcome(true); }
function_block-full_function
[]
C++
src/tracking/multi_tracker.cpp
PPokorski/laser_object_tracker
bc967459218b417c7e0e97603464e77f110e25ef
#include "laser_object_tracker/tracking/multi_tracker.hpp" #include <numeric> namespace laser_object_tracker { namespace tracking { MultiTracker::MultiTracker(DistanceFunctor distance_calculator, std::unique_ptr<data_association::BaseDataAssociation> data_association, std::unique_ptr<BaseTracking> tracker_prototype, std::unique_ptr<BaseTrackerRejection> tracker_rejector_prototype) : distance_calculator_(std::move(distance_calculator)), data_association_(std::move(data_association)), tracker_prototype_(std::move(tracker_prototype)), tracker_rejector_prototype_(std::move(tracker_rejector_prototype)) {} void MultiTracker::predict() { for (auto& tracker : trackers_) { tracker->predict(); } } void MultiTracker::update(const std::vector<Eigen::VectorXd>& measurements) { Eigen::MatrixXd cost_matrix = buildCostMatrix(measurements); Eigen::VectorXi assignment_vector = buildAssignmentVector(cost_matrix); updateAndInitializeTracks(measurements, assignment_vector); handleNotUpdatedTracks(assignment_vector); handleRejectedTracks(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::begin() const { return trackers_.begin(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::end() const { return trackers_.end(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::cbegin() const { return trackers_.cbegin(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::cend() const { return trackers_.cend(); } const BaseTracking& MultiTracker::at(int index) const { return *trackers_.at(index); } int MultiTracker::size() const { return trackers_.size(); } Eigen::MatrixXd MultiTracker::buildCostMatrix(const std::vector<Eigen::VectorXd>& measurements) { Eigen::MatrixXd cost_matrix(trackers_.size(), measurements.size()); for (int row = 0; row < cost_matrix.rows(); ++row) { for (int col = 0; col < cost_matrix.cols(); ++col) { cost_matrix(row, col) = distance_calculator_(measurements.at(col), *trackers_.at(row)); } } return cost_matrix; } Eigen::VectorXi MultiTracker::buildAssignmentVector(const Eigen::MatrixXd& cost_matrix) { Eigen::VectorXi assignment_vector; data_association_->solve(cost_matrix, data_association_->NOT_NEEDED, assignment_vector); return assignment_vector; } void MultiTracker::updateAndInitializeTracks(const std::vector<Eigen::VectorXd>& measurements, const Eigen::VectorXi& assignment_vector) { for (int i = 0; i < measurements.size(); ++i) { if (assignment_vector(i) != data_association_->NO_ASSIGNMENT) { int tracker_index = assignment_vector(i); trackers_.at(tracker_index)->update(measurements.at(i)); trackers_rejections_.at(tracker_index)->updated(*trackers_.at(tracker_index)); } else { trackers_.push_back(std::move(tracker_prototype_->clone())); trackers_.back()->initFromMeasurement(measurements.at(i)); trackers_rejections_.push_back(std::move(tracker_rejector_prototype_->clone())); } } } void MultiTracker::handleNotUpdatedTracks(const Eigen::VectorXi& assignment_vector) { std::vector<int> trackers_indices(trackers_.size()); std::iota(trackers_indices.begin(), trackers_indices.end(), 0); std::vector<int> updated_trackers(assignment_vector.data(), assignment_vector.data() + assignment_vector.size()); std::sort(updated_trackers.begin(), updated_trackers.end()); std::vector<int> not_updated_trackers; not_updated_trackers.reserve(trackers_indices.size()); std::set_difference(trackers_indices.begin(), trackers_indices.end(), updated_trackers.begin(), updated_trackers.end(), std::back_inserter(not_updated_trackers)); for (int index : not_updated_trackers) { trackers_rejections_.at(index)->notUpdated(*trackers_.at(index)); } } void MultiTracker::handleRejectedTracks() { auto trackers_it = trackers_.cbegin(); auto rejectors_it = trackers_rejections_.cbegin(); for (; trackers_it != trackers_.cend(); ) { const auto& tracker = **trackers_it; const auto& rejector = **rejectors_it; if (rejector.invalidate(tracker)) { trackers_it = trackers_.erase(trackers_it); rejectors_it = trackers_rejections_.erase(rejectors_it); } else { ++trackers_it; ++rejectors_it; } } } } }
#include "laser_object_tracker/tracking/multi_tracker.hpp" #include <numeric> namespace laser_object_tracker { namespace tracking { MultiTracker::MultiTracker(DistanceFunctor distance_calculator, std::unique_ptr<data_association::BaseDataAssociation> data_association, std::unique_ptr<BaseTracking> tracker_prototype, std::unique_ptr<BaseTrackerRejection> tracker_rejector_prototype) : distance_calculator_(std::move(distance_calculator)), data_association_(std::move(data_association)), tracker_prototype_(std::move(tracker_prototype)), tracker_rejector_prototype_(std::move(tracker_rejector_prototype)) {} void MultiTracker::predict() { for (auto& tracker : trackers_) { tracker->predict(); } } void MultiTracker::update(const std::vector<Eigen::VectorXd>& measurements) { Eigen::MatrixXd cost_matrix = buildCostMatrix(measurements); Eigen::VectorXi assignment_vector = buildAssignmentVector(cost_matrix); updateAndInitializeTracks(measurements, assignment_vector); handleNotUpdatedTracks(assignment_vector); handleRejectedTracks(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::begin() const { return trackers_.begin(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::end() const { return trackers_.end(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::cbegin() const { return trackers_.cbegin(); } std::vector<std::unique_ptr<BaseTracking>>::const_iterator MultiTracker::cend() const { return trackers_.cend(); } const BaseTracking& MultiTracker::at(int index) const { return *trackers_.at(index); } int MultiTracker::size() const { return trackers_.size(); } Eigen::MatrixXd MultiTracker::buildCostMatrix(const std::vector<Eigen::VectorXd>& measurements) { Eigen::MatrixXd cost_matrix(trackers_.size(), measurements.size()); for (int row = 0; row < cost_matrix.rows(); ++row) { for (int col = 0; col < cost_matrix.cols(); ++col) { cost_matrix(row, col) = distance_calculator_(measurements.at(col), *trackers_.at(row)); } } return cost_matrix; } Eigen::VectorXi MultiTracker::buildAssignmentVector(const Eigen::MatrixXd& cost_matrix) { Eigen::VectorXi assignment_vector; data_association_->solve(cost_matrix, data_association_->NOT_NEEDED, assignment_vector); return assignment_vector; } void MultiTracker::updateAndInitializeTracks(const std::vector<Eigen::VectorXd>& measurements, const Eigen::VectorXi& assignment_vector) { for (int i = 0; i < measurements.size(); ++i) { if (assignment_vector(i) != data_association_->NO_ASSIGNMENT) { int tracker_index = assignment_vector(i); trackers_.at(tracker_index)->update(measurements.at(i)); trackers_rejections_.at(tracker_index)->updated(*trackers_.at(tracker_index)); } else { trackers_.push_back(std::move(tracker_prototype_->clone())); trackers_.back()->initFromMeasurement(measurements.at(i)); trackers_rejections_.push_back(std::move(tracker_rejector_prototype_->clone())); } } }
void MultiTracker::handleRejectedTracks() { auto trackers_it = trackers_.cbegin(); auto rejectors_it = trackers_rejections_.cbegin(); for (; trackers_it != trackers_.cend(); ) { const auto& tracker = **trackers_it; const auto& rejector = **rejectors_it; if (rejector.invalidate(tracker)) { trackers_it = trackers_.erase(trackers_it); rejectors_it = trackers_rejections_.erase(rejectors_it); } else { ++trackers_it; ++rejectors_it; } } } } }
void MultiTracker::handleNotUpdatedTracks(const Eigen::VectorXi& assignment_vector) { std::vector<int> trackers_indices(trackers_.size()); std::iota(trackers_indices.begin(), trackers_indices.end(), 0); std::vector<int> updated_trackers(assignment_vector.data(), assignment_vector.data() + assignment_vector.size()); std::sort(updated_trackers.begin(), updated_trackers.end()); std::vector<int> not_updated_trackers; not_updated_trackers.reserve(trackers_indices.size()); std::set_difference(trackers_indices.begin(), trackers_indices.end(), updated_trackers.begin(), updated_trackers.end(), std::back_inserter(not_updated_trackers)); for (int index : not_updated_trackers) { trackers_rejections_.at(index)->notUpdated(*trackers_.at(index)); } }
function_block-full_function
[ { "content": "*\n\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\n* DISCLAIMED. IN NO EVENT SHALL THE COPYRIG...
C++
src/rendering/ui.cpp
hyp/Arpheg
78d142c15028da7c0c2ef4503bed6bcfd1ced67d
#include <limits> #include <string.h> #include "../core/assert.h" #include "../core/allocatorNew.h" #include "../core/bufferArray.h" #include "../services.h" #include "rendering.h" #include "ui.h" #include "../data/font/font.h" #include "2d.h" #include "text.h" #include "opengl/gl.h" namespace rendering { namespace ui { enum { NormalGeometry, TextGeometry, OutlinedTextGeometry }; Batch::Batch() : verticesSize(0),indicesSize(0),primitive(topology::Triangle),name("") { layer=depth = 0; } struct BatchImpl { uint32 layerDepth; core::BufferAllocator vertices; core::BufferAllocator indices; uint32 meshId; uint32 vertexSize; int pipelineId; const data::Font* font; uint32 textureId; BatchImpl(const Batch& batch); BatchImpl(const BatchImpl& other,uint32 layer,uint32 texture); inline bool operator < (const BatchImpl& other){ return this->layerDepth < other.layerDepth; } }; BatchImpl::BatchImpl(const Batch& batch) : vertices(batch.verticesSize?batch.verticesSize: 2048,services::threadSafeFrameAllocator(),core::BufferAllocator::GrowOnOverflow), indices(batch.indicesSize? batch.indicesSize: 1024,services::threadSafeFrameAllocator() ,core::BufferAllocator::GrowOnOverflow) { assert(batch.layer <= Batch::kMaxLayer); assert(batch.depth <= Batch::kMaxDepth); layerDepth = (batch.layer<<8) | batch.depth; meshId = 0; font = nullptr; textureId = 0; } BatchImpl::BatchImpl(const BatchImpl& other,uint32 layer,uint32 texture) : vertices(2048,services::threadSafeFrameAllocator(),core::BufferAllocator::GrowOnOverflow), indices( 1024,services::threadSafeFrameAllocator() ,core::BufferAllocator::GrowOnOverflow) { assert(layer <= Batch::kMaxLayer); layerDepth = (layer << 8) | (other.layerDepth & Batch::kMaxDepth); meshId = other.meshId; font = other.font; textureId = texture; vertexSize = other.vertexSize; pipelineId = other.pipelineId; } uint32 Service::registerBatch(const Batch& batch,int pipelineId,uint32 meshId ) { using namespace core::bufferArray; auto bimpl = new(batches_.allocate(sizeof(BatchImpl),alignof(BatchImpl))) BatchImpl(batch); bimpl->meshId = meshId; bimpl->vertexSize = meshes_[meshId].vertexSize; bimpl->pipelineId = pipelineId; return uint32(length<BatchImpl>(batches_)-1); } uint32 Service::cloneBatch(uint32 id,uint32 layerId,uint32 textureId) { using namespace core::bufferArray; auto bimpl = new(batches_.allocate(sizeof(BatchImpl),alignof(BatchImpl))) BatchImpl(nth<BatchImpl>(batches_,id),layerId,textureId); return uint32(length<BatchImpl>(batches_)-1); } struct BatchFontMapping { const data::Font* key; uint32 value; }; Service::UniquePipeline::UniquePipeline(Pipeline pipeline) :matrixConstant("matrix"),texturesConstant("textures") { this->pipeline = pipeline; } uint32 Service::uiPipeline(const rendering::Pipeline& pipeline) { for(uint32 i = 0;i<kMaxPipelines;++i){ if(pipelines_[i].pipeline == pipeline) return i; } for(uint32 dest = kMaxDefaultPipelines;dest<kMaxPipelines;++dest){ if(pipelines_[dest].pipeline == Pipeline::nullPipeline()){ pipelines_[dest] = UniquePipeline(pipeline); return dest; } } assertRelease(false && "Can't register a new ui pipeline!"); return 0; } uint32 Service::uiTexture (const rendering::Texture2D& texture) { for(uint32 i = 0;i<kMaxTextures;++i){ if(textures_[i] == texture) return i; } for(uint32 dest = 0;dest<kMaxTextures;++dest){ if(textures_[dest] == Texture2D::null()){ textures_[dest] = texture; return dest; } } assertRelease(false && "Can't register a new ui texture - need mores storage units!"); return 0; } bool Service::loadCorePipeline(int id,const char* name) { int& pipe = defaultPipelines_[id]; if(pipe == -1){ if(auto asset = services::data()->pipeline(services::data()->bundle("core",true),name,true)){ pipe = id; assert(pipelines_[id].pipeline == Pipeline::nullPipeline()); pipelines_[id] = UniquePipeline(asset->pipeline()); } else { pipe = -2; return false; } } return true; } uint32 Service::registerFontBatch(const data::Font* font) { if(font->renderingType() == text::fontType::Outlined) loadCorePipeline(OutlinedTextPipeline,"rendering.text.outlined.pipeline"); else loadCorePipeline(TextPipeline,"rendering.text.pipeline"); Batch batch; batch.name = "font"; batch.depth = Batch::kMaxDepth; auto id = registerBatch(batch, font->renderingType() == text::fontType::Outlined? OutlinedTextPipeline : TextPipeline, font->renderingType() == text::fontType::Outlined? OutlinedTextGeometry : TextGeometry); core::bufferArray::nth<BatchImpl>(batches_,id).font = font; BatchFontMapping map = {font,id}; core::bufferArray::add<BatchFontMapping>(fontBatches_,map); return id; } Batch::Geometry Service::allocate(uint32 layerId,const data::Font* font,uint32 vertexCount,uint32 indexCount) { uint32 batchId = 0xFFFF; using namespace core::bufferArray; for(const BatchFontMapping* i = begin<BatchFontMapping>(fontBatches_),*e = end<BatchFontMapping>(fontBatches_);i<e;++i){ if(i->key == font){ batchId = i->value; break; } } if(batchId == 0xFFFF) batchId = registerFontBatch(font); return allocate(layerId,batchId,0,vertexCount,indexCount); } Batch::Geometry Service::allocate(uint32 layerId,uint32 batchId,uint32 textureId,uint32 vertexCount,uint32 indexCount) { assert(batchId < core::bufferArray::length<BatchImpl>(batches_)); auto batch = core::bufferArray::begin<BatchImpl>(batches_) + batchId; if(batch->textureId != textureId){ batch = core::bufferArray::begin<BatchImpl>(batches_) + cloneBatch(batchId,layerId,textureId); } Batch::Geometry result = { batch->vertices.size()/batch->vertexSize, (float*)batch->vertices.allocate(batch->vertexSize*vertexCount), indexCount? (uint16*)batch->indices.allocate(sizeof(uint16)*indexCount) : nullptr }; return result; } static VertexDescriptor meshVertexDescriptor(uint32 i){ return i == NormalGeometry? draw2D::positionInt16::vertexLayout(draw2D::mode::Textured|draw2D::mode::Coloured) : i == TextGeometry? text::vertexLayout(text::fontType::Default) : text::vertexLayout(text::fontType::Outlined) ; } static uint32 vertexSize(uint32 i){ auto layout = meshVertexDescriptor(i); uint32 sz = 0; for(uint32 i = 0;i<layout.count;++i){ sz += layout.fields[i].size(); } return sz; } void Service::prepareRendering() { using namespace core::bufferArray; loadCorePipeline(TexturedColouredPipeline,"rendering.2d.textured.coloured.pipeline"); loadCorePipeline(ColouredPipeline,"rendering.2d.coloured.pipeline"); pointSampler_ = services::data()->sampler(services::data()->bundle("core",true),"rendering.sampler.point",true); fontSampler_ = pointSampler_; auto batchCount = length<BatchImpl>(batches_); uint32 storage[1024]; if(batchCount > (sizeof(storage)/sizeof(storage[0]))){ assert(false && "Can't sort the ui batches"); return; } for(size_t i = 0;i<batchCount;++i){ storage[i] = (uint32(i)<<16) | nth<BatchImpl>(batches_,i).layerDepth; } struct Pred{ inline bool operator ()(uint32 a,uint32 b) { return (a&0xFFFF) < (b&0xFFFF); } }; std::sort(storage,storage+batchCount,Pred()); } void Service::render(const mat44f& matrix) { auto renderer = services::rendering(); renderer->bind(blending::alpha()); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); using namespace core::bufferArray; struct MeshSupport { size_t requiredVertexSize; size_t requiredIndexSize; uint32 vertexOffset,indexOffset; Buffer::Mapping vertexMapping,indexMapping; bool justCreated; inline uint8* vertices(uint32 vertexSize){ return ((uint8*)vertexMapping.data) + vertexOffset*vertexSize; } inline uint8* indices(){ return ((uint8*)indexMapping.data) + indexOffset*sizeof(uint16); } }; MeshSupport meshSupport[kMaxGeometries]; struct BatchSupport { bool draw,indexed; uint32 baseVertex; uint32 offset,count; }; for(uint32 i = 0;i<kMaxGeometries;++i){ meshSupport[i].requiredVertexSize = meshSupport[i].requiredIndexSize = 0; meshSupport[i].justCreated = false; } for(BatchImpl* i = begin<BatchImpl>(batches_),*e = end<BatchImpl>(batches_);i<e;++i){ meshSupport[i->meshId].requiredVertexSize+= i->vertices.size(); meshSupport[i->meshId].requiredIndexSize += i->indices.size(); } for(uint32 i = 0;i<kMaxGeometries;++i){ auto mesh = meshes_ + i; if(mesh->vbo.isNull()){ mesh->vbo = renderer->create(rendering::Buffer::Vertex,true,meshSupport[i].requiredVertexSize); mesh->ibo = renderer->create(rendering::Buffer::Index,true,meshSupport[i].requiredIndexSize); mesh->mesh = renderer->create(mesh->vbo,mesh->ibo,meshVertexDescriptor(i)); meshSupport[i].justCreated = true; } } size_t batchCount = length<BatchImpl>(batches_); BatchSupport* batchSupport = (BatchSupport*)services::frameAllocator()->allocate(sizeof(BatchSupport)*batchCount,alignof(BatchSupport)); for(uint32 i = 0;i<kMaxGeometries;++i){ auto mesh = meshes_ + i; if(!meshSupport[i].justCreated){ renderer->recreate(rendering::Buffer::Vertex,mesh->vbo,true,meshSupport[i].requiredVertexSize); renderer->recreate(rendering::Buffer::Index,mesh->ibo,true,meshSupport[i].requiredIndexSize); } if(meshSupport[i].requiredVertexSize > 0){ meshSupport[i].vertexMapping = renderer->map(rendering::Buffer::Vertex,mesh->vbo); meshSupport[i].vertexOffset = 0; } if(meshSupport[i].requiredIndexSize > 0){ meshSupport[i].indexMapping = renderer->map(rendering::Buffer::Index,mesh->ibo); meshSupport[i].indexOffset = 0; } } for(size_t i = 0;i<batchCount;++i){ const BatchImpl* batch = begin<BatchImpl>(batches_) + i; BatchSupport support; support.draw = false; if(batch->vertices.size()){ support.baseVertex = meshSupport[batch->meshId].vertexOffset; support.draw = true; memcpy(meshSupport[batch->meshId].vertices(batch->vertexSize),batch->vertices.bufferBase(),batch->vertices.size()); support.offset = uint32(meshSupport[batch->meshId].vertexOffset); uint32 vertexCount = uint32(batch->vertices.size()/batch->vertexSize); support.count = vertexCount; meshSupport[batch->meshId].vertexOffset+=vertexCount; } if(batch->indices.size()){ support.indexed = true; memcpy(meshSupport[batch->meshId].indices(),batch->indices.bufferBase(),batch->indices.size()); support.offset = uint32(meshSupport[batch->meshId].indexOffset)*sizeof(uint16); uint32 indexCount = uint32(batch->indices.size()/sizeof(uint16)); support.count = indexCount; meshSupport[batch->meshId].indexOffset+=indexCount; } batchSupport[i] = support; } for(uint32 i = 0;i<kMaxGeometries;++i){ if(meshSupport[i].requiredVertexSize > 0) renderer->unmap(meshSupport[i].vertexMapping); if(meshSupport[i].requiredIndexSize > 0) renderer->unmap(meshSupport[i].indexMapping); } if(!(textures_[0] == Texture2D::null())){ renderer->bind(textures_[0],0); renderer->bind(pointSampler_,0); } uint32 currentBoundMesh = kMaxGeometries; Pipeline currentBoundPipeline = Pipeline::nullPipeline(); bool constantsBound[kMaxPipelines] = {false}; bool textureUnitsBound[kMaxPipelines] = {false}; for(size_t i = 0;i<batchCount;++i){ if(!batchSupport[i].draw) continue; const BatchImpl* batch = begin<BatchImpl>(batches_) + i; if(!(pipelines_[batch->pipelineId].pipeline == currentBoundPipeline)){ renderer->bind(pipelines_[batch->pipelineId].pipeline); if(!constantsBound[batch->pipelineId]){ renderer->bind(pipelines_[batch->pipelineId].matrixConstant,matrix); constantsBound[batch->pipelineId] = true; } if(batch->font){ int fontTextureUnit = 2; renderer->bind(batch->font->pages_[0],fontTextureUnit); renderer->bind(fontSampler_,fontTextureUnit); renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&fontTextureUnit); } else { if(batch->textureId != 0){ int unit = 1; renderer->bind(textures_[batch->textureId],unit); renderer->bind(pointSampler_,unit); renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&unit); textureUnitsBound[batch->pipelineId] = false; } else if(!textureUnitsBound[batch->pipelineId]) { int unit = 0 ; renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&unit); textureUnitsBound[batch->pipelineId] = true; } } } if(currentBoundMesh != batch->meshId){ renderer->bind(meshes_[batch->meshId].mesh,rendering::topology::Triangle,sizeof(uint16)); currentBoundMesh = batch->meshId; } if(batchSupport[i].indexed) renderer->drawIndexed(batchSupport[i].offset,batchSupport[i].count,batchSupport[i].baseVertex); else renderer->draw(batchSupport[i].offset,batchSupport[i].count); } glEnable(GL_DEPTH_TEST); renderer->bind(blending::disabled()); } void Service::servicePreStep(){ new(&fontBatches_) core::BufferAllocator(sizeof(BatchFontMapping)*32,services::frameAllocator(),core::BufferAllocator::GrowOnOverflow); new(&batches_) core::BufferAllocator(sizeof(BatchImpl)*64,services::frameAllocator(),core::BufferAllocator::GrowOnOverflow); for(uint32 dest = 0;dest<kMaxTextures;++dest){ textures_[dest] = Texture2D::null(); } } void Service::servicePostStep(){ } Service::Service() : batches_(128,services::frameAllocator()), fontBatches_(128,services::frameAllocator()) { for(uint32 i = 0;i<kMaxDefaultPipelines;++i) defaultPipelines_[i] = -1; for(uint32 i = 0; i<kMaxGeometries;++i){ meshes_[i].vertexSize = vertexSize(i); meshes_[i].vbo = meshes_[i].ibo = Buffer::nullBuffer(); } } Service::~Service(){ using namespace core::bufferArray; auto renderer = services::rendering(); for(uint32 i = 0; i<kMaxGeometries;++i){ if(!meshes_[i].vbo.isNull()){ renderer->release(meshes_[i].mesh); renderer->release(meshes_[i].vbo); if(meshes_[i].ibo.isNull()) renderer->release(meshes_[i].ibo); } } } } }
#include <limits> #include <string.h> #include "../core/assert.h" #include "../core/allocatorNew.h" #include "../core/bufferArray.h" #include "../services.h" #include "rendering.h" #include "ui.h" #include "../data/font/font.h" #include "2d.h" #include "text.h" #include "opengl/gl.h" namespace rendering { namespace ui { enum { NormalGeometry, TextGeometry, OutlinedTextGeometry }; Batch::Batch() : verticesSize(0),indicesSize(0),primitive(topology::Triangle),name("") { layer=depth = 0; } struct BatchImpl { uint32 layerDepth; core::BufferAllocator vertices; core::BufferAllocator indices; uint32 meshId; uint32 vertexSize; int pipelineId; const data::Font* font; uint32 textureId; BatchImpl(const Batch& batch); BatchImpl(const BatchImpl& other,uint32 layer,uint32 texture); inline bool operator < (const BatchImpl& other){ return this->layerDepth < other.layerDepth; } }; BatchImpl::BatchImpl(const Batch& batch) : vertices(batch.verticesSize?batch.verticesSize: 2048,services::threadSafeFrameAllocator(),core::BufferAllocator::GrowOnOverflow), indices(batch.indicesSize? batch.indicesSize: 1024,services::threadSafeFrameAllocator() ,core::BufferAllocator::GrowOnOverflow) { assert(batch.layer <= Batch::kMaxLayer); assert(batch.depth <= Batch::kMaxDepth); layerDepth = (batch.layer<<8) | batch.depth; meshId = 0; font = nullptr; textureId = 0; } BatchImpl::BatchImpl(const BatchImpl& other,uint32 layer,uint32 texture) : vertices(2048,services::threadSafeFrameAllocator(),core::BufferAllocator::GrowOnOverflow), indices( 1024,services::threadSafeFrameAllocator() ,core::BufferAllocator::GrowOnOverflow) { assert(layer <= Batch::kMaxLayer); layerDepth = (layer << 8) | (other.layerDepth & Batch::kMaxDepth); meshId = other.meshId; font = other.font; textureId = texture; vertexSize = other.vertexSize; pipelineId = other.pipelineId; } uint32 Service::registerBatch(const Batch& batch,int pipelineId,uint32 meshId ) { using namespace core::bufferArray; auto bimpl = new(batches_.allocate(sizeof(BatchImpl),alignof(BatchImpl))) BatchImpl(batch); bimpl->meshId = meshId; bimpl->vertexSize = meshes_[meshId].vertexSize; bimpl->pipelineId = pipelineId; return uint32(length<BatchImpl>(batches_)-1); } uint32 Service::cloneBatch(uint32 id,uint32 layerId,uint32 textureId) { using namespace core::bufferArray; auto bimpl = new(batches_.allocate(sizeof(BatchImpl),alignof(BatchImpl))) BatchImpl(nth<BatchImpl>(batches_,id),layerId,textureId); return uint32(length<BatchImpl>(batches_)-1); } struct BatchFontMapping { const data::Font* key; uint32 value; }; Service::UniquePipeline::UniquePipeline(Pipeline pipeline) :matrixConstant("matrix"),texturesConstant("textures") { this->pipeline = pipeline; } uint32 Service::uiPipeline(const rendering::Pipeline& pipeline) { for(uint32 i = 0;i<kMaxPipelines;++i){ if(pipelines_[i].pipeline == pipeline) return i; } for(uint32 dest = kMaxDefaultPipelines;dest<kMaxPipelines;++dest){ if(pipelines_[dest].pipeline == Pipeline::nullPipeline()){ pipelines_[dest] = UniquePipeline(pipeline); return dest; } } assertRelease(false && "Can't register a new ui pipeline!"); return 0; } uint32 Service::uiTexture (const rendering::Texture2D& texture) { for(uint32 i = 0;i<kMaxTextures;++i){ if(textures_[i] == texture) return i; } for(uint32 dest = 0;dest<kMaxTextures;++dest){ if(textures_[dest] == Texture2D::null()){ textures_[dest] = texture; return dest; } } assertRelease(false && "Can't register a new ui texture - need mores storage units!"); return 0; } bool Service::loadCorePipeline(int id,const char* name) { int& pipe = defaultPipelines_[id]; if(pipe == -1){ if(auto asset = services::data()->pipeline(services::data()->bundle("core",true),name,true)){ pipe = id; assert(pipelines_[id].pipeline == Pipeline::nullPipeline()); pipelines_[id] = UniquePipeline(asset->pipeline()); } else { pipe = -2; return false; } } return true; } uint32 Service::registerFontBatch(const data::Font* font) { if(font->renderingType() == text::fontType::Outlined) loadCorePipeline(OutlinedTextPipeline,"rendering.text.outlined.pipeline"); else loadCorePipeline(TextPipeline,"rendering.text.pipeline"); Batch batch; batch.name = "font"; batch.depth = Batch::kMaxDepth; auto id =
; core::bufferArray::nth<BatchImpl>(batches_,id).font = font; BatchFontMapping map = {font,id}; core::bufferArray::add<BatchFontMapping>(fontBatches_,map); return id; } Batch::Geometry Service::allocate(uint32 layerId,const data::Font* font,uint32 vertexCount,uint32 indexCount) { uint32 batchId = 0xFFFF; using namespace core::bufferArray; for(const BatchFontMapping* i = begin<BatchFontMapping>(fontBatches_),*e = end<BatchFontMapping>(fontBatches_);i<e;++i){ if(i->key == font){ batchId = i->value; break; } } if(batchId == 0xFFFF) batchId = registerFontBatch(font); return allocate(layerId,batchId,0,vertexCount,indexCount); } Batch::Geometry Service::allocate(uint32 layerId,uint32 batchId,uint32 textureId,uint32 vertexCount,uint32 indexCount) { assert(batchId < core::bufferArray::length<BatchImpl>(batches_)); auto batch = core::bufferArray::begin<BatchImpl>(batches_) + batchId; if(batch->textureId != textureId){ batch = core::bufferArray::begin<BatchImpl>(batches_) + cloneBatch(batchId,layerId,textureId); } Batch::Geometry result = { batch->vertices.size()/batch->vertexSize, (float*)batch->vertices.allocate(batch->vertexSize*vertexCount), indexCount? (uint16*)batch->indices.allocate(sizeof(uint16)*indexCount) : nullptr }; return result; } static VertexDescriptor meshVertexDescriptor(uint32 i){ return i == NormalGeometry? draw2D::positionInt16::vertexLayout(draw2D::mode::Textured|draw2D::mode::Coloured) : i == TextGeometry? text::vertexLayout(text::fontType::Default) : text::vertexLayout(text::fontType::Outlined) ; } static uint32 vertexSize(uint32 i){ auto layout = meshVertexDescriptor(i); uint32 sz = 0; for(uint32 i = 0;i<layout.count;++i){ sz += layout.fields[i].size(); } return sz; } void Service::prepareRendering() { using namespace core::bufferArray; loadCorePipeline(TexturedColouredPipeline,"rendering.2d.textured.coloured.pipeline"); loadCorePipeline(ColouredPipeline,"rendering.2d.coloured.pipeline"); pointSampler_ = services::data()->sampler(services::data()->bundle("core",true),"rendering.sampler.point",true); fontSampler_ = pointSampler_; auto batchCount = length<BatchImpl>(batches_); uint32 storage[1024]; if(batchCount > (sizeof(storage)/sizeof(storage[0]))){ assert(false && "Can't sort the ui batches"); return; } for(size_t i = 0;i<batchCount;++i){ storage[i] = (uint32(i)<<16) | nth<BatchImpl>(batches_,i).layerDepth; } struct Pred{ inline bool operator ()(uint32 a,uint32 b) { return (a&0xFFFF) < (b&0xFFFF); } }; std::sort(storage,storage+batchCount,Pred()); } void Service::render(const mat44f& matrix) { auto renderer = services::rendering(); renderer->bind(blending::alpha()); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); using namespace core::bufferArray; struct MeshSupport { size_t requiredVertexSize; size_t requiredIndexSize; uint32 vertexOffset,indexOffset; Buffer::Mapping vertexMapping,indexMapping; bool justCreated; inline uint8* vertices(uint32 vertexSize){ return ((uint8*)vertexMapping.data) + vertexOffset*vertexSize; } inline uint8* indices(){ return ((uint8*)indexMapping.data) + indexOffset*sizeof(uint16); } }; MeshSupport meshSupport[kMaxGeometries]; struct BatchSupport { bool draw,indexed; uint32 baseVertex; uint32 offset,count; }; for(uint32 i = 0;i<kMaxGeometries;++i){ meshSupport[i].requiredVertexSize = meshSupport[i].requiredIndexSize = 0; meshSupport[i].justCreated = false; } for(BatchImpl* i = begin<BatchImpl>(batches_),*e = end<BatchImpl>(batches_);i<e;++i){ meshSupport[i->meshId].requiredVertexSize+= i->vertices.size(); meshSupport[i->meshId].requiredIndexSize += i->indices.size(); } for(uint32 i = 0;i<kMaxGeometries;++i){ auto mesh = meshes_ + i; if(mesh->vbo.isNull()){ mesh->vbo = renderer->create(rendering::Buffer::Vertex,true,meshSupport[i].requiredVertexSize); mesh->ibo = renderer->create(rendering::Buffer::Index,true,meshSupport[i].requiredIndexSize); mesh->mesh = renderer->create(mesh->vbo,mesh->ibo,meshVertexDescriptor(i)); meshSupport[i].justCreated = true; } } size_t batchCount = length<BatchImpl>(batches_); BatchSupport* batchSupport = (BatchSupport*)services::frameAllocator()->allocate(sizeof(BatchSupport)*batchCount,alignof(BatchSupport)); for(uint32 i = 0;i<kMaxGeometries;++i){ auto mesh = meshes_ + i; if(!meshSupport[i].justCreated){ renderer->recreate(rendering::Buffer::Vertex,mesh->vbo,true,meshSupport[i].requiredVertexSize); renderer->recreate(rendering::Buffer::Index,mesh->ibo,true,meshSupport[i].requiredIndexSize); } if(meshSupport[i].requiredVertexSize > 0){ meshSupport[i].vertexMapping = renderer->map(rendering::Buffer::Vertex,mesh->vbo); meshSupport[i].vertexOffset = 0; } if(meshSupport[i].requiredIndexSize > 0){ meshSupport[i].indexMapping = renderer->map(rendering::Buffer::Index,mesh->ibo); meshSupport[i].indexOffset = 0; } } for(size_t i = 0;i<batchCount;++i){ const BatchImpl* batch = begin<BatchImpl>(batches_) + i; BatchSupport support; support.draw = false; if(batch->vertices.size()){ support.baseVertex = meshSupport[batch->meshId].vertexOffset; support.draw = true; memcpy(meshSupport[batch->meshId].vertices(batch->vertexSize),batch->vertices.bufferBase(),batch->vertices.size()); support.offset = uint32(meshSupport[batch->meshId].vertexOffset); uint32 vertexCount = uint32(batch->vertices.size()/batch->vertexSize); support.count = vertexCount; meshSupport[batch->meshId].vertexOffset+=vertexCount; } if(batch->indices.size()){ support.indexed = true; memcpy(meshSupport[batch->meshId].indices(),batch->indices.bufferBase(),batch->indices.size()); support.offset = uint32(meshSupport[batch->meshId].indexOffset)*sizeof(uint16); uint32 indexCount = uint32(batch->indices.size()/sizeof(uint16)); support.count = indexCount; meshSupport[batch->meshId].indexOffset+=indexCount; } batchSupport[i] = support; } for(uint32 i = 0;i<kMaxGeometries;++i){ if(meshSupport[i].requiredVertexSize > 0) renderer->unmap(meshSupport[i].vertexMapping); if(meshSupport[i].requiredIndexSize > 0) renderer->unmap(meshSupport[i].indexMapping); } if(!(textures_[0] == Texture2D::null())){ renderer->bind(textures_[0],0); renderer->bind(pointSampler_,0); } uint32 currentBoundMesh = kMaxGeometries; Pipeline currentBoundPipeline = Pipeline::nullPipeline(); bool constantsBound[kMaxPipelines] = {false}; bool textureUnitsBound[kMaxPipelines] = {false}; for(size_t i = 0;i<batchCount;++i){ if(!batchSupport[i].draw) continue; const BatchImpl* batch = begin<BatchImpl>(batches_) + i; if(!(pipelines_[batch->pipelineId].pipeline == currentBoundPipeline)){ renderer->bind(pipelines_[batch->pipelineId].pipeline); if(!constantsBound[batch->pipelineId]){ renderer->bind(pipelines_[batch->pipelineId].matrixConstant,matrix); constantsBound[batch->pipelineId] = true; } if(batch->font){ int fontTextureUnit = 2; renderer->bind(batch->font->pages_[0],fontTextureUnit); renderer->bind(fontSampler_,fontTextureUnit); renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&fontTextureUnit); } else { if(batch->textureId != 0){ int unit = 1; renderer->bind(textures_[batch->textureId],unit); renderer->bind(pointSampler_,unit); renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&unit); textureUnitsBound[batch->pipelineId] = false; } else if(!textureUnitsBound[batch->pipelineId]) { int unit = 0 ; renderer->bind(pipelines_[batch->pipelineId].texturesConstant,&unit); textureUnitsBound[batch->pipelineId] = true; } } } if(currentBoundMesh != batch->meshId){ renderer->bind(meshes_[batch->meshId].mesh,rendering::topology::Triangle,sizeof(uint16)); currentBoundMesh = batch->meshId; } if(batchSupport[i].indexed) renderer->drawIndexed(batchSupport[i].offset,batchSupport[i].count,batchSupport[i].baseVertex); else renderer->draw(batchSupport[i].offset,batchSupport[i].count); } glEnable(GL_DEPTH_TEST); renderer->bind(blending::disabled()); } void Service::servicePreStep(){ new(&fontBatches_) core::BufferAllocator(sizeof(BatchFontMapping)*32,services::frameAllocator(),core::BufferAllocator::GrowOnOverflow); new(&batches_) core::BufferAllocator(sizeof(BatchImpl)*64,services::frameAllocator(),core::BufferAllocator::GrowOnOverflow); for(uint32 dest = 0;dest<kMaxTextures;++dest){ textures_[dest] = Texture2D::null(); } } void Service::servicePostStep(){ } Service::Service() : batches_(128,services::frameAllocator()), fontBatches_(128,services::frameAllocator()) { for(uint32 i = 0;i<kMaxDefaultPipelines;++i) defaultPipelines_[i] = -1; for(uint32 i = 0; i<kMaxGeometries;++i){ meshes_[i].vertexSize = vertexSize(i); meshes_[i].vbo = meshes_[i].ibo = Buffer::nullBuffer(); } } Service::~Service(){ using namespace core::bufferArray; auto renderer = services::rendering(); for(uint32 i = 0; i<kMaxGeometries;++i){ if(!meshes_[i].vbo.isNull()){ renderer->release(meshes_[i].mesh); renderer->release(meshes_[i].vbo); if(meshes_[i].ibo.isNull()) renderer->release(meshes_[i].ibo); } } } } }
registerBatch(batch, font->renderingType() == text::fontType::Outlined? OutlinedTextPipeline : TextPipeline, font->renderingType() == text::fontType::Outlined? OutlinedTextGeometry : TextGeometry)
call_expression
[ { "content": "struct Batch {\n\n\tenum { kMaxLayer = 0xFF };\n\n\tenum { kMaxDepth = 0xFF };\n\n\n\n\ttypedef batching::Geometry Geometry;\n\n\n\n\tsize_t verticesSize,indicesSize;\n\n\ttopology::Primitive primitive;\n\n\tconst char* name;\n\n\tuint32 layer,depth;//Batches are sorted by depth and layers.\n\n\n\...